Skip to content

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

✨ feat(agent-identity): wake on mail by rules, fold the rest into a digest (#22555)

Arvin Xuc40b59c8b523
diff --git a/apps/cli/src/commands/agent/account.ts b/apps/cli/src/commands/agent/account.ts
index 7d90fbba7df..c708628a00a 100644
--- a/apps/cli/src/commands/agent/account.ts
+++ b/apps/cli/src/commands/agent/account.ts
@@ -17,6 +17,7 @@ import { readFileSync } from 'node:fs';
import { text } from 'node:stream/consumers';
import type { Command } from 'commander';
+import { InvalidArgumentError } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../../api/client';
@@ -44,7 +45,9 @@ const parseCapabilities = (value: string) => {
const known = ['login', 'receive', 'send', 'sign'];
const unknown = [...granted].filter((item) => !known.includes(item));
if (unknown.length > 0) {
- throw new Error(`Unknown capability: ${unknown.join(', ')}. Valid values: ${known.join(', ')}.`);
+ throw new Error(
+ `Unknown capability: ${unknown.join(', ')}. Valid values: ${known.join(', ')}.`,
+ );
}
return {
@@ -65,6 +68,29 @@ const readJsonObject = async (source: string, label: string): Promise<Record<str
};
/** `key=value` pairs from a repeatable option. */
+const WAKE_MODES = ['on', 'off'] as const;
+type WakeMode = (typeof WAKE_MODES)[number];
+
+const parseWakeMode = (value: string): WakeMode => {
+ if ((WAKE_MODES as readonly string[]).includes(value)) return value as WakeMode;
+ throw new InvalidArgumentError(`Expected one of: ${WAKE_MODES.join(', ')}`);
+};
+
+const parseMinutes = (value: string): number => {
+ const minutes = Number(value);
+ if (!Number.isInteger(minutes) || minutes <= 0) {
+ throw new InvalidArgumentError('Expected a whole number of minutes');
+ }
+ return minutes;
+};
+
+/** Comma-separated addresses or `@domain`s; `""` clears the list. */
+const parseSenders = (value: string): string[] =>
+ value
+ .split(',')
+ .map((sender) => sender.trim())
+ .filter(Boolean);
+
const collectPair = (value: string, previous: Record<string, string> = {}) => {
const index = value.indexOf('=');
if (index <= 0) throw new Error(`Expected key=value, got: ${value}`);
@@ -187,6 +213,12 @@ export function registerAgentAccountCommand(agent: Command) {
if (item.credentialHint?.username) {
console.log(` Username: ${item.credentialHint.username}`);
}
+ const wake = item.settings?.wake;
+ console.log(` Wake: ${wake?.mode ?? 'on'}`);
+ if (wake?.wakeSenders?.length) {
+ console.log(` Senders: ${wake.wakeSenders.join(', ')}`);
+ }
+ if (wake?.digestMinutes) console.log(` Digest: every ${wake.digestMinutes} min`);
if (item.createdAt) console.log(` Created: ${timeAgo(item.createdAt)}`);
});
@@ -304,19 +336,38 @@ export function registerAgentAccountCommand(agent: Command) {
parseCapabilities,
)
.option('--metadata-file <path>', 'JSON object of non-secret metadata ("-" for stdin)')
+ .option(
+ '--wake <mode>',
+ 'on: listed senders and replies to the agent wake it at once, the rest waits for the digest; off: never wake',
+ parseWakeMode,
+ )
+ .option(
+ '--wake-senders <list>',
+ 'Comma-separated senders that wake the agent at once: addresses or @domains ("" to clear)',
+ parseSenders,
+ )
+ .option(
+ '--digest-minutes <minutes>',
+ 'How long the digest collects held messages',
+ parseMinutes,
+ )
.action(
async (
accountId: string,
options: {
capabilities?: ReturnType<typeof parseCapabilities>;
+ digestMinutes?: number;
displayName?: string;
metadataFile?: string;
+ wake?: WakeMode;
+ wakeSenders?: string[];
},
) => {
const patch: {
capabilities?: ReturnType<typeof parseCapabilities>;
displayName?: string | null;
metadata?: Record<string, unknown>;
+ settings?: Record<string, any>;
} = {};
if (options.displayName !== undefined) patch.displayName = options.displayName || null;
if (options.capabilities) patch.capabilities = options.capabilities;
@@ -324,13 +375,28 @@ export function registerAgentAccountCommand(agent: Command) {
patch.metadata = await readJsonObject(options.metadataFile, 'metadata');
}
+ const client = await getTrpcClient();
+
+ const wakePatch = {
+ ...(options.wake ? { mode: options.wake } : {}),
+ ...(options.wakeSenders ? { wakeSenders: options.wakeSenders } : {}),
+ ...(options.digestMinutes ? { digestMinutes: options.digestMinutes } : {}),
+ };
+ if (Object.keys(wakePatch).length > 0) {
+ // Settings are written whole: start from what the account holds now.
+ const current: any = await client.agentAccount.get.query({ id: accountId });
+ const settings = current?.settings ?? {};
+ patch.settings = { ...settings, wake: { ...settings.wake, ...wakePatch } };
+ }
+
if (Object.keys(patch).length === 0) {
- log.error('Nothing to update. Pass --display-name, --capabilities or --metadata-file.');
+ log.error(
+ 'Nothing to update. Pass --display-name, --capabilities, --metadata-file, --wake, --wake-senders or --digest-minutes.',
+ );
process.exit(1);
return;
}
- const client = await getTrpcClient();
await client.agentAccount.update.mutate({ id: accountId, ...patch });
console.log(`${pc.green('βœ“')} Updated account ${pc.bold(accountId)}`);
},
@@ -558,7 +624,9 @@ export function registerAgentInboxCommand(agent: Command) {
}
if (message.threadKey) console.log(` Thread: ${message.threadKey}`);
if (message.attachments?.length) {
- const names = message.attachments.map((file: any) => file.filename || `#${file.index}`).join(', ');
+ const names = message.attachments
+ .map((file: any) => file.filename || `#${file.index}`)
+ .join(', ');
console.log(` Files: ${names}`);
}
console.log(
diff --git a/apps/server/src/router-hono/agent/handlers/agentAccountDigestFlush.ts b/apps/server/src/router-hono/agent/handlers/agentAccountDigestFlush.ts
new file mode 100644
index 00000000000..7c0c4af1f4f
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/agentAccountDigestFlush.ts
@@ -0,0 +1,35 @@
+import type { Context } from 'hono';
+import { z } from 'zod';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { runDigestFlush } from '@/server/services/agentIdentity/wake/digest';
+
+const payloadSchema = z.object({
+ payload: z.object({
+ accountId: z.string().uuid(),
+ at: z.number(),
+ }),
+});
+
+/**
+ * The mail digest's delayed trigger: runs what one account held back since the last digest.
+ * QStash can deliver it more than once; the second delivery finds the items already claimed.
+ */
+export async function agentAccountDigestFlush(c: Context): Promise<Response> {
+ const body = payloadSchema.safeParse(await c.req.json().catch(() => null));
+ if (!body.success) return c.json({ error: 'Invalid digest flush payload' }, 400);
+
+ try {
+ const result = await runDigestFlush(await getServerDB(), body.data.payload);
+
+ return c.json({ result, success: true });
+ } catch (error) {
+ console.error(
+ '[agentAccountDigestFlush] flush failed for %s:',
+ body.data.payload.accountId,
+ error,
+ );
+ // A 5xx makes QStash retry the flush; the items it claimed were given back.
+ return c.json({ error: 'Digest flush failed' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.ts
index 9aee6917484..dd3dfda7e4c 100644
--- a/apps/server/src/router-hono/agent/index.ts
+++ b/apps/server/src/router-hono/agent/index.ts
@@ -1,5 +1,6 @@
import { Hono } from 'hono';
+import { agentAccountDigestFlush } from './handlers/agentAccountDigestFlush';
import { agentAccountWebhook, agentAccountWebhookBodyLimit } from './handlers/agentAccountWebhook';
import { botCallback } from './handlers/botCallback';
import { botReplay } from './handlers/botReplay';
@@ -128,6 +129,10 @@ app.post('/webhooks/:platform/:appId?', platformWebhook);
// is buffered.
app.post('/accounts/webhooks/:provider', agentAccountWebhookBodyLimit, agentAccountWebhook);
+// POST /api/agent/accounts/digest-flush β€” delayed run of the mail held for one
+// account's digest (QStash)
+app.post('/accounts/digest-flush', qstashAuth(), agentAccountDigestFlush);
+
// GET /api/agent/messenger/:platform/install β€” start per-tenant OAuth install
app.get('/messenger/:platform/install', messengerInstall);
diff --git a/apps/server/src/routers/lambda/agentAccount.ts b/apps/server/src/routers/lambda/agentAccount.ts
index f97aebe2da6..e0099ba99a8 100644
--- a/apps/server/src/routers/lambda/agentAccount.ts
+++ b/apps/server/src/routers/lambda/agentAccount.ts
@@ -12,6 +12,7 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { AgentAccountService, isAgentAccountError } from '@/server/services/agentIdentity';
import { createDefaultAgentAccountRegistry } from '@/server/services/agentIdentity/providers';
+import { agentAccountSettingsSchema } from '@/server/services/agentIdentity/wake/config';
import { assertCanEditResource } from '@/server/services/resourcePermission';
/**
@@ -266,6 +267,8 @@ export const agentAccountRouter = router({
capabilities: capabilitiesSchema.optional(),
displayName: z.string().nullable().optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
+ /** The owner's own settings (wake rules); patchable whoever provides the account. */
+ settings: agentAccountSettingsSchema.optional(),
}),
)
.mutation(async ({ ctx, input }) => {
diff --git a/apps/server/src/services/agentIdentity/__tests__/index.test.ts b/apps/server/src/services/agentIdentity/__tests__/index.test.ts
index d9583d1a08b..66db5ffeff2 100644
--- a/apps/server/src/services/agentIdentity/__tests__/index.test.ts
+++ b/apps/server/src/services/agentIdentity/__tests__/index.test.ts
@@ -475,6 +475,30 @@ describe('AgentAccountService β€” actions', () => {
);
});
+ it("lets the owner set an issued account's wake rules, in the shape this build accepts", async () => {
+ const { fetchImpl } = createMailFetch();
+ const service = buildService(fetchImpl);
+ const created = await service.provision({ agentId, provider: 'agent-mail' });
+
+ // Settings are the owner's, not the provider's: patchable on an issued account.
+ await expect(
+ service.update(created.id, {
+ settings: { wake: { mode: 'on', wakeSenders: [' [email protected] '] } },
+ }),
+ ).resolves.toBe(created.id);
+ expect(await service.get(created.id)).toMatchObject({
+ metadata: { clientId: 'cli_1', inboxId: 'inb_1' },
+ settings: { wake: { mode: 'on', wakeSenders: ['[email protected]'] } },
+ });
+
+ await expect(
+ service.update(created.id, { settings: { wake: { mode: 'loud' } } as any }),
+ ).rejects.toMatchObject({ code: 'invalid_settings', reason: 'invalid' });
+ expect(await service.get(created.id)).toMatchObject({
+ settings: { wake: { mode: 'on' } },
+ });
+ });
+
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';
diff --git a/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts
new file mode 100644
index 00000000000..878ab8dcc8a
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts
@@ -0,0 +1,652 @@
+// @vitest-environment node
+import { createServer } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+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 { AgentMailModel } from '@/database/models/agentMail';
+import {
+ agentAccounts,
+ agentInboxMessages,
+ agents,
+ signalDecisions,
+ users,
+} from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import type * as AgentIdentityProviders from '../providers';
+
+/**
+ * The mail wake rules and the digest, over the real webhook route.
+ *
+ * Real: the Hono routes, signature verification, the Drizzle models on PGlite,
+ * the wake rules and the digest flush. Faked, and named:
+ * - the Agent Mail SaaS (a loopback server serving the message details);
+ * - `AiAgentService.execAgent`, which would call an LLM β€” the fake records
+ * every run it is asked to start;
+ * - the job queue, so a test decides whether QStash is configured and sees
+ * every flush the digest books;
+ * - the QStash signature check on the flush route.
+ */
+
+const holder = vi.hoisted(() => ({ db: undefined as unknown as LobeChatDatabase }));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: async () => holder.db }));
+
+const runs = vi.hoisted(() => [] as Array<{ params: any; userId: string }>);
+const runFailure = vi.hoisted(() => ({ next: undefined as string | undefined }));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ private readonly db: any;
+ private readonly userId: string;
+ constructor(db: unknown, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+ async execAgent(params: any) {
+ runs.push({ params, userId: this.userId });
+ if (runFailure.next) {
+ const error = runFailure.next;
+ runFailure.next = undefined;
+ return { error };
+ }
+ const topicId = params.appContext?.topicId ?? `tpc_mail_wake_${runs.length}`;
+ const { topics } = await import('@/database/schemas');
+ await this.db
+ .insert(topics)
+ .values({ id: topicId, userId: this.userId })
+ .onConflictDoNothing();
+ return { operationId: `op_${runs.length}`, topicId };
+ }
+ },
+}));
+
+const queue = vi.hoisted(() => ({ failNext: 0, local: false, scheduled: [] as any[] }));
+vi.mock('@/server/services/queue', () => ({
+ QueueService: class {
+ isLocalExecution() {
+ return queue.local;
+ }
+ async scheduleMessage(message: any) {
+ if (queue.failNext > 0) {
+ queue.failNext -= 1;
+ throw new Error('queue unavailable');
+ }
+ queue.scheduled.push(message);
+ return `msg_${queue.scheduled.length}`;
+ }
+ },
+}));
+
+const qstash = vi.hoisted(() => ({ valid: true }));
+vi.mock('@/libs/qstash', () => ({ verifyQStashSignature: async () => qstash.valid }));
+
+let mockBaseUrl = '';
+const claims = vi.hoisted(() => ({ store: undefined as any }));
+
+vi.mock('../providers', async (importOriginal) => {
+ const actual = await importOriginal<typeof AgentIdentityProviders>();
+ return {
+ ...actual,
+ createDefaultAgentAccountRegistry: () =>
+ actual.createAgentAccountRegistry({
+ agentMail: { apiBaseUrl: mockBaseUrl, apiKey: 'am_wake_test', dedupeStore: claims.store },
+ }),
+ };
+});
+
+const { default: agentApp } = await import('@/server/router-hono/agent');
+const { MAIL_WAKE_PIPELINE_VERSION } = await import('../wake/policies');
+const { INBOUND_WAKE_LIMITS } = await import('../inbound');
+
+const serverDB: LobeChatDatabase = await getTestDB();
+holder.db = serverDB;
+
+const userId = 'mail-wake-user';
+const agentId = 'mail-wake-agent';
+const ADDRESS = '[email protected]';
+const WEBHOOK_SECRET = 'whsec_mail_wake';
+
+interface MailFixture {
+ from: string;
+ messageId: string;
+ references?: string[];
+ subject: string;
+}
+
+/** Message details the loopback provider serves, by provider message id. */
+const mails = new Map<string, MailFixture>();
+
+const detailOf = (id: string) => {
+ const mail = mails.get(id);
+ if (!mail) return undefined;
+
+ return {
+ attachments: [],
+ bcc: [],
+ cc: [],
+ codes: [],
+ direction: 'inbound' as const,
+ envelope: { from: mail.from, to: ADDRESS },
+ error: null,
+ from: { address: mail.from },
+ html: null,
+ id,
+ inboxId: 'inb_wake',
+ inReplyTo: mail.references?.at(-1) ?? null,
+ links: [],
+ messageId: mail.messageId,
+ read: false,
+ receivedAt: new Date().toISOString(),
+ references: mail.references ?? [],
+ replyTo: [],
+ size: 64,
+ snippet: null,
+ status: 'received',
+ subject: mail.subject,
+ text: `Body of ${mail.subject}`,
+ to: [{ address: ADDRESS }],
+ };
+};
+
+let mockServer: ReturnType<typeof createServer>;
+let accountId = '';
+
+beforeAll(async () => {
+ vi.stubEnv('KEY_VAULTS_SECRET', Buffer.alloc(32, 7).toString('base64'));
+
+ mockServer = createServer((req, res) => {
+ req.resume();
+ req.on('end', () => {
+ const method = req.method ?? 'GET';
+ const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1');
+ 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: ADDRESS, clientId: 'cli_wake', id: 'inb_wake' });
+ if (method === 'POST' && pathname === '/v1/webhooks')
+ return json(200, { id: 'wh_wake', secret: WEBHOOK_SECRET, url: 'http://127.0.0.1/hook' });
+ const match = /^\/v1\/messages\/([^/]+)$/.exec(pathname);
+ const detail = match && method === 'GET' ? detailOf(match[1]) : undefined;
+ if (detail) return json(200, detail);
+ return json(404, { error: { message: `unexpected ${method} ${pathname}` } });
+ });
+ });
+
+ await new Promise<void>((resolve) => mockServer.listen(0, '127.0.0.1', resolve));
+ mockBaseUrl = `http://127.0.0.1:${(mockServer.address() as AddressInfo).port}`;
+});
+
+afterAll(async () => {
+ await new Promise<void>((resolve, reject) =>
+ mockServer.close((error) => (error ? reject(error) : resolve())),
+ );
+ vi.unstubAllEnvs();
+});
+
+beforeEach(async () => {
+ runs.length = 0;
+ runFailure.next = undefined;
+ queue.local = false;
+ queue.failNext = 0;
+ queue.scheduled.length = 0;
+ qstash.valid = true;
+ mails.clear();
+ const { createInMemoryLinqWebhookDedupeStore } = await import('@lobechat/agent-address-linq');
+ claims.store = createInMemoryLinqWebhookDedupeStore();
+
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+
+ const { AgentAccountService } = await import('../index');
+ const { createAgentMailProvider } = await import('../providers/agentMail');
+ const { AgentAccountProviderRegistry } = await import('../registry');
+ const { KeyVaultsGateKeeper } = await import('@/server/modules/KeyVaultsEncrypt');
+
+ const service = new AgentAccountService(serverDB, userId, {
+ gateKeeper: await KeyVaultsGateKeeper.initWithEnvKey(),
+ registry: new AgentAccountProviderRegistry().register(
+ createAgentMailProvider({
+ apiBaseUrl: mockBaseUrl,
+ apiKey: 'am_wake_test',
+ webhookUrl: 'http://127.0.0.1/hook',
+ }),
+ ),
+ });
+ accountId = (await service.provision({ agentId, provider: 'agent-mail' })).id;
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentInboxMessages);
+ await serverDB.delete(agentAccounts);
+ await serverDB.delete(users);
+});
+
+const setWake = (wake: Record<string, unknown>) =>
+ serverDB.update(agentAccounts).set({ settings: { wake } }).where(eq(agentAccounts.id, accountId));
+
+/** Delivers one signed `message.received` for a mail served by the loopback provider. */
+const deliver = async (id: string, mail: MailFixture) => {
+ mails.set(id, mail);
+ const body = JSON.stringify({
+ createdAt: new Date().toISOString(),
+ data: {
+ inbox: { address: ADDRESS, clientId: 'cli_wake', id: 'inb_wake' },
+ message: { id },
+ },
+ id: `evt_${id}`,
+ type: 'message.received',
+ });
+ const response = await agentApp.request('/api/agent/accounts/webhooks/agent-mail', {
+ body,
+ headers: {
+ 'content-type': 'application/json',
+ 'x-agentmail-signature': computeAgentMailSignature(
+ WEBHOOK_SECRET,
+ body,
+ Math.floor(Date.now() / 1000),
+ ),
+ },
+ method: 'POST',
+ });
+
+ return { json: await response.json(), status: response.status };
+};
+
+const decisions = () =>
+ serverDB
+ .select()
+ .from(signalDecisions)
+ .where(eq(signalDecisions.pipelineVersion, MAIL_WAKE_PIPELINE_VERSION));
+
+const inboxRows = () =>
+ serverDB.select().from(agentInboxMessages).where(eq(agentInboxMessages.accountId, accountId));
+
+const flush = (payload: Record<string, unknown>) =>
+ agentApp.request('/api/agent/accounts/digest-flush', {
+ body: JSON.stringify({ payload }),
+ headers: { 'content-type': 'application/json' },
+ method: 'POST',
+ });
+
+describe('mail wake β€” the default rules', () => {
+ it('holds strangers and machine senders for the digest without any setup', async () => {
+ const stranger = await deliver('m_stranger', {
+ messageId: '<[email protected]>',
+ subject: 'LobeHub x Coupler?',
+ });
+ const robot = await deliver('m_robot', {
+ messageId: '<[email protected]>',
+ subject: 'CI failed',
+ });
+
+ expect(stranger.json.wake).toEqual({ reason: 'held-for-digest', started: false });
+ expect(robot.json.wake).toEqual({ reason: 'held-for-digest', started: false });
+ expect(runs).toHaveLength(0);
+
+ const rows = await decisions();
+ expect(rows).toHaveLength(2);
+ for (const row of rows) {
+ expect(row).toMatchObject({ outcome: 'defer', scopeKey: `agent-mail:${accountId}` });
+ expect(row.metadata).toMatchObject({ extra: { mode: 'on' } });
+ }
+ const robotRow = rows.find((row) => row.verdicts.some((v) => v.reason === 'automated-sender'));
+ expect(robotRow).toMatchObject({ finalReason: 'automated-sender', toTag: 'mail-wake:rules' });
+ expect(robotRow?.verdicts).toEqual([
+ expect.objectContaining({ mode: 'enforce', policyId: 'mail-wake:rules', verdict: 'deny' }),
+ ]);
+ });
+});
+
+describe('mail wake β€” with listed senders', () => {
+ beforeEach(async () => {
+ await setWake({ digestMinutes: 30, mode: 'on', wakeSenders: ['@lobehub.com'] });
+ });
+
+ it('holds a stranger for the digest and books one flush per window', async () => {
+ const first = await deliver('m_pitch_1', {
+ messageId: '<[email protected]>',
+ subject: 'Agent workloads',
+ });
+ await deliver('m_pitch_2', {
+ messageId: '<[email protected]>',
+ subject: 'LLM API costs at LobeHub',
+ });
+
+ expect(first.status).toBe(200);
+ expect(first.json.wake).toEqual({ reason: 'held-for-digest', started: false });
+ expect(runs).toHaveLength(0);
+
+ // Both bookings carry the same window, so QStash keeps one flush.
+ expect(queue.scheduled).toHaveLength(2);
+ const [a, b] = queue.scheduled;
+ expect(a.deduplicationId).toBe(b.deduplicationId);
+ expect(a.endpoint).toMatch(/\/api\/agent\/accounts\/digest-flush$/);
+ expect(a.payload).toEqual({ accountId, at: expect.any(Number) });
+ expect(a.payload.at % (30 * 60_000)).toBe(0);
+
+ const rows = await inboxRows();
+ expect(rows.every((row) => row.readAt === null && row.wakeClaimedAt === null)).toBe(true);
+ expect((await decisions()).map((row) => row.outcome)).toEqual(['defer', 'defer']);
+ });
+
+ it('wakes at once for a listed sender', async () => {
+ const result = await deliver('m_team', {
+ messageId: '<[email protected]>',
+ subject: 'AWS migration plan',
+ });
+
+ expect(result.json.wake).toMatchObject({ reason: 'started', started: true });
+ expect(runs).toHaveLength(1);
+ expect(queue.scheduled).toHaveLength(0);
+ expect(await decisions()).toEqual([
+ expect.objectContaining({
+ finalReason: 'wake-sender',
+ outcome: 'wake',
+ toTag: 'mail-wake:rules',
+ topicId: 'tpc_mail_wake_1',
+ }),
+ ]);
+ });
+
+ it('wakes at once for a reply in a thread the agent wrote to that sender', async () => {
+ await deliver('m_root', {
+ messageId: '<[email protected]>',
+ subject: 'Backlinks',
+ });
+ expect(runs).toHaveLength(0);
+ const [root] = await inboxRows();
+
+ // The agent answered the thread (with the owner's approval).
+ await AgentMailModel.record(
+ serverDB,
+ {
+ accountId,
+ agentId,
+ deliveredAt: new Date(),
+ direction: 'outbound',
+ fromAddress: ADDRESS,
+ provider: 'agent-mail',
+ providerMessageId: 'out_1',
+ text: 'Thanks, tell me more.',
+ threadKey: root.threadKey!,
+ to: [{ address: '[email protected]' }],
+ },
+ { userId },
+ );
+
+ const reply = await deliver('m_reply', {
+ messageId: '<[email protected]>',
+ references: ['<[email protected]>'],
+ subject: 'RE: Backlinks',
+ });
+ expect(reply.json.wake).toMatchObject({ started: true });
+
+ // Someone else who learned the thread's key does not get the same pass.
+ const outsider = await deliver('m_outsider', {
+ messageId: '<[email protected]>',
+ references: ['<[email protected]>'],
+ subject: 'RE: Backlinks',
+ });
+ expect(outsider.json.wake).toEqual({ reason: 'held-for-digest', started: false });
+ expect(runs).toHaveLength(1);
+ });
+
+ it('wakes at once when the deployment has no durable queue to hold for', async () => {
+ queue.local = true;
+
+ const result = await deliver('m_local', {
+ messageId: '<[email protected]>',
+ subject: 'Agent workloads',
+ });
+
+ expect(result.json.wake).toMatchObject({ started: true });
+ expect(queue.scheduled).toHaveLength(0);
+ expect((await decisions())[0]).toMatchObject({
+ finalReason: 'digest-unavailable',
+ outcome: 'wake',
+ });
+ });
+});
+
+describe('mail wake β€” past the wake budget', () => {
+ /** One more than the per-sender budget, all from a sender the rules would wake for. */
+ const flood = async () => {
+ const results = [];
+ for (let i = 0; i <= INBOUND_WAKE_LIMITS.perSender; i++) {
+ results.push(
+ await deliver(`m_flood_${i}`, {
+ messageId: `<flood-${i}@lobehub.com>`,
+ subject: `Update ${i}`,
+ }),
+ );
+ }
+ return results;
+ };
+
+ it('holds the overflow for the digest', async () => {
+ await setWake({ mode: 'on', wakeSenders: ['@lobehub.com'] });
+
+ const results = await flood();
+
+ expect(runs).toHaveLength(INBOUND_WAKE_LIMITS.perSender);
+ expect(results.at(-1)!.json.wake).toEqual({ reason: 'held-for-digest', started: false });
+ expect(queue.scheduled).toHaveLength(1);
+ expect((await decisions()).filter((row) => row.outcome === 'defer')).toEqual([
+ expect.objectContaining({ finalReason: 'rate-limited' }),
+ ]);
+ });
+
+ it('drops the overflow when the deployment has no digest', async () => {
+ queue.local = true;
+ await setWake({ mode: 'on', wakeSenders: ['@lobehub.com'] });
+
+ const results = await flood();
+
+ expect(runs).toHaveLength(INBOUND_WAKE_LIMITS.perSender);
+ expect(results.at(-1)!.json.wake).toEqual({ reason: 'rate-limited', started: false });
+ expect(queue.scheduled).toHaveLength(0);
+ expect((await decisions()).filter((row) => row.outcome === 'skip')).toEqual([
+ expect.objectContaining({ finalReason: 'rate-limited' }),
+ ]);
+ });
+});
+
+describe('mail wake β€” off', () => {
+ it('keeps the message in the inbox and starts nothing', async () => {
+ await setWake({ mode: 'off' });
+
+ const result = await deliver('m_off', {
+ messageId: '<[email protected]>',
+ subject: 'Anything',
+ });
+
+ expect(result.json.wake).toEqual({ reason: 'wake-off', started: false });
+ expect(runs).toHaveLength(0);
+ expect(queue.scheduled).toHaveLength(0);
+ expect(await inboxRows()).toHaveLength(1);
+ expect((await decisions())[0]).toMatchObject({ outcome: 'skip', verdicts: [] });
+ });
+});
+
+describe('mail digest flush', () => {
+ beforeEach(async () => {
+ await setWake({ mode: 'on' });
+ await deliver('m_d1', {
+ messageId: '<[email protected]>',
+ subject: 'Agent workloads',
+ });
+ await deliver('m_d2', {
+ messageId: '<[email protected]>',
+ subject: 'lobehub + boxd',
+ });
+ });
+
+ it('starts one run for everything held, and a repeated flush finds nothing', async () => {
+ const response = await flush(queue.scheduled[0].payload);
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ result: 'started' });
+
+ expect(runs).toHaveLength(1);
+ expect(runs[0]).toMatchObject({
+ params: { agentId, appContext: { scope: 'agent' }, trigger: 'inbox' },
+ userId,
+ });
+ const prompt: string = runs[0].params.prompt;
+ const [own, , fenced] = prompt.split('\n\n');
+ expect(own).toContain('2 messages arrived');
+ expect(own).not.toContain('launchdriftcloud');
+ expect(fenced.startsWith('<untrusted_inbox>')).toBe(true);
+ expect(fenced.indexOf('Agent workloads')).toBeLessThan(fenced.indexOf('lobehub + boxd'));
+
+ const rows = await inboxRows();
+ expect(rows.every((row) => row.readAt !== null && row.topicId === 'tpc_mail_wake_1')).toBe(
+ true,
+ );
+
+ const again = await flush(queue.scheduled[0].payload);
+ expect(await again.json()).toMatchObject({ result: 'empty' });
+ expect(runs).toHaveLength(1);
+ });
+
+ it('leaves out what the owner already read', async () => {
+ const [first] = await inboxRows();
+ await serverDB
+ .update(agentInboxMessages)
+ .set({ readAt: new Date() })
+ .where(eq(agentInboxMessages.id, first.id));
+
+ await flush(queue.scheduled[0].payload);
+
+ expect(runs).toHaveLength(1);
+ expect(runs[0].params.prompt).toContain('1 message arrived');
+ });
+
+ it('runs nothing once the owner switched wake off', async () => {
+ await setWake({ mode: 'off' });
+
+ const response = await flush(queue.scheduled[0].payload);
+
+ expect(await response.json()).toMatchObject({ result: 'wake-off' });
+ expect(runs).toHaveLength(0);
+ });
+
+ it('gives the messages back and books the next window when the run does not start', async () => {
+ runFailure.next = 'budget exhausted';
+ const booked = queue.scheduled.length;
+
+ const failed = await flush(queue.scheduled[0].payload);
+
+ // QStash retries this flush; should every retry fail, the next window tries again.
+ expect(failed.status).toBe(500);
+ expect(queue.scheduled).toHaveLength(booked + 1);
+ const next = queue.scheduled.at(-1);
+ // The default window is an hour; the next one starts where the held one ended.
+ expect(next.payload.at).toBe(queue.scheduled[0].payload.at + 60 * 60_000);
+ expect(next.deduplicationId).toBe(`agent-mail-digest:${accountId}:${next.payload.at}`);
+ expect((await inboxRows()).every((row) => row.wakeClaimedAt === null)).toBe(true);
+
+ const retried = await flush(next.payload);
+ expect(await retried.json()).toMatchObject({ result: 'started' });
+ expect(runs.at(-1)!.params.prompt).toContain('2 messages arrived');
+ });
+
+ it('never sweeps in mail that arrived while wake was off', async () => {
+ await setWake({ mode: 'off' });
+ await deliver('m_off_period', {
+ messageId: '<[email protected]>',
+ subject: 'While you were off',
+ });
+ await setWake({ mode: 'on' });
+
+ await flush(queue.scheduled[0].payload);
+
+ expect(runs).toHaveLength(1);
+ expect(runs[0].params.prompt).toContain('2 messages arrived');
+ expect(runs[0].params.prompt).not.toContain('While you were off');
+ });
+
+ it('refuses a flush without a valid QStash signature', async () => {
+ qstash.valid = false;
+
+ const response = await flush(queue.scheduled[0].payload);
+
+ expect(response.status).toBe(401);
+ expect(runs).toHaveLength(0);
+ });
+});
+
+describe('mail digest flush β€” a full batch', () => {
+ it('runs one batch and books a prompt follow-up for the rest', async () => {
+ const { DIGEST_BATCH_LIMIT } = await import('../wake/digest');
+ await setWake({ mode: 'on' });
+ for (let i = 0; i <= DIGEST_BATCH_LIMIT; i++) {
+ await deliver(`m_bulk_${i}`, {
+ from: `sender${i}@example.org`,
+ messageId: `<bulk-${i}@example.org>`,
+ subject: `Bulk ${i}`,
+ });
+ }
+ const [window] = queue.scheduled;
+ const booked = queue.scheduled.length;
+
+ await flush(window.payload);
+
+ expect(runs).toHaveLength(1);
+ expect(runs[0].params.prompt).toContain(`${DIGEST_BATCH_LIMIT} messages arrived`);
+ const followUp = queue.scheduled.at(-1);
+ expect(queue.scheduled).toHaveLength(booked + 1);
+ expect(followUp.delay).toBeLessThanOrEqual(60_000);
+
+ await flush(followUp.payload);
+ expect(runs).toHaveLength(2);
+ expect(runs[1].params.prompt).toContain('1 message arrived');
+ });
+
+ it('fails the flush so QStash retries the leftover when the follow-up cannot be booked', async () => {
+ const { DIGEST_BATCH_LIMIT } = await import('../wake/digest');
+ await setWake({ mode: 'on' });
+ for (let i = 0; i <= DIGEST_BATCH_LIMIT; i++) {
+ await deliver(`m_stuck_${i}`, {
+ from: `sender${i}@example.org`,
+ messageId: `<stuck-${i}@example.org>`,
+ subject: `Stuck ${i}`,
+ });
+ }
+ const [window] = queue.scheduled;
+ queue.failNext = 1;
+
+ const failed = await flush(window.payload);
+
+ // Acknowledging the flush here would leave the rest unread until someone writes again, so the
+ // flush reports the failure instead; the batch it did run keeps its messages.
+ expect(failed.status).toBe(500);
+ expect(runs).toHaveLength(1);
+ expect((await inboxRows()).filter((row) => row.readAt === null)).toHaveLength(1);
+
+ const retried = await flush(window.payload);
+ expect(retried.status).toBe(200);
+ expect(runs).toHaveLength(2);
+ expect(runs[1].params.prompt).toContain('1 message arrived');
+ });
+});
diff --git a/apps/server/src/services/agentIdentity/errors.ts b/apps/server/src/services/agentIdentity/errors.ts
index 0a4bf641f6b..c5395d85bf0 100644
--- a/apps/server/src/services/agentIdentity/errors.ts
+++ b/apps/server/src/services/agentIdentity/errors.ts
@@ -11,18 +11,21 @@
* - `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.
+ * - `invalid_settings`: the patch's settings are not a shape this build accepts.
* - `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'
| 'identifier_taken'
+ | 'invalid_settings'
| 'provider_managed'
| 'provider_owned_field'
| 'reply_target_not_owned';
const INVALID_REQUEST_CODES = new Set<AgentAccountErrorCode>([
'capabilities_required',
+ 'invalid_settings',
'provider_managed',
'provider_owned_field',
'reply_target_not_owned',
diff --git a/apps/server/src/services/agentIdentity/inbound.ts b/apps/server/src/services/agentIdentity/inbound.ts
index b38c049caf9..12fbb18697b 100644
--- a/apps/server/src/services/agentIdentity/inbound.ts
+++ b/apps/server/src/services/agentIdentity/inbound.ts
@@ -15,6 +15,10 @@ import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { AgentInboxService } from './inbox';
import { AgentAccountService } from './index';
import { createDefaultAgentAccountRegistry } from './providers';
+import type { ResolvedWakeConfig } from './wake/config';
+import type { MailWakeAction, MailWakePlan } from './wake/decide';
+import { planMailWake, recordMailWakeDecision } from './wake/decide';
+import { holdForDigest, isDigestAvailable } from './wake/digest';
import { createAgentInboundWaker } from './waker';
/**
@@ -63,9 +67,21 @@ export type AgentInboundResult =
| { accountId?: string; outcome: 'rejected'; status: 401 }
| { outcome: 'unknown-account' | 'unroutable'; status: 404 };
+/** Where a delivery the wake rules hold back goes: the account's next digest. */
+export interface AgentInboundDigest {
+ /** Books the digest flush for the window this delivery arrived in. */
+ hold: (account: AgentAccountView, config: ResolvedWakeConfig) => Promise<void>;
+ /** Without a durable delay queue there is no digest; held deliveries wake at once instead. */
+ isAvailable: () => boolean;
+}
+
+const DEFAULT_DIGEST: AgentInboundDigest = { hold: holdForDigest, isAvailable: isDigestAvailable };
+
export interface AgentInboundServiceOptions {
/** The account service that owns signature verification. */
accountService: AgentAccountService;
+ /** Defaults to the QStash-backed digest. */
+ digest?: AgentInboundDigest;
/** Defaults to a no-op waker that reports `not-configured`. */
waker?: AgentInboundWaker;
}
@@ -115,11 +131,14 @@ const toSignalPayload = (payload: unknown): Record<string, unknown> =>
* is then recorded as an `agent_mails` row and put in the inbox. Each step
* is idempotent, so a provider retry returns the same item with
* `created: false` instead of duplicating it or waking the agent twice.
- * 3. **Wake** β€” a genuinely new delivery wakes the agent through the injected
- * waker, within {@link INBOUND_WAKE_LIMITS}. A duplicate of a message that
- * was already woken never reaches this step; a wake that failed transiently
- * answers 503 and releases the replay claim, so the provider's retry wakes
- * the still-unread message then.
+ * 3. **Decide** β€” the account's wake rules ({@link planMailWake}) say whether
+ * the delivery wakes the agent now, waits for the digest, or neither; the
+ * decision is recorded against the signal either way.
+ * 4. **Wake** β€” a delivery the rules let through wakes the agent through the
+ * injected waker, within {@link INBOUND_WAKE_LIMITS}. A duplicate of a
+ * message that was already woken never reaches this step; a wake that failed
+ * transiently answers 503 and releases the replay claim, so the provider's
+ * retry wakes the still-unread message then.
*/
export class AgentInboundService {
private readonly db: LobeChatDatabase;
@@ -249,45 +268,81 @@ export class AgentInboundService {
};
}
- if (await this.overWakeBudget(accountId, row.from)) {
- return {
+ const delivered = (wake: AgentInboundWakeResult, status: 200 | 503 = 200) =>
+ ({
accountId,
created,
messageId: row.id,
outcome: 'delivered',
- status: 200,
- wake: { reason: 'rate-limited', started: false },
- };
+ status,
+ wake,
+ }) satisfies AgentInboundResult;
+
+ const plan = await this.planWake(account, row);
+ const record = (action: MailWakeAction, reason?: string, topicId?: string) =>
+ recordMailWakeDecision(this.db, { account, action, plan, reason, signalId, topicId });
+
+ if (plan.action === 'skip') {
+ await record('skip');
+ return delivered({ reason: plan.reason, started: false });
+ }
+
+ // The `defer` row is what puts the message in the digest, so it must be on
+ // record before the flush is booked; a failure throws, and the provider's
+ // retry holds the message again.
+ const hold = async (reason?: string) => {
+ if (!(await record('defer', reason))) throw new Error('the defer decision was not recorded');
+ await this.digest.hold(account, plan.config);
+ return delivered({ reason: 'held-for-digest', started: false });
+ };
+
+ if (plan.action === 'defer') return hold();
+
+ if (await this.overWakeBudget(accountId, row.from)) {
+ // A delivery past the budget waits for the digest instead of never
+ // running; only without a digest is it dropped.
+ if (this.digest.isAvailable()) return hold('rate-limited');
+ await record('skip', 'rate-limited');
+ return delivered({ reason: 'rate-limited', started: false });
}
// The unique insert only dedupes storage: two workers handling the same
// delivery can both see the row unread. The wake itself is claimed
// atomically on the row, so exactly one of them starts a run.
if (!(await AgentInboxModel.claimWake(this.db, row.id))) {
- return {
- accountId,
- created,
- messageId: row.id,
- outcome: 'delivered',
- status: 200,
- wake: { reason: 'duplicate-delivery', started: false },
- };
+ return delivered({ reason: 'duplicate-delivery', started: false });
}
const wake = await this.wake(account, row);
// A transient failure gives the claim back so the provider's retry wakes it.
- if (RETRYABLE_WAKE_REASONS.has(wake.reason)) await AgentInboxModel.releaseWake(this.db, row.id);
-
- return {
- accountId,
- created,
- messageId: row.id,
- outcome: 'delivered',
- status: RETRYABLE_WAKE_REASONS.has(wake.reason) ? 503 : 200,
- wake,
- };
+ if (RETRYABLE_WAKE_REASONS.has(wake.reason)) {
+ await AgentInboxModel.releaseWake(this.db, row.id);
+ return delivered(wake, 503);
+ }
+
+ await (wake.started ? record('wake', undefined, wake.topicId) : record('skip', wake.reason));
+ return delivered(wake);
};
+ /**
+ * The wake rules' plan for a delivery. Without a digest to hold it for, a
+ * delivery the rules would defer wakes the agent at once instead, so nothing
+ * is held where no flush will ever come.
+ */
+ private planWake = async (
+ account: AgentAccountView,
+ entry: AgentInboxEntry,
+ ): Promise<MailWakePlan> => {
+ const plan = await planMailWake(this.db, account, entry);
+ if (plan.action !== 'defer' || this.digest.isAvailable()) return plan;
+
+ return { ...plan, action: 'wake', reason: 'digest-unavailable' };
+ };
+
+ private get digest(): AgentInboundDigest {
+ return this.options.digest ?? DEFAULT_DIGEST;
+ }
+
/** Record an authentic delivery as a signal, owned by the account's owner. */
private recordSignal = (
provider: string,
diff --git a/apps/server/src/services/agentIdentity/index.ts b/apps/server/src/services/agentIdentity/index.ts
index 99e9a785e34..ffc0ee1b762 100644
--- a/apps/server/src/services/agentIdentity/index.ts
+++ b/apps/server/src/services/agentIdentity/index.ts
@@ -7,6 +7,7 @@ import type {
AgentAccountKind,
AgentAccountOutboundMessage,
AgentAccountRef,
+ AgentAccountSettings,
} from '@lobechat/types';
import type {
@@ -26,9 +27,25 @@ import {
import { AgentAccountError } from './errors';
import type { AgentAccountProviderRegistry } from './registry';
import { isReservedAgentAccountProvider } from './registry';
+import { agentAccountSettingsSchema } from './wake/config';
const PG_UNIQUE_VIOLATION = '23505';
+/**
+ * The owner's settings as a write must carry them. Reads tolerate anything stored; a write is
+ * held to the shape this build understands.
+ */
+const parseSettings = (settings: unknown): AgentAccountSettings => {
+ const parsed = agentAccountSettingsSchema.safeParse(settings);
+ if (parsed.success) return parsed.data;
+
+ const issue = parsed.error.issues[0];
+ throw new AgentAccountError(
+ 'invalid_settings',
+ `Invalid agent account settings${issue ? ` at ${issue.path.join('.') || '(root)'}: ${issue.message}` : ''}.`,
+ );
+};
+
export type { AgentAccountErrorCode } from './errors';
export { AgentAccountError, isAgentAccountError } from './errors';
@@ -317,7 +334,10 @@ export class AgentAccountService {
);
}
- return this.model.update(id, patch);
+ return this.model.update(
+ id,
+ patch.settings === undefined ? patch : { ...patch, settings: parseSettings(patch.settings) },
+ );
};
/** Install or rotate a credential. Write-only: nothing reads it back out here. */
diff --git a/apps/server/src/services/agentIdentity/wake/config.test.ts b/apps/server/src/services/agentIdentity/wake/config.test.ts
new file mode 100644
index 00000000000..5af9a7e34c8
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/wake/config.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ agentAccountSettingsSchema,
+ DEFAULT_DIGEST_MINUTES,
+ isWakeSender,
+ resolveWakeConfig,
+} from './config';
+
+describe('resolveWakeConfig', () => {
+ it('defaults to on with an hourly digest and no listed senders', () => {
+ expect(resolveWakeConfig(undefined)).toEqual({
+ digestMs: DEFAULT_DIGEST_MINUTES * 60_000,
+ mode: 'on',
+ wakeSenders: [],
+ });
+ });
+
+ it('falls back field by field on stored values this build does not accept', () => {
+ const config = resolveWakeConfig({
+ wake: {
+ digestMinutes: 1.5,
+ mode: 'loud' as any,
+ wakeSenders: ['[email protected]', 'not-an-address', 42 as any, '@Team.io'],
+ },
+ });
+
+ expect(config).toEqual({
+ digestMs: DEFAULT_DIGEST_MINUTES * 60_000,
+ mode: 'on',
+ wakeSenders: ['[email protected]', '@team.io'],
+ });
+ });
+
+ it('clamps the digest window into its range', () => {
+ expect(resolveWakeConfig({ wake: { digestMinutes: 1 } }).digestMs).toBe(5 * 60_000);
+ expect(resolveWakeConfig({ wake: { digestMinutes: 99_999 } }).digestMs).toBe(1440 * 60_000);
+ });
+});
+
+describe('isWakeSender', () => {
+ const senders = ['[email protected]', '@team.io'];
+
+ it('matches a full address or a whole domain, ignoring case', () => {
+ expect(isWakeSender('[email protected]', senders)).toBe(true);
+ expect(isWakeSender('[email protected]', senders)).toBe(true);
+ });
+
+ it('does not match a look-alike domain or another address at the same domain', () => {
+ expect(isWakeSender('[email protected]', senders)).toBe(false);
+ expect(isWakeSender('[email protected]', senders)).toBe(false);
+ expect(isWakeSender('[email protected]', senders)).toBe(false);
+ });
+});
+
+describe('agentAccountSettingsSchema', () => {
+ it('accepts and normalizes a valid write', () => {
+ expect(
+ agentAccountSettingsSchema.parse({
+ wake: {
+ digestMinutes: 30,
+ mode: 'on',
+ wakeSenders: [' [email protected] ', '@team.io'],
+ },
+ }),
+ ).toEqual({
+ wake: { digestMinutes: 30, mode: 'on', wakeSenders: ['[email protected]', '@team.io'] },
+ });
+ });
+
+ it('refuses unknown modes, bad senders, out-of-range windows and unknown keys', () => {
+ expect(agentAccountSettingsSchema.safeParse({ wake: { mode: 'loud' } }).success).toBe(false);
+ expect(
+ agentAccountSettingsSchema.safeParse({ wake: { wakeSenders: ['nobody'] } }).success,
+ ).toBe(false);
+ expect(agentAccountSettingsSchema.safeParse({ wake: { digestMinutes: 1 } }).success).toBe(
+ false,
+ );
+ expect(agentAccountSettingsSchema.safeParse({ other: true }).success).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/agentIdentity/wake/config.ts b/apps/server/src/services/agentIdentity/wake/config.ts
new file mode 100644
index 00000000000..a3286ca7a05
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/wake/config.ts
@@ -0,0 +1,84 @@
+import type { AgentAccountSettings, AgentAccountWakeMode } from '@lobechat/types';
+import { AGENT_ACCOUNT_DIGEST_MINUTES_RANGE, AGENT_ACCOUNT_WAKE_MODES } from '@lobechat/types';
+import { z } from 'zod';
+
+import { normalizeMailAddress } from '@/database/models/agentMail';
+
+/** Digest window when the owner set none. */
+export const DEFAULT_DIGEST_MINUTES = 60;
+
+/** Most senders one account may list; the list is matched on every delivery. */
+export const MAX_WAKE_SENDERS = 200;
+
+/** A full address (`[email protected]`) or a whole domain (`@b.com`). */
+const WAKE_SENDER_PATTERN = /^[^\s@]*@[^\s@]+\.[^\s@]+$/;
+
+/** What a write must look like. Reads use {@link resolveWakeConfig}, which never throws. */
+export const agentAccountSettingsSchema = z
+ .object({
+ wake: z
+ .object({
+ digestMinutes: z
+ .number()
+ .int()
+ .min(AGENT_ACCOUNT_DIGEST_MINUTES_RANGE.min)
+ .max(AGENT_ACCOUNT_DIGEST_MINUTES_RANGE.max)
+ .optional(),
+ mode: z.enum(AGENT_ACCOUNT_WAKE_MODES).optional(),
+ wakeSenders: z
+ .array(z.string().trim().toLowerCase().regex(WAKE_SENDER_PATTERN))
+ .max(MAX_WAKE_SENDERS)
+ .optional(),
+ })
+ .strict()
+ .optional(),
+ })
+ .strict();
+
+/** The wake rules of one account with every default applied. */
+export interface ResolvedWakeConfig {
+ digestMs: number;
+ mode: AgentAccountWakeMode;
+ /** Lowercased; a leading `@` marks a whole domain. */
+ wakeSenders: string[];
+}
+
+/**
+ * Reads an account's wake rules. Settings are stored JSON that may predate a field or carry a
+ * value a later build no longer accepts, so anything malformed falls back to its default instead
+ * of failing the delivery.
+ */
+export const resolveWakeConfig = (
+ settings: AgentAccountSettings | null | undefined,
+): ResolvedWakeConfig => {
+ const wake = settings?.wake;
+ const mode = (AGENT_ACCOUNT_WAKE_MODES as readonly string[]).includes(wake?.mode ?? '')
+ ? (wake!.mode as AgentAccountWakeMode)
+ : 'on';
+
+ const minutes = Number.isInteger(wake?.digestMinutes)
+ ? Math.min(
+ AGENT_ACCOUNT_DIGEST_MINUTES_RANGE.max,
+ Math.max(AGENT_ACCOUNT_DIGEST_MINUTES_RANGE.min, wake!.digestMinutes!),
+ )
+ : DEFAULT_DIGEST_MINUTES;
+
+ const wakeSenders = Array.isArray(wake?.wakeSenders)
+ ? wake.wakeSenders
+ .filter((sender): sender is string => typeof sender === 'string')
+ .map((sender) => normalizeMailAddress(sender))
+ .filter((sender) => WAKE_SENDER_PATTERN.test(sender))
+ : [];
+
+ return { digestMs: minutes * 60_000, mode, wakeSenders };
+};
+
+/** Whether `from` is one of the listed senders, by full address or by domain. */
+export const isWakeSender = (from: string, wakeSenders: readonly string[]): boolean => {
+ const address = normalizeMailAddress(from);
+ const domain = address.slice(address.lastIndexOf('@'));
+
+ return wakeSenders.some((sender) =>
+ sender.startsWith('@') ? domain === sender : address === sender,
+ );
+};
diff --git a/apps/server/src/services/agentIdentity/wake/decide.ts b/apps/server/src/services/agentIdentity/wake/decide.ts
new file mode 100644
index 00000000000..09193619074
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/wake/decide.ts
@@ -0,0 +1,141 @@
+import type { SignalDecisionOutcome } from '@lobechat/types';
+import debug from 'debug';
+
+import type { AgentAccountView } from '@/database/models/agentAccount';
+import type { AgentInboxEntry } from '@/database/models/agentInbox';
+import { AgentMailModel } from '@/database/models/agentMail';
+import { SignalDecisionModel } from '@/database/models/signalDecision';
+import type { LobeChatDatabase } from '@/database/type';
+import { aggregateWakeVerdicts } from '@/server/services/conversationWake/aggregator';
+import { toWakeVerdicts } from '@/server/services/conversationWake/initiation';
+import type { WakeDecision, WakeStateSnapshot } from '@/server/services/conversationWake/types';
+
+import type { ResolvedWakeConfig } from './config';
+import { resolveWakeConfig } from './config';
+import { createMailRulesPolicy, MAIL_WAKE_PIPELINE_VERSION, toMailWakeSignal } from './policies';
+
+const log = debug('lobe-server:agent-identity:mail-wake');
+
+/**
+ * What to do with one delivery.
+ *
+ * - `wake`: start a run for it now
+ * - `defer`: leave it unread for the digest
+ * - `skip`: leave it in the inbox; nothing will run for it
+ */
+export type MailWakeAction = 'defer' | 'skip' | 'wake';
+
+export interface MailWakePlan {
+ action: MailWakeAction;
+ config: ResolvedWakeConfig;
+ /** The rules' aggregate decision; absent when the account's wake is `off`. */
+ decision?: WakeDecision;
+ /** Why, as recorded on the decision row. */
+ reason: string;
+}
+
+/**
+ * Whether the sender is answering the agent: the thread holds mail the agent sent, and the sender
+ * was among its recipients. Knowing a thread's key is not enough, so a stranger cannot borrow a
+ * thread to jump the queue.
+ */
+const isReplyToAgent = (
+ db: LobeChatDatabase,
+ account: AgentAccountView,
+ entry: AgentInboxEntry,
+): Promise<boolean> =>
+ entry.threadKey
+ ? AgentMailModel.hasSentInThreadTo(db, {
+ accountId: account.id,
+ address: entry.from,
+ threadKey: entry.threadKey,
+ })
+ : Promise.resolve(false);
+
+/**
+ * Decides whether a delivery wakes the agent now, waits for the digest, or neither.
+ *
+ * The rules are the shared wake policies run through the shared aggregator, so a mail decision
+ * reads like a bot one in `signal_decisions`: an allow wakes the agent, anything else is deferred
+ * to the digest.
+ */
+export const planMailWake = async (
+ db: LobeChatDatabase,
+ account: AgentAccountView,
+ entry: AgentInboxEntry,
+): Promise<MailWakePlan> => {
+ const config = resolveWakeConfig(account.settings);
+ if (config.mode === 'off') return { action: 'skip', config, reason: 'wake-off' };
+
+ const snapshot: WakeStateSnapshot = {
+ explicitMention: false,
+ replyToBot: await isReplyToAgent(db, account, entry),
+ threadSubscribed: false,
+ };
+ const decision = aggregateWakeVerdicts(
+ [createMailRulesPolicy('enforce', config.wakeSenders)],
+ toMailWakeSignal(account, entry),
+ snapshot,
+ );
+ const action: MailWakeAction = decision.verdict === 'allow' ? 'wake' : 'defer';
+
+ return { action, config, decision, reason: decision.reason };
+};
+
+const OUTCOME_BY_ACTION: Record<MailWakeAction, SignalDecisionOutcome> = {
+ defer: 'defer',
+ skip: 'skip',
+ wake: 'wake',
+};
+
+export interface RecordMailWakeDecisionParams {
+ account: AgentAccountView;
+ /** What actually happened, which the wake budget may have changed from the plan. */
+ action: MailWakeAction;
+ plan: MailWakePlan;
+ /** Why the action differs from the plan's, when it does (`rate-limited`). */
+ reason?: string;
+ signalId: string;
+ topicId?: string;
+}
+
+/**
+ * Keeps the decision for one delivery, so the rules can be judged against what happened. A `defer`
+ * row is also what marks the message as waiting for the digest.
+ *
+ * Never throws: returns whether the row is on record, so a caller that depends on it (the defer
+ * path) can fail the delivery, while the others carry on without the record.
+ */
+export const recordMailWakeDecision = async (
+ db: LobeChatDatabase,
+ { account, action, plan, reason, signalId, topicId }: RecordMailWakeDecisionParams,
+): Promise<boolean> => {
+ try {
+ const recorded = await new SignalDecisionModel(
+ db,
+ account.userId,
+ account.workspaceId ?? undefined,
+ ).record({
+ agentId: account.agentId,
+ finalReason: reason ?? plan.reason,
+ metadata: {
+ extra: {
+ mode: plan.config.mode,
+ ...(plan.decision?.fastPath ? { fastPath: true } : {}),
+ },
+ },
+ outcome: OUTCOME_BY_ACTION[action],
+ pipelineVersion: MAIL_WAKE_PIPELINE_VERSION,
+ scopeKey: `agent-mail:${account.id}`,
+ signalId,
+ toTag: plan.decision?.decidedBy,
+ topicId,
+ verdicts: plan.decision ? toWakeVerdicts(plan.decision) : [],
+ });
+
+ return !!recorded;
+ } catch (error) {
+ log('recording the decision for signal %s failed: %O', signalId, error);
+ return false;
+ }
+};
diff --git a/apps/server/src/services/agentIdentity/wake/digest.ts b/apps/server/src/services/agentIdentity/wake/digest.ts
new file mode 100644
index 00000000000..48b58eabbde
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/wake/digest.ts
@@ -0,0 +1,209 @@
+import { RequestTrigger } from '@lobechat/types';
+import debug from 'debug';
+
+import type { AgentAccountView } from '@/database/models/agentAccount';
+import { AgentAccountModel } from '@/database/models/agentAccount';
+import type { AgentInboxEntry } from '@/database/models/agentInbox';
+import { AgentInboxModel } from '@/database/models/agentInbox';
+import type { LobeChatDatabase } from '@/database/type';
+import { appEnv } from '@/envs/app';
+import { AiAgentService } from '@/server/services/aiAgent';
+import { QueueService } from '@/server/services/queue';
+import { agentSignalScopeFlowControl } from '@/server/workflows/agentSignal';
+
+import { fenceUntrustedInbox, toUntrustedInboxEntry } from '../untrusted';
+import type { ResolvedWakeConfig } from './config';
+import { resolveWakeConfig } from './config';
+
+const log = debug('lobe-server:agent-identity:mail-digest');
+
+export const DIGEST_FLUSH_ENDPOINT = '/api/agent/accounts/digest-flush';
+
+/** Most messages one digest run reads; the rest go to the next flush. */
+export const DIGEST_BATCH_LIMIT = 30;
+
+/** Body budget per message in the digest prompt; the full text stays readable through the tool. */
+const DIGEST_BODY_PREVIEW_CHARS = 600;
+
+/**
+ * How far back a digest looks. A held message older than this missed every digest since (each
+ * flush failed); running it now would only surprise the owner, so it stays in the inbox unread.
+ */
+const DIGEST_LOOKBACK_MS = 3 * 24 * 60 * 60 * 1000;
+
+/** When the batch was full, the next flush comes this soon instead of a whole window later. */
+const DIGEST_FOLLOW_UP_MS = 60 * 1000;
+
+/** What the delayed flush carries back. */
+export interface DigestFlushPayload {
+ accountId: string;
+ /** The window end this flush was booked for; part of its dedupe key. */
+ at: number;
+}
+
+/**
+ * The digest needs a delay queue that survives a restart (QStash). The local, in-process queue
+ * would lose an unfired timer, so without a real queue there is no digest and a held message
+ * would never run: callers wake at once instead.
+ */
+export const isDigestAvailable = (): boolean => !new QueueService().isLocalExecution();
+
+/** End of the window `now` falls in. Every delivery in one window books the same flush. */
+export const digestWindowEnd = (now: number, digestMs: number): number =>
+ Math.ceil((now + 1) / digestMs) * digestMs;
+
+/**
+ * Books the flush that will run the digest. Idempotent per account and window: QStash drops a
+ * second booking with the same deduplication id, so every held delivery can call it.
+ */
+export const scheduleDigestFlush = async (accountId: string, at: number): Promise<void> => {
+ const queue = new QueueService();
+ const baseURL = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';
+ const payload: DigestFlushPayload = { accountId, at };
+
+ await queue.scheduleMessage({
+ deduplicationId: `agent-mail-digest:${accountId}:${at}`,
+ delay: Math.max(0, at - Date.now()),
+ endpoint: new URL(DIGEST_FLUSH_ENDPOINT, baseURL).toString(),
+ // One account's flushes run one at a time, so two of them never split a batch.
+ flowControl: agentSignalScopeFlowControl(`agent-mail:${accountId}`),
+ operationId: `agent-mail-digest:${accountId}`,
+ payload,
+ retries: 3,
+ stepIndex: 0,
+ });
+};
+
+/** Holds a delivery for the digest of the window it arrived in. */
+export const holdForDigest = (
+ account: Pick<AgentAccountView, 'id'>,
+ config: Pick<ResolvedWakeConfig, 'digestMs'>,
+ now = Date.now(),
+): Promise<void> => scheduleDigestFlush(account.id, digestWindowEnd(now, config.digestMs));
+
+/**
+ * The prompt of a digest run. As with a single wake, only the instructions are ours; every message
+ * rides inside the `<untrusted_inbox>` fence.
+ */
+export const buildDigestPrompt = (account: AgentAccountView, messages: AgentInboxEntry[]): string =>
+ [
+ `${messages.length} message${messages.length === 1 ? '' : 's'} arrived for your ${account.kind} account ${account.identifier} and were held for this digest, oldest first.`,
+ 'Go through them together: work out which ones need your owner, which ones you can take care of, and which are noise. Tell your owner only about what needs them, briefly, and say why. Any message you send is held for their approval.',
+ fenceUntrustedInbox(
+ messages.map((message) =>
+ toUntrustedInboxEntry(message, { maxBodyChars: DIGEST_BODY_PREVIEW_CHARS }),
+ ),
+ ),
+ ].join('\n\n');
+
+/** Starts the digest run. Injected so the flush can be exercised without the run pipeline. */
+export type DigestRunStarter = (input: {
+ account: AgentAccountView;
+ messages: AgentInboxEntry[];
+}) => Promise<{ error?: string; topicId?: string }>;
+
+/** Production starter: one run in a fresh topic, stamped as an inbox event like a single wake. */
+export const createDigestRunStarter =
+ (db: LobeChatDatabase): DigestRunStarter =>
+ async ({ account, messages }) => {
+ const service = new AiAgentService(db, account.userId, {
+ workspaceId: account.workspaceId ?? undefined,
+ });
+ const result = await service.execAgent({
+ agentId: account.agentId,
+ appContext: { scope: 'agent' },
+ prompt: buildDigestPrompt(account, messages),
+ trigger: RequestTrigger.Inbox,
+ });
+
+ return { error: result.error, topicId: result.topicId };
+ };
+
+export type DigestFlushResult =
+ | 'empty'
+ | 'no-account'
+ | 'started'
+ /** The owner switched the account's wake off after the messages were held. */
+ | 'wake-off';
+
+/**
+ * QStash delivered a flush: takes what the account is holding and starts one run for it.
+ *
+ * A flush may arrive more than once; the claim on each item makes a second one find nothing. A run
+ * that fails to start gives its items back, books the next window's flush and throws, so QStash
+ * retries this one and, should every retry fail, the next window tries again instead of the
+ * messages waiting for an unrelated delivery. A full batch whose follow-up booking fails throws
+ * too: the batch itself is done, and the retry finishes the leftover mail.
+ */
+export const runDigestFlush = async (
+ db: LobeChatDatabase,
+ payload: DigestFlushPayload,
+ startRun: DigestRunStarter = createDigestRunStarter(db),
+): Promise<DigestFlushResult> => {
+ const account = await AgentAccountModel.findByIdUnscoped(db, payload.accountId);
+ if (!account || account.status === 'revoked' || account.status === 'suspended') {
+ return 'no-account';
+ }
+ const config = resolveWakeConfig(account.settings);
+ if (config.mode === 'off') return 'wake-off';
+
+ const ids = await AgentInboxModel.claimDigest(db, {
+ accountId: account.id,
+ limit: DIGEST_BATCH_LIMIT,
+ since: new Date(Date.now() - DIGEST_LOOKBACK_MS),
+ });
+ if (ids.length === 0) return 'empty';
+
+ const giveBack = async (error: unknown): Promise<never> => {
+ console.error(
+ '[mailDigest] the run for %d held message(s) of account %s did not start:',
+ ids.length,
+ account.id,
+ error,
+ );
+ await AgentInboxModel.releaseWakes(db, ids).catch(() => undefined);
+ // The window after this flush's own, even when QStash delivered it early.
+ await holdForDigest(account, config, Math.max(Date.now(), payload.at)).catch((bookError) =>
+ console.error('[mailDigest] booking the next flush for %s failed:', account.id, bookError),
+ );
+ throw error instanceof Error ? error : new Error(String(error));
+ };
+
+ let result: Awaited<ReturnType<DigestRunStarter>>;
+ try {
+ const messages = await AgentInboxModel.findEntries(db, ids);
+ result = await startRun({ account, messages });
+ } catch (error) {
+ return giveBack(error);
+ }
+ if (result.error) return giveBack(new Error(`digest run did not start: ${result.error}`));
+
+ // The run has its messages. Failing to stamp them must not fail the flush, or QStash's retry
+ // would start a second run at once. The claims keep them out of digests for the claim lease;
+ // past it a later digest would take them again, so the failure is logged loudly.
+ try {
+ await AgentInboxModel.markManyWoken(db, ids, result.topicId);
+ } catch (error) {
+ console.error(
+ '[mailDigest] run started but marking messages %s read failed:',
+ ids.join(','),
+ error,
+ );
+ }
+
+ // A full batch means mail is still waiting, and only this booking would come for it: nobody
+ // writes to the account again just to book one. Fail the flush rather than acknowledge it, so
+ // QStash retries β€” the batch above is already stamped, so the retry takes the leftover mail,
+ // runs it and books its own follow-up instead of leaving it unread.
+ if (ids.length === DIGEST_BATCH_LIMIT) {
+ try {
+ await scheduleDigestFlush(account.id, Date.now() + DIGEST_FOLLOW_UP_MS);
+ } catch (error) {
+ console.error('[mailDigest] booking the follow-up flush for %s failed:', account.id, error);
+ throw error instanceof Error ? error : new Error(String(error));
+ }
+ }
+
+ log('started a digest run for %d message(s) of account %s', ids.length, account.id);
+ return 'started';
+};
diff --git a/apps/server/src/services/agentIdentity/wake/policies.ts b/apps/server/src/services/agentIdentity/wake/policies.ts
new file mode 100644
index 00000000000..fadb8f52784
--- /dev/null
+++ b/apps/server/src/services/agentIdentity/wake/policies.ts
@@ -0,0 +1,96 @@
+import type { AgentAccountView } from '@/database/models/agentAccount';
+import type { AgentInboxEntry } from '@/database/models/agentInbox';
+import { normalizeMailAddress } from '@/database/models/agentMail';
+import type {
+ WakePolicy,
+ WakePolicyMode,
+ WakePolicyResult,
+ WakeSignal,
+} from '@/server/services/conversationWake/types';
+
+import { isWakeSender } from './config';
+
+export const MAIL_RULES_POLICY_ID = 'mail-wake:rules';
+
+/** Revision of the mail-wake pipeline recorded on every decision. Bump when the judgement changes. */
+export const MAIL_WAKE_PIPELINE_VERSION = 'mail-wake@1';
+
+/**
+ * Local parts that only machines send from: bounces, notification relays, no-reply senders. Mail
+ * from them is never a reason to interrupt anyone at once; the digest still reads it.
+ */
+const AUTOMATED_LOCAL_PART =
+ /^(?:no[-_.]?reply|do[-_.]?not[-_.]?reply|mailer[-_.]?daemon|postmaster|bounces?|notifications?|notify|alerts?|newsletters?|news|digest|updates?|marketing|info)(?:[-_.+].*)?$/;
+
+/** Longest text the policies read: the subject and the start of the body are what they judge. */
+const SIGNAL_TEXT_LENGTH = 2000;
+
+/**
+ * One inbox message as a wake policy reads it.
+ *
+ * The author's `id` is the sender's address and the channel is the account, keyed by thread, so
+ * the shared wake types carry a mail without a mail-specific field.
+ */
+export const toMailWakeSignal = (account: AgentAccountView, entry: AgentInboxEntry): WakeSignal => {
+ const from = normalizeMailAddress(entry.from);
+
+ return {
+ agentId: account.agentId,
+ author: {
+ id: from,
+ isBot: AUTOMATED_LOCAL_PART.test(from.slice(0, from.lastIndexOf('@'))),
+ isMe: from === normalizeMailAddress(account.identifier),
+ isOwner: false,
+ isSystem: false,
+ },
+ channelKeys: {
+ channelKey: `agent-mail:${account.id}`,
+ ids: [account.id],
+ threadKey: entry.threadKey ?? undefined,
+ },
+ hasAttachments: entry.attachments.length > 0,
+ message: [entry.subject, entry.text].filter(Boolean).join('\n\n').slice(0, SIGNAL_TEXT_LENGTH),
+ platform: account.provider,
+ platformThreadId: entry.threadKey ?? undefined,
+ timestamp: entry.receivedAt.getTime(),
+ };
+};
+
+const result = (
+ verdict: WakePolicyResult['verdict'],
+ reason: string,
+ confidence: number,
+): WakePolicyResult => ({ confidence, reason, tags: ['mail-rule', reason], verdict });
+
+/**
+ * The rules that decide whether a message is worth a run of its own right now.
+ *
+ * - The account's own address and machine senders (no-reply, bounces, notification relays) never
+ * are; they wait for the digest.
+ * - A sender the owner listed always is.
+ * - Anything else has no opinion here, and an abstaining message waits for the digest:
+ * being able to reach the address is not, by itself, a reason to start a run.
+ *
+ * A reply in a thread the agent itself wrote to does not reach this policy: the aggregator wakes
+ * for it on its fast path (`replyToBot`).
+ */
+export const createMailRulesPolicy = (
+ mode: WakePolicyMode,
+ wakeSenders: readonly string[],
+): WakePolicy => ({
+ evaluate: ({ signal }) => {
+ const { author } = signal;
+
+ if (author?.isMe) return result('deny', 'self-message', 1);
+ if (author?.isBot) return result('deny', 'automated-sender', 0.9);
+ if (author?.id && isWakeSender(author.id, wakeSenders)) {
+ return result('allow', 'wake-sender', 1);
+ }
+
+ return result('abstain', 'no-rule-hit', 0);
+ },
+ id: MAIL_RULES_POLICY_ID,
+ mode,
+ requires: [],
+ version: 1,
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.outboundAudit.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.outboundAudit.test.ts
new file mode 100644
index 00000000000..66b5be403ad
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/runtimeFactory.outboundAudit.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { AGENT_ACCOUNT_OUTBOUND_AUDIT } from '@lobechat/builtin-tool-agent-account';
+import { RequestTrigger } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeFactoryDeps } from '../runtimeFactory';
+import { createAgentRuntime } from '../runtimeFactory';
+
+const inbox = vi.hoisted(() => ({ isInboxTopic: vi.fn() }));
+vi.mock('@/database/models/agentInbox', () => ({ AgentInboxModel: inbox }));
+
+/** The account outbound audit of a runtime built for a run with this origin. */
+const outboundAuditFor = async (origin: { topicId?: string; trigger: RequestTrigger }) => {
+ const agentFactory = vi.fn((config: any) => ({ config, runner: vi.fn() }));
+ const deps = {
+ agentFactory,
+ completeGroupMemberBarrier: vi.fn(),
+ coordinator: { isInterrupted: vi.fn(), loadAgentState: vi.fn() },
+ delegate: {},
+ serverDB: {},
+ userId: 'user_1',
+ } as unknown as RuntimeFactoryDeps;
+
+ await createAgentRuntime(deps, {
+ agentState: { origin: { ...origin, userId: 'user_1' } },
+ operationId: 'op_1',
+ stepIndex: 0,
+ });
+
+ return agentFactory.mock.calls[0][0].dynamicInterventionAudits[AGENT_ACCOUNT_OUTBOUND_AUDIT];
+};
+
+const threadReply = { text: 'my owner said…', threadKey: 'thread_1', to: '[email protected]' };
+
+describe('createAgentRuntime β€” agent account outbound audit', () => {
+ beforeEach(() => {
+ inbox.isInboxTopic.mockReset().mockResolvedValue(false);
+ });
+
+ it('holds a thread reply for approval in a run an inbound message started', async () => {
+ const audit = await outboundAuditFor({ trigger: RequestTrigger.Inbox });
+
+ await expect(audit(threadReply)).resolves.toBe(true);
+ });
+
+ it('holds a thread reply in any later turn of a topic that holds outside mail', async () => {
+ // e.g. the continuation a background sub-agent starts, stamped `chat`.
+ inbox.isInboxTopic.mockResolvedValue(true);
+ const audit = await outboundAuditFor({ topicId: 'tpc_inbox', trigger: RequestTrigger.Chat });
+
+ await expect(audit(threadReply)).resolves.toBe(true);
+ expect(inbox.isInboxTopic).toHaveBeenCalledWith({}, 'tpc_inbox');
+ });
+
+ it('holds the send when the topic cannot be checked', async () => {
+ inbox.isInboxTopic.mockRejectedValue(new Error('db down'));
+ const audit = await outboundAuditFor({ topicId: 'tpc_any', trigger: RequestTrigger.Chat });
+
+ await expect(audit(threadReply)).resolves.toBe(true);
+ });
+
+ it('keeps the thread-reply exemption in a topic the owner started with no outside mail', async () => {
+ const audit = await outboundAuditFor({ topicId: 'tpc_chat', trigger: RequestTrigger.Chat });
+
+ await expect(audit(threadReply)).resolves.toBe(false);
+ });
+
+ it('looks nothing up until the agent actually sends', async () => {
+ await outboundAuditFor({ topicId: 'tpc_chat', trigger: RequestTrigger.Chat });
+
+ expect(inbox.isInboxTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
index 534061ad97a..f57040bb1a8 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
@@ -1,5 +1,9 @@
import type { AgentRunLlmExecutor, AgentState } from '@lobechat/agent-runtime';
import { AgentRuntime, findInMessages, GeneralChatAgent } from '@lobechat/agent-runtime';
+import {
+ AGENT_ACCOUNT_OUTBOUND_AUDIT,
+ createAgentAccountOutboundAudit,
+} from '@lobechat/builtin-tool-agent-account';
import { DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
@@ -7,6 +11,7 @@ import { type UIChatMessage } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
+import { AgentInboxModel } from '@/database/models/agentInbox';
import {
createRuntimeExecutors,
type RuntimeExecutorContext,
@@ -122,6 +127,27 @@ export async function getLlmExecutor(
}
}
+/**
+ * Whether a run may be acting on mail from outside: an inbound message started it, or it runs in
+ * a topic that holds one. The second covers every later turn there β€” a background sub-agent's
+ * continuation, the owner chatting on β€” whatever trigger it carries. Fails closed: a lookup that
+ * errors holds the send.
+ */
+const holdsMailFromOutside = async (
+ db: RuntimeFactoryDeps['serverDB'],
+ origin: AgentState['origin'] | undefined,
+): Promise<boolean> => {
+ if (origin?.trigger === RequestTrigger.Inbox) return true;
+ if (!origin?.topicId) return false;
+
+ try {
+ return await AgentInboxModel.isInboxTopic(db, origin.topicId);
+ } catch (error) {
+ log('inbox topic lookup failed for %s; holding the send: %O', origin.topicId, error);
+ return true;
+ }
+};
+
/**
* Create Agent Runtime instance
*/
@@ -173,6 +199,11 @@ export async function createAgentRuntime(
},
dynamicInterventionAudits: {
...dynamicInterventionAudits,
+ // A run that may be acting on mail from outside answers to whoever wrote
+ // it: every send it makes waits for the owner's approval.
+ [AGENT_ACCOUNT_OUTBOUND_AUDIT]: createAgentAccountOutboundAudit({
+ holdEverySend: () => holdsMailFromOutside(deps.serverDB, origin),
+ }),
[DASHBOARD_DRY_RUN_AUDIT]: createWidgetDryRunAudit(
deps.serverDB,
origin?.userId ?? deps.userId,
diff --git a/packages/builtin-skills/src/lobehub/references/agent.ts b/packages/builtin-skills/src/lobehub/references/agent.ts
index 925b38d468b..6dd22b40af2 100644
--- a/packages/builtin-skills/src/lobehub/references/agent.ts
+++ b/packages/builtin-skills/src/lobehub/references/agent.ts
@@ -23,6 +23,7 @@ user mounts) and receive mail on them.
- \`lh agent account provision [agentId] [--prefix <handle>]\` - Open a new Agent Mail inbox; the issued address may differ from the prefix
- \`lh agent account mount [agentId] -i <identifier> -k <kind> [-c receive,send,login]\` - Attach an account the user already holds
- \`lh agent account edit <accountId> [-n <name>] [-c <capabilities>]\` - Update non-secret fields
+- \`lh agent account edit <accountId> --wake <on|off> [--wake-senders <[email protected],@y.com>] [--digest-minutes <n>]\` - Set how mail wakes the agent: \`on\` (default) wakes at once for listed senders and replies to the agent, and holds the rest for one digest run per window; \`off\` never wakes
- \`lh agent account set-credential <accountId> --credential-file <path|->\` - Store a secret (write-only; reads a JSON object so it stays out of shell history)
- \`lh agent account revoke <accountId> --yes\` - Release the address and purge its credential
- \`lh agent inbox list [agentId] [-u] [-L <n>] [--before <cursor>]\` - List received mail, newest first
diff --git a/packages/builtin-tool-agent-account/src/index.ts b/packages/builtin-tool-agent-account/src/index.ts
index 8288860c210..3b362b543ab 100644
--- a/packages/builtin-tool-agent-account/src/index.ts
+++ b/packages/builtin-tool-agent-account/src/index.ts
@@ -1,5 +1,9 @@
export { AgentAccountManifest } from './manifest';
-export { AGENT_ACCOUNT_OUTBOUND_AUDIT, agentAccountOutboundAudit } from './outboundAudit';
+export {
+ AGENT_ACCOUNT_OUTBOUND_AUDIT,
+ agentAccountOutboundAudit,
+ createAgentAccountOutboundAudit,
+} from './outboundAudit';
export { systemPrompt } from './systemRole';
export {
AgentAccountApiName,
diff --git a/packages/builtin-tool-agent-account/src/outboundAudit.test.ts b/packages/builtin-tool-agent-account/src/outboundAudit.test.ts
index fcc10a1353e..545a3d14f90 100644
--- a/packages/builtin-tool-agent-account/src/outboundAudit.test.ts
+++ b/packages/builtin-tool-agent-account/src/outboundAudit.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, it } from 'vitest';
import { AgentAccountManifest } from './manifest';
-import { AGENT_ACCOUNT_OUTBOUND_AUDIT, agentAccountOutboundAudit } from './outboundAudit';
+import {
+ AGENT_ACCOUNT_OUTBOUND_AUDIT,
+ agentAccountOutboundAudit,
+ createAgentAccountOutboundAudit,
+} from './outboundAudit';
import { AgentAccountApiName } from './types';
describe('agentAccountOutboundAudit', () => {
@@ -30,3 +34,21 @@ describe('agentAccountOutboundAudit', () => {
});
});
});
+
+describe('createAgentAccountOutboundAudit', () => {
+ const threadReply = { text: 'my owner said…', threadKey: 'thread_1', to: '[email protected]' };
+
+ it('holds even a thread reply in a run an inbound message started', async () => {
+ const audit = createAgentAccountOutboundAudit({ holdEverySend: async () => true });
+
+ await expect(audit(threadReply)).resolves.toBe(true);
+ await expect(audit({ text: 'hi', to: '[email protected]' })).resolves.toBe(true);
+ });
+
+ it('keeps the thread-reply exemption in a run the owner started', async () => {
+ const audit = createAgentAccountOutboundAudit({ holdEverySend: () => false });
+
+ await expect(audit(threadReply)).resolves.toBe(false);
+ await expect(audit({ text: 'hi', to: '[email protected]' })).resolves.toBe(true);
+ });
+});
diff --git a/packages/builtin-tool-agent-account/src/outboundAudit.ts b/packages/builtin-tool-agent-account/src/outboundAudit.ts
index f77b99676a2..8fc1d220236 100644
--- a/packages/builtin-tool-agent-account/src/outboundAudit.ts
+++ b/packages/builtin-tool-agent-account/src/outboundAudit.ts
@@ -23,4 +23,24 @@ export const agentAccountOutboundAudit: DynamicInterventionResolver = async (too
return !(typeof threadKey === 'string' && threadKey.trim().length > 0);
};
+/**
+ * The outbound gate for a run that may be acting on mail from outside (the
+ * server runtime builds one per run). Nobody the owner trusts asked for such a
+ * run: whoever wrote the mail did, and the thread-reply exemption above would
+ * let them have the agent answer them with whatever it can read β€” the owner's
+ * memory, documents, earlier topics β€” without the owner seeing it. So there
+ * every send is held for the owner, thread reply or not.
+ *
+ * `holdEverySend` is asked only when the agent actually sends, so a lookup
+ * behind it costs nothing on the turns that do not.
+ */
+export const createAgentAccountOutboundAudit =
+ ({
+ holdEverySend,
+ }: {
+ holdEverySend: () => Promise<boolean> | boolean;
+ }): DynamicInterventionResolver =>
+ async (toolArgs, metadata) =>
+ (await holdEverySend()) || agentAccountOutboundAudit(toolArgs, metadata);
+
export const AGENT_ACCOUNT_OUTBOUND_AUDIT = 'agentAccountOutboundAudit';
diff --git a/packages/database/src/models/__tests__/agentInbox.digest.test.ts b/packages/database/src/models/__tests__/agentInbox.digest.test.ts
new file mode 100644
index 00000000000..da285c06d30
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentInbox.digest.test.ts
@@ -0,0 +1,228 @@
+// @vitest-environment node
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentAccounts, agentInboxMessages, agents, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentAccountModel } from '../agentAccount';
+import { AgentInboxModel, WAKE_CLAIM_LEASE_SECONDS } from '../agentInbox';
+import { AgentMailModel } from '../agentMail';
+import { SignalModel } from '../signal';
+import { SignalDecisionModel } from '../signalDecision';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-inbox-digest-user';
+const agentId = 'agent-inbox-digest-agent';
+let accountId = '';
+
+/**
+ * Lands one mail in the account's inbox, received `minutesAgo` minutes ago. Unless `deferred` is
+ * false, a wake decision deferred it to the digest, as the inbound edge records it.
+ */
+const deliver = async (providerMessageId: string, minutesAgo: number, deferred = true) => {
+ const receivedAt = new Date(Date.now() - minutesAgo * 60_000);
+ const { signal } = await SignalModel.record(
+ serverDB,
+ {
+ accountId,
+ agentId,
+ externalId: `evt_${providerMessageId}`,
+ source: 'agent-mail',
+ type: 'message.received',
+ },
+ { userId },
+ );
+ if (deferred) {
+ await new SignalDecisionModel(serverDB, userId).record({
+ agentId,
+ outcome: 'defer',
+ pipelineVersion: 'mail-wake@1',
+ scopeKey: `agent-mail:${accountId}`,
+ signalId: signal.id,
+ });
+ }
+ const { mail } = await AgentMailModel.record(
+ serverDB,
+ {
+ accountId,
+ agentId,
+ deliveredAt: receivedAt,
+ direction: 'inbound',
+ fromAddress: `${providerMessageId}@example.com`,
+ provider: 'agent-mail',
+ providerMessageId,
+ signalId: signal.id,
+ subject: `Subject ${providerMessageId}`,
+ text: `Body ${providerMessageId}`,
+ to: [{ address: '[email protected]' }],
+ },
+ { userId },
+ );
+ const { item } = await AgentInboxModel.deliver(
+ serverDB,
+ {
+ accountId,
+ agentId,
+ receivedAt,
+ sender: mail.fromAddress,
+ sourceId: mail.id,
+ sourceType: 'mail',
+ title: mail.subject,
+ },
+ { userId },
+ );
+
+ return item;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ const account = await new AgentAccountModel(serverDB, userId).create({
+ agentId,
+ capabilities: { receive: true, send: false },
+ identifier: '[email protected]',
+ kind: 'mail',
+ provider: 'agent-mail',
+ });
+ accountId = account.id;
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentInboxMessages);
+ await serverDB.delete(agentAccounts);
+ await serverDB.delete(users);
+});
+
+describe('AgentInboxModel.claimDigest', () => {
+ const since = () => new Date(Date.now() - 24 * 60 * 60_000);
+
+ it('takes the held items oldest first, up to the limit, and only once', async () => {
+ const newest = await deliver('m3', 1);
+ const oldest = await deliver('m1', 30);
+ const middle = await deliver('m2', 10);
+
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 2, since: since() }),
+ ).toEqual([oldest.id, middle.id]);
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 2, since: since() }),
+ ).toEqual([newest.id]);
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 2, since: since() }),
+ ).toEqual([]);
+ });
+
+ it('leaves out what was read, what a live wake holds, and what is older than `since`', async () => {
+ const read = await deliver('read', 5);
+ const woken = await deliver('woken', 5);
+ await deliver('old', 3 * 24 * 60);
+ const held = await deliver('held', 5);
+
+ await new AgentInboxModel(serverDB, userId).markRead([read.id]);
+ expect(await AgentInboxModel.claimWake(serverDB, woken.id)).toBe(true);
+
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since: since() }),
+ ).toEqual([held.id]);
+ });
+
+ it('leaves out mail no wake decision deferred, such as mail stored while wake was off', async () => {
+ await deliver('stored', 5, false);
+ const held = await deliver('held', 5);
+
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since: since() }),
+ ).toEqual([held.id]);
+ });
+
+ it('takes over an item whose claim outlived its lease', async () => {
+ const stale = await deliver('stale', 5);
+ await serverDB
+ .update(agentInboxMessages)
+ .set({
+ wakeClaimedAt: sql`now() - make_interval(secs => ${WAKE_CLAIM_LEASE_SECONDS + 60})`,
+ })
+ .where(eq(agentInboxMessages.id, stale.id));
+
+ expect(
+ await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since: since() }),
+ ).toEqual([stale.id]);
+ });
+
+ it('lets exactly one of two concurrent flushes take each item', async () => {
+ const items = await Promise.all(['a', 'b', 'c'].map((id, i) => deliver(id, i + 1)));
+
+ const [first, second] = await Promise.all([
+ AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since: since() }),
+ AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since: since() }),
+ ]);
+
+ expect([...first, ...second].sort()).toEqual(items.map((item) => item.id).sort());
+ });
+});
+
+describe('AgentInboxModel.releaseWakes', () => {
+ it('gives every claim back in one go, so the next digest can take the items again', async () => {
+ const items = await Promise.all(['r1', 'r2'].map((id, i) => deliver(id, i + 1)));
+ const since = new Date(Date.now() - 24 * 60 * 60_000);
+ const claimed = await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since });
+ expect(claimed).toHaveLength(2);
+
+ await AgentInboxModel.releaseWakes(serverDB, claimed);
+
+ expect(
+ (await serverDB.select().from(agentInboxMessages)).map((row) => row.wakeClaimedAt),
+ ).toEqual([null, null]);
+ expect(
+ (await AgentInboxModel.claimDigest(serverDB, { accountId, limit: 10, since })).sort(),
+ ).toEqual(items.map((item) => item.id).sort());
+ });
+});
+
+describe('AgentInboxModel.markManyWoken', () => {
+ it('marks every item read and remembers the topic, keeping an earlier read time', async () => {
+ const earlier = await deliver('earlier', 9);
+ const later = await deliver('later', 1);
+ const readAt = new Date('2026-11-01T00:00:00.000Z');
+ await serverDB
+ .update(agentInboxMessages)
+ .set({ readAt })
+ .where(eq(agentInboxMessages.id, earlier.id));
+
+ await AgentInboxModel.markManyWoken(serverDB, [earlier.id, later.id], undefined);
+
+ const rows = await serverDB.select().from(agentInboxMessages);
+ expect(rows.find((row) => row.id === earlier.id)?.readAt).toEqual(readAt);
+ expect(rows.find((row) => row.id === later.id)?.readAt).not.toBeNull();
+ });
+});
+
+describe('AgentInboxModel.isInboxTopic', () => {
+ it('tells a topic that holds outside mail from one that does not', async () => {
+ const item = await deliver('topic', 1);
+ await serverDB.insert(topics).values({ id: 'tpc_digest', userId });
+ await AgentInboxModel.markManyWoken(serverDB, [item.id], 'tpc_digest');
+
+ expect(await AgentInboxModel.isInboxTopic(serverDB, 'tpc_digest')).toBe(true);
+ expect(await AgentInboxModel.isInboxTopic(serverDB, 'tpc_other')).toBe(false);
+ });
+});
+
+describe('AgentInboxModel.findEntries', () => {
+ it('reads several items with their content, oldest first', async () => {
+ const later = await deliver('later', 1);
+ const earlier = await deliver('earlier', 9);
+
+ const entries = await AgentInboxModel.findEntries(serverDB, [later.id, earlier.id]);
+
+ expect(entries.map((entry) => [entry.id, entry.subject, entry.text])).toEqual([
+ [earlier.id, 'Subject earlier', 'Body earlier'],
+ [later.id, 'Subject later', 'Body later'],
+ ]);
+ expect(await AgentInboxModel.findEntries(serverDB, [])).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/agentInbox.ts b/packages/database/src/models/agentInbox.ts
index ec085e03518..a7731db8775 100644
--- a/packages/database/src/models/agentInbox.ts
+++ b/packages/database/src/models/agentInbox.ts
@@ -1,8 +1,4 @@
-import type {
- AgentInboxSourceType,
- AgentMailAddress,
- AgentMailAttachment,
-} from '@lobechat/types';
+import type { AgentInboxSourceType, AgentMailAddress, AgentMailAttachment } from '@lobechat/types';
import {
and,
asc,
@@ -21,7 +17,7 @@ import {
} from 'drizzle-orm';
import type { AgentInboxMessageItem, NewAgentInboxMessage } from '../schemas';
-import { agentInboxMessages, agentMails } from '../schemas';
+import { agentInboxMessages, agentMails, signalDecisions } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { agentUsableBy } from '../utils/agent-access';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -293,6 +289,127 @@ export class AgentInboxModel {
return rows.length > 0;
};
+ /**
+ * Take the items of one account that are waiting for a digest: deferred by a
+ * wake decision (a `defer` row in `signal_decisions` for the mail's signal),
+ * unread, unclaimed (or left behind by a dead worker) and received at or
+ * after `since`, oldest first. Mail that was merely left unread β€” stored while
+ * wake was off, or dropped past the wake budget β€” is never swept in. Claimed
+ * the way {@link claimWake} claims one item, so two flushes of the same digest
+ * cannot both take the same item.
+ *
+ * Returns the claimed items' ids; their content is read with
+ * {@link findEntries}.
+ */
+ static claimDigest = async (
+ db: LobeChatDatabase,
+ params: { accountId: string; limit: number; since: Date },
+ ): Promise<string[]> => {
+ const waiting = and(
+ eq(agentInboxMessages.accountId, params.accountId),
+ isNull(agentInboxMessages.readAt),
+ gte(agentInboxMessages.receivedAt, params.since),
+ or(
+ isNull(agentInboxMessages.wakeClaimedAt),
+ lt(
+ agentInboxMessages.wakeClaimedAt,
+ sql`now() - make_interval(secs => ${WAKE_CLAIM_LEASE_SECONDS})`,
+ ),
+ ),
+ sql`exists (
+ select 1 from ${agentMails}
+ join ${signalDecisions} on ${signalDecisions.signalId} = ${agentMails.signalId}
+ where ${agentMails.id} = ${agentInboxMessages.sourceId}
+ and ${agentInboxMessages.sourceType} = 'mail'
+ and ${signalDecisions.outcome} = 'defer'
+ )`,
+ );
+
+ // Two statements, not `update … where id in (select … limit … for update
+ // skip locked)`: a planner may run that subquery once per row, and the
+ // limit then no longer bounds the batch.
+ return db.transaction(async (tx) => {
+ const candidates = await tx
+ .select({ id: agentInboxMessages.id })
+ .from(agentInboxMessages)
+ .where(waiting)
+ .orderBy(asc(agentInboxMessages.receivedAt))
+ .limit(params.limit)
+ .for('update', { skipLocked: true });
+ if (candidates.length === 0) return [];
+
+ const claimed = await tx
+ .update(agentInboxMessages)
+ .set({ wakeClaimedAt: sql`now()` })
+ .where(
+ and(
+ inArray(
+ agentInboxMessages.id,
+ candidates.map((row) => row.id),
+ ),
+ waiting,
+ ),
+ )
+ .returning({ id: agentInboxMessages.id });
+ const ids = new Set(claimed.map((row) => row.id));
+
+ return candidates.map((row) => row.id).filter((id) => ids.has(id));
+ });
+ };
+
+ /** Several items with their content, unscoped, oldest first β€” for the digest run. */
+ static findEntries = async (db: LobeChatDatabase, ids: string[]): Promise<AgentInboxEntry[]> => {
+ if (ids.length === 0) return [];
+
+ return db
+ .select(entryColumns)
+ .from(agentInboxMessages)
+ .leftJoin(agentMails, mailOfItem)
+ .where(inArray(agentInboxMessages.id, ids))
+ .orderBy(asc(agentInboxMessages.receivedAt));
+ };
+
+ /** {@link releaseWake} for every item of a digest run that did not start, in one statement. */
+ static releaseWakes = async (db: LobeChatDatabase, ids: string[]): Promise<void> => {
+ if (ids.length === 0) return;
+
+ await db
+ .update(agentInboxMessages)
+ .set({ wakeClaimedAt: null })
+ .where(inArray(agentInboxMessages.id, ids));
+ };
+
+ /** {@link markWoken} for every item of one digest run, in one statement. */
+ static markManyWoken = async (
+ db: LobeChatDatabase,
+ ids: string[],
+ topicId: string | undefined,
+ ): Promise<void> => {
+ if (ids.length === 0) return;
+
+ await db
+ .update(agentInboxMessages)
+ .set({
+ readAt: sql`coalesce(${agentInboxMessages.readAt}, now())`,
+ ...(topicId ? { topicId } : {}),
+ })
+ .where(inArray(agentInboxMessages.id, ids));
+ };
+
+ /**
+ * Whether a topic was opened or continued by mail from outside. Unscoped:
+ * the runtime asks while gating a send, keyed by the run's own topic.
+ */
+ static isInboxTopic = async (db: LobeChatDatabase, topicId: string): Promise<boolean> => {
+ const [row] = await db
+ .select({ id: agentInboxMessages.id })
+ .from(agentInboxMessages)
+ .where(eq(agentInboxMessages.topicId, topicId))
+ .limit(1);
+
+ return !!row;
+ };
+
/** Give a wake claim back after the wake failed, so the provider's retry can wake it. */
static releaseWake = async (db: LobeChatDatabase, id: string): Promise<void> => {
await db
diff --git a/packages/database/src/models/agentMail.ts b/packages/database/src/models/agentMail.ts
index 0757fb2e09a..e7be7a527f7 100644
--- a/packages/database/src/models/agentMail.ts
+++ b/packages/database/src/models/agentMail.ts
@@ -255,6 +255,33 @@ export class AgentMailModel {
return row;
};
+ /**
+ * Whether the agent sent mail in this thread to `address` (as a `To` or `Cc`
+ * recipient). Unscoped: the inbound edge asks before any user is known.
+ */
+ static hasSentInThreadTo = async (
+ db: LobeChatDatabase,
+ params: { accountId: string; address: string; threadKey: string },
+ ): Promise<boolean> => {
+ const [row] = await db
+ .select({ id: agentMails.id })
+ .from(agentMails)
+ .where(
+ and(
+ eq(agentMails.accountId, params.accountId),
+ eq(agentMails.threadKey, params.threadKey),
+ eq(agentMails.direction, 'outbound'),
+ sql`exists (
+ select 1 from jsonb_array_elements(${agentMails.to} || ${agentMails.cc}) as recipient
+ where lower(recipient->>'address') = ${normalizeMailAddress(params.address)}
+ )`,
+ ),
+ )
+ .limit(1);
+
+ return !!row;
+ };
+
/** One account's thread, oldest first β€” both what arrived and what the agent sent. */
listThread = async (params: { accountId: string; threadKey: string }): Promise<AgentMailItem[]> =>
this.db