Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(mail): agent mailboxes with inbound threading, spam scoring and Resend delivery
nirholas9cce7cc39c65
diff --git a/api/_lib/mail/config.js b/api/_lib/mail/config.jsnew file mode 100644index 000000000..72888adca--- /dev/null+++ b/api/_lib/mail/config.js@@ -0,0 +1,94 @@+// Agent mail configuration: the receiving domain, the price list, and the+// deliverability limits. Everything a deployment may want to tune lives here so+// the store, the routes and the MCP tools read one source.+//+// Domain: agents.three.ws. `mail.three.ws` already routes to the team's own+// mailbox provider, so agent addresses get a subdomain nothing else uses. Set+// AGENT_MAIL_DOMAIN to point a deployment at the provider's sandbox domain.+//+// Prices are USD and overridable at runtime through app_settings key+// `agent_mail_pricing` ({ "create_usd": 1, "send_usd": 0.01 }) so the owner can+// reprice without a deploy. A malformed or missing row falls back to the+// defaults below, never to free.++import { sql } from '../db.js';++export const DEFAULT_MAIL_DOMAIN = 'agents.three.ws';++export function mailDomain() {+ const d = String(process.env.AGENT_MAIL_DOMAIN || DEFAULT_MAIL_DOMAIN).trim().toLowerCase();+ return d || DEFAULT_MAIL_DOMAIN;+}++export const PRICING_SETTINGS_KEY = 'agent_mail_pricing';++export const DEFAULT_PRICING = Object.freeze({ create_usd: 1, send_usd: 0.01 });++// A quote is valid for ten minutes, the window prompt 03 sets for every preview.+export const QUOTE_TTL_MS = 10 * 60 * 1000;++// Outbound limits. A new mailbox starts narrow and widens daily for two weeks,+// which is how a fresh sending identity earns reputation with receiving+// providers instead of being filtered as a burst sender.+export const WARMUP_DAYS = 14;+export const WARMUP_START = Object.freeze({ perHour: 10, perDay: 30 });+export const WARMUP_FULL = Object.freeze({ perHour: 60, perDay: 500 });++export const MAX_RECIPIENTS = 10;+export const MAX_ATTACHMENTS = 5;+export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;+export const MAX_TOTAL_ATTACHMENT_BYTES = 20 * 1024 * 1024;+export const MAX_TEXT_CHARS = 100_000;+export const MAX_HTML_CHARS = 300_000;++// Inbound attachment storage caps. Anything above is recorded but not stored.+export const MAX_INBOUND_ATTACHMENT_BYTES = 15 * 1024 * 1024;+export const MAX_INBOUND_TOTAL_BYTES = 30 * 1024 * 1024;++// Local parts no agent can take: they are role addresses receiving systems and+// abuse desks expect to reach a human operator.+export const RESERVED_LOCAL_PARTS = new Set([+ 'abuse', 'admin', 'administrator', 'billing', 'help', 'hostmaster', 'info', 'mailer-daemon',+ 'no-reply', 'noreply', 'postmaster', 'root', 'security', 'support', 'webmaster', 'www',+ 'three', 'threews', 'team', 'staff', 'owner', 'dmarc', 'bounce', 'bounces',+]);++function positive(v, fallback) {+ const n = Number(v);+ return Number.isFinite(n) && n > 0 && n < 1000 ? n : fallback;+}++/** Normalize a stored pricing object onto the defaults. Pure, exported for tests. */+export function normalizePricing(raw) {+ const p = raw && typeof raw === 'object' ? raw : {};+ return {+ create_usd: positive(p.create_usd, DEFAULT_PRICING.create_usd),+ send_usd: positive(p.send_usd, DEFAULT_PRICING.send_usd),+ };+}++/** Current price list, read from app_settings with the defaults as the floor. */+export async function mailPricing() {+ try {+ const [row] = await sql`select value from app_settings where key = ${PRICING_SETTINGS_KEY} limit 1`;+ return normalizePricing(row?.value);+ } catch {+ return normalizePricing(null);+ }+}++/**+ * Hourly and daily outbound caps for a mailbox of a given age. Linear ramp from+ * WARMUP_START on day 0 to WARMUP_FULL on day WARMUP_DAYS. Pure.+ */+export function warmupLimits(createdAt, now = Date.now()) {+ const ageDays = Math.max(0, (now - new Date(createdAt).getTime()) / 86_400_000);+ const t = Math.min(1, ageDays / WARMUP_DAYS);+ const lerp = (a, b) => Math.round(a + (b - a) * t);+ return {+ perHour: lerp(WARMUP_START.perHour, WARMUP_FULL.perHour),+ perDay: lerp(WARMUP_START.perDay, WARMUP_FULL.perDay),+ warming: t < 1,+ ageDays: Math.floor(ageDays),+ };+}diff --git a/api/_lib/mail/content-rules.js b/api/_lib/mail/content-rules.jsnew file mode 100644index 000000000..66cfe7f24--- /dev/null+++ b/api/_lib/mail/content-rules.js@@ -0,0 +1,131 @@+// Outbound content rules for agent mail, enforced on the server before any+// charge or send. An agent writes to real people; every message must read like+// correspondence from someone accountable: a real subject, a greeting, a body+// with substance, a sign-off, and no manufactured urgency.+//+// checkOutboundContent() is pure and returns every violation at once, each with+// a stable code, so a model can fix its draft in one pass. The same rules are+// stated to models in the tool descriptions and in docs/agent-mail.md.++const GREETING_RE =+ /^(hi|hello|hey|dear|greetings|good (morning|afternoon|evening|day)|thanks|thank you|welcome|hope you|to whom it may concern)\b/i;+// A salutation line such as "Maria," or "Team at Acme," also counts.+const NAME_SALUTATION_RE = /^[\p{L}][\p{L}\p{M}'. -]{0,58},$/u;++const SIGNOFF_RE =+ /^(best|best regards|best wishes|regards|kind regards|warm regards|warmly|thanks|thank you|many thanks|cheers|sincerely|yours|yours truly|all the best|talk soon|with thanks|respectfully|take care)\b[,.!]?/i;+// A dash signature ("- Ava", or the same with an em dash) also counts.+const DASH_SIGNATURE_RE = /^(-{1,2}|—|–)\s*\p{L}/u;++// Pressure tactics that turn a message into a phishing template. Matched on the+// subject and the body; any hit rejects the draft.+const URGENCY_PATTERNS = [+ { re: /\bact (now|immediately|fast)\b/i, label: 'act now' },+ { re: /\b(urgent|urgently)\b/i, label: 'urgent' },+ { re: /\bimmediate(ly)? action\b/i, label: 'immediate action' },+ { re: /\bfinal (notice|warning|reminder)\b/i, label: 'final notice' },+ { re: /\blast chance\b/i, label: 'last chance' },+ { re: /\b(expires?|ending|ends) (today|tonight|in \d+ (minutes?|hours?))\b/i, label: 'expires today' },+ { re: /\bwithin (the next )?\d+ (minutes?|hours?)\b/i, label: 'within N hours' },+ { re: /\blimited[- ]time (offer|only)\b/i, label: 'limited time offer' },+ { re: /\baccount (has been |will be )?(suspended|locked|closed|terminated|deactivated|compromised)\b/i, label: 'account suspended' },+ { re: /\bverify your (account|identity|wallet|password)\b/i, label: 'verify your account' },+ { re: /\b(don'?t|do not) (miss out|delay)\b/i, label: 'do not miss out' },+ { re: /\bor (else|you will lose)\b/i, label: 'or else' },+];++const MIN_SUBJECT_CHARS = 3;+const MAX_SUBJECT_CHARS = 200;+const MIN_BODY_WORDS = 12;+const MIN_BODY_CHARS = 60;++function lines(text) {+ return String(text || '')+ .replace(/\r\n?/g, '\n')+ .split('\n')+ .map((l) => l.trim())+ .filter(Boolean);+}++function words(s) {+ return String(s || '').match(/[\p{L}\p{N}][\p{L}\p{N}'-]*/gu) || [];+}++function isShouting(subject) {+ const letters = subject.match(/\p{L}/gu) || [];+ if (letters.length < 8) return false;+ const upper = letters.filter((c) => c === c.toUpperCase() && c !== c.toLowerCase()).length;+ return upper / letters.length > 0.8;+}++/** Strip tags from HTML to judge its words. Not a sanitizer; never rendered. */+export function textFromHtml(html) {+ return String(html || '')+ .replace(/<(script|style|head)[\s\S]*?<\/\1>/gi, ' ')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<\/(p|div|li|h[1-6]|tr)>/gi, '\n')+ .replace(/<[^>]+>/g, ' ')+ .replace(/ /gi, ' ')+ .replace(/&/gi, '&')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/'|'/gi, "'")+ .replace(/"/gi, '"')+ .replace(/[ \t]+/g, ' ');+}++/**+ * Judge a draft. `isReply` is true when the send threads onto a received+ * message (in_reply_to set); only then may the subject start with "Re:".+ *+ * @param {{ subject?: string, text?: string, html?: string, isReply?: boolean }} draft+ * @returns {{ ok: boolean, violations: Array<{ code: string, message: string }> }}+ */+export function checkOutboundContent({ subject, text, html, isReply = false } = {}) {+ const violations = [];+ const add = (code, message) => violations.push({ code, message });++ const subj = String(subject || '').trim();+ if (subj.length < MIN_SUBJECT_CHARS) {+ add('subject_missing', 'Write a real subject line that says what the email is about.');+ } else if (subj.length > MAX_SUBJECT_CHARS) {+ add('subject_too_long', `Keep the subject under ${MAX_SUBJECT_CHARS} characters.`);+ } else {+ if (words(subj).length < 2 && !isReply) {+ add('subject_one_word', 'A one-word subject reads as spam. Say what the email is about in a few words.');+ }+ if (isShouting(subj)) add('subject_all_caps', 'Do not write the subject in capital letters.');+ if (/^(re|fwd?|fw)\s*:/i.test(subj) && !isReply) {+ add('subject_fake_reply', 'Only a reply to a received message may start with "Re:" or "Fwd:".');+ }+ if (/!{2,}|\?{3,}|\$\$+/.test(subj)) add('subject_punctuation', 'Drop the repeated punctuation from the subject.');+ }++ const bodyText = String(text || '').trim() || textFromHtml(html).trim();+ const bodyLines = lines(bodyText);+ if (!bodyLines.length) {+ add('body_missing', 'The email has no body. Write the message.');+ } else {+ const first = bodyLines[0];+ if (!(GREETING_RE.test(first) || NAME_SALUTATION_RE.test(first))) {+ add('greeting_missing', 'Open with a greeting, such as "Hi Maria," on the first line.');+ }+ const tail = bodyLines.slice(-3);+ if (!tail.some((l) => SIGNOFF_RE.test(l) || DASH_SIGNATURE_RE.test(l))) {+ add('signoff_missing', 'Close with a sign-off, such as "Best," followed by the agent\'s name.');+ }+ // Substance is judged on the lines between the greeting and the sign-off.+ const core = bodyLines.slice(1, Math.max(1, bodyLines.length - 1)).join(' ');+ if (words(core).length < MIN_BODY_WORDS || core.length < MIN_BODY_CHARS) {+ add('body_too_short', `Write a body of substance: at least ${MIN_BODY_WORDS} words between the greeting and the sign-off.`);+ }+ }++ const haystack = `${subj}\n${bodyText}`;+ const hits = URGENCY_PATTERNS.filter((p) => p.re.test(haystack)).map((p) => p.label);+ if (hits.length) {+ add('deceptive_urgency', `Remove pressure language (${[...new Set(hits)].join(', ')}). State facts and real dates instead.`);+ }++ return { ok: violations.length === 0, violations };+}diff --git a/api/_lib/mail/inbound.js b/api/_lib/mail/inbound.jsnew file mode 100644index 000000000..486b91e93--- /dev/null+++ b/api/_lib/mail/inbound.js@@ -0,0 +1,204 @@+// Inbound agent mail: turn a verified provider webhook into stored messages.+//+// Pipeline for `email.received`:+// 1. Resolve every recipient (to, cc) on the agents domain to an active+// mailbox. Mail for an address nobody holds is dropped, not stored.+// 2. Fetch the full message from the provider (the webhook carries only an+// envelope), score it (./spam.js) and thread it (./threading.js).+// 3. Store attachments in object storage unless the malware scan flagged the+// message; they are only ever served as downloads.+// 4. Insert the message once per mailbox (unique on the provider id, so a+// retried webhook is a no-op), then tell the owner: a `mail_received`+// notification, and the agent's `on_mail_received` wallet intents.+//+// The body of an inbound email is untrusted data. Nothing in this file passes+// it to a model or interprets it: the intents it can fire are owner-authored+// notify/freeze rules that never read the body, and every reader downstream+// (MCP tools, the inbox page) labels it as untrusted content.+//+// Delivery events (`email.delivered`, `email.bounced`, ...) update the status+// of the outbound send they belong to; events for mail this feature did not+// send (platform transactional email) match no row and are ignored.++import { sql } from '../db.js';+import { putObject } from '../r2.js';+import { insertNotification } from '../notify.js';+import { onMailReceived } from '../wallet-intents.js';+import { mailDomain, MAX_INBOUND_ATTACHMENT_BYTES, MAX_INBOUND_TOTAL_BYTES } from './config.js';+import { scoreInbound } from './spam.js';+import { normalizeMessageId, normalizeSubject, parseAddress, parseReferences, threadCandidates } from './threading.js';++function recipientsOnDomain(list, domain) {+ const out = [];+ for (const raw of list || []) {+ const { address } = parseAddress(raw);+ if (address.endsWith(`@${domain}`) && !out.includes(address)) out.push(address);+ }+ return out;+}++function headerValue(headers, name) {+ if (!headers) return null;+ const want = name.toLowerCase();+ for (const [k, v] of Object.entries(headers)) if (String(k).toLowerCase() === want) return Array.isArray(v) ? v.join(' ') : String(v);+ return null;+}++async function resolveThread(mailboxId, { inReplyTo, references, subject, counterparty }) {+ const ids = threadCandidates({ inReplyTo, references });+ if (ids.length) {+ const [hit] = await sql`+ select thread_id from agent_mail_messages+ where mailbox_id = ${mailboxId} and lower(message_id) = any(${ids})+ order by created_at desc limit 1+ `;+ if (hit) return hit.thread_id;+ }+ const norm = normalizeSubject(subject);+ if (norm) {+ const [hit] = await sql`+ select thread_id, subject from agent_mail_messages+ where mailbox_id = ${mailboxId} and created_at > now() - interval '30 days'+ and (from_address = ${counterparty} or ${counterparty} = any(to_addresses))+ order by created_at desc limit 20+ `.then((rows) => rows.filter((r) => normalizeSubject(r.subject) === norm));+ if (hit) return hit.thread_id;+ }+ return null;+}++function safeFilename(name, i) {+ const s = String(name || `attachment-${i + 1}`).replace(/[^\w.\- ]+/g, '_').replace(/^\.+/, '').slice(0, 120);+ return s || `attachment-${i + 1}`;+}++async function storeAttachments({ provider, email, mailboxId, messageKey, quarantine }) {+ const out = [];+ let total = 0;+ for (const [i, a] of email.attachments.entries()) {+ const base = { filename: a.filename, size: a.size, content_type: a.contentType };+ if (quarantine) {+ out.push({ ...base, quarantined: true });+ continue;+ }+ if (a.size > MAX_INBOUND_ATTACHMENT_BYTES || total + a.size > MAX_INBOUND_TOTAL_BYTES) {+ out.push({ ...base, skipped_reason: 'Over the attachment size limit, so it was not stored.' });+ continue;+ }+ try {+ const file = await provider.downloadInboundAttachment(email.id, a.id, MAX_INBOUND_ATTACHMENT_BYTES);+ const key = `agent-mail/${mailboxId}/${messageKey}/${i}-${safeFilename(a.filename, i)}`;+ await putObject({ key, body: file.buffer, contentType: 'application/octet-stream', metadata: { 'original-type': String(file.contentType).slice(0, 100) } });+ total += file.buffer.length;+ out.push({ ...base, size: file.buffer.length, key });+ } catch (err) {+ out.push({ ...base, skipped_reason: `Could not be stored: ${String(err?.message || 'download failed').slice(0, 160)}` });+ }+ }+ return out;+}++/**+ * Store one received email for every mailbox it addresses. Returns the rows+ * created (empty when no mailbox matched or the webhook is a replay).+ */+export async function ingestReceived({ provider, event }) {+ const data = event?.data || {};+ const domain = mailDomain();+ const envelope = recipientsOnDomain([...(data.to || []), ...(data.cc || []), ...(data.bcc || [])], domain);+ if (!envelope.length) return { stored: [], reason: 'no_recipient_on_domain' };++ const mailboxes = await sql`+ select mb.*, a.name as agent_name+ from agent_mailboxes mb join agent_identities a on a.id = mb.agent_id+ where mb.address = any(${envelope}) and mb.status = 'active' and a.deleted_at is null+ `;+ if (!mailboxes.length) return { stored: [], reason: 'no_active_mailbox' };++ const email = await provider.getInbound(data.email_id);+ const verdict = scoreInbound(email.headers);+ const sender = parseAddress(email.from);+ const inReplyTo = normalizeMessageId(headerValue(email.headers, 'in-reply-to'));+ const references = parseReferences(headerValue(email.headers, 'references'));+ const messageId = normalizeMessageId(email.messageId);++ const stored = [];+ for (const mb of mailboxes) {+ const [dupe] = await sql`+ select id from agent_mail_messages+ where mailbox_id = ${mb.id} and direction = 'in' and provider_message_id = ${email.id} limit 1+ `;+ if (dupe) continue;++ const threadId = await resolveThread(mb.id, { inReplyTo, references, subject: email.subject, counterparty: sender.address });+ const messageKey = email.id.replace(/[^\w-]/g, '').slice(0, 64);+ const attachments = await storeAttachments({ provider, email, mailboxId: mb.id, messageKey, quarantine: verdict.quarantineAttachments });++ const [row] = await sql`+ insert into agent_mail_messages+ (mailbox_id, direction, thread_id, from_address, from_name, to_addresses, cc_addresses, reply_to,+ subject, text_body, html_body, attachments, message_id, in_reply_to, references_ids, provider,+ provider_message_id, spam_score, spam_verdict, virus_verdict, auth_results)+ values+ (${mb.id}, 'in', coalesce(${threadId}::uuid, gen_random_uuid()), ${sender.address}, ${sender.name},+ ${email.to.map((t) => parseAddress(t).address)}, ${email.cc.map((c) => parseAddress(c).address)},+ ${email.replyTo.map((r) => parseAddress(r).address)},+ ${String(email.subject || '').slice(0, 998)}, ${email.text}, ${email.html}, ${JSON.stringify(attachments)}::jsonb,+ ${messageId}, ${inReplyTo}, ${references}, ${provider.name}, ${email.id},+ ${verdict.score}, ${verdict.spamVerdict}, ${verdict.virusVerdict}, ${JSON.stringify(verdict.auth)}::jsonb)+ on conflict do nothing+ returning id, thread_id+ `;+ if (!row) continue;+ stored.push({ mailbox: mb, row, verdict });++ if (!verdict.isSpam) {+ insertNotification(mb.user_id, 'mail_received', {+ agent_id: mb.agent_id,+ agent_name: mb.agent_name,+ mailbox: mb.address,+ from: sender.address,+ from_name: sender.name,+ subject: String(email.subject || '').slice(0, 140),+ message_id: row.id,+ link: `/agents/${mb.agent_id}/mail?m=${row.id}`,+ });+ await onMailReceived(mb.agent_id, {+ message_id: row.id,+ from: sender.address,+ subject: String(email.subject || ''),+ spam_score: verdict.score,+ });+ }+ }+ return { stored };+}++const DELIVERY_STATUS = {+ 'email.delivered': 'delivered',+ 'email.delivery_delayed': 'delayed',+ 'email.bounced': 'bounced',+ 'email.complained': 'complained',+ 'email.failed': 'failed',+};++/** Apply a provider delivery event to the outbound send it belongs to. */+export async function applyDeliveryEvent(event) {+ const status = DELIVERY_STATUS[event?.type];+ const providerId = event?.data?.email_id;+ if (!status || !providerId) return { updated: 0 };+ const reason =+ event.data?.bounce?.message || event.data?.failed?.reason || (status === 'complained' ? 'The recipient marked this message as spam.' : null);+ const rows = await sql`+ update agent_mail_sends set+ status = case when status = 'delivered' and ${status} = 'delayed' then status else ${status} end,+ error_message = coalesce(${reason}, error_message),+ updated_at = now()+ where provider_id = ${providerId} and kind = 'send'+ returning message_row_id+ `;+ for (const r of rows) {+ if (r.message_row_id) await sql`update agent_mail_messages set delivery_status = ${status} where id = ${r.message_row_id}`;+ }+ return { updated: rows.length };+}diff --git a/api/_lib/mail/provider.js b/api/_lib/mail/provider.jsnew file mode 100644index 000000000..7dc615cf5--- /dev/null+++ b/api/_lib/mail/provider.js@@ -0,0 +1,42 @@+// The one boundary between agent mail and an email provider.+//+// Everything above this file (store, routes, MCP tools, the inbound webhook)+// speaks the normalized shapes documented here and never imports a provider SDK.+// Adding a second provider is one file that implements the same object and one+// line in PROVIDERS; AGENT_MAIL_PROVIDER selects it.+//+// Provider contract:+// name stable id stored on every message row+// configured() true when sending and reading are possible+// webhookConfigured() true when inbound webhooks can be verified+// send(msg) -> { id } (throws ProviderError)+// msg: { from, to[], cc[], replyTo?, subject, text, html?, headers?,+// attachments?: [{ filename, content: Buffer, contentType }],+// idempotencyKey }+// verifyWebhook({ rawBody, headers }) -> { type, data } (throws ProviderError 'bad_signature')+// getInbound(id) -> NormalizedInbound+// { id, from, to[], cc[], replyTo[], subject, text, html, headers,+// messageId, createdAt, attachments: [{ id, filename, size, contentType }] }+// downloadInboundAttachment(emailId, attachmentId, maxBytes) -> { buffer, contentType, filename }++import { resendProvider } from './resend.js';++export class ProviderError extends Error {+ constructor(code, message, { status = 502, retryable = false } = {}) {+ super(message);+ this.code = code;+ this.status = status;+ this.retryable = retryable;+ }+}++const PROVIDERS = {+ resend: resendProvider,+};++export function mailProvider() {+ const name = String(process.env.AGENT_MAIL_PROVIDER || 'resend').trim().toLowerCase();+ const make = PROVIDERS[name];+ if (!make) throw new ProviderError('provider_unknown', `Unknown AGENT_MAIL_PROVIDER "${name}".`, { status: 500 });+ return make({ ProviderError });+}diff --git a/api/_lib/mail/resend.js b/api/_lib/mail/resend.jsnew file mode 100644index 000000000..eebc5a4a6--- /dev/null+++ b/api/_lib/mail/resend.js@@ -0,0 +1,156 @@+// Resend adapter for agent mail (contract in ./provider.js).+//+// Outbound: POST /emails with an Idempotency-Key, so a retried send never+// delivers twice. Inbound: Resend receives on the agents domain's MX, posts an+// `email.received` webhook signed with the Standard Webhooks scheme (svix-id,+// svix-timestamp, svix-signature), and we fetch the full message and its+// attachments back through the receiving API.+//+// Env: RESEND_API_KEY (shared with api/_lib/email.js), RESEND_WEBHOOK_SECRET+// (the signing secret of the webhook pointed at /api/mail/inbound).++import { Resend } from 'resend';++let _client = null;+let _clientKey = null;+function client() {+ const key = process.env.RESEND_API_KEY;+ if (!_client || _clientKey !== key) {+ _client = new Resend(key);+ _clientKey = key;+ }+ return _client;+}++function headerValue(headers, ...names) {+ for (const n of names) {+ const v = typeof headers?.get === 'function' ? headers.get(n) : headers?.[n];+ if (v) return Array.isArray(v) ? v[0] : String(v);+ }+ return null;+}++function asList(v) {+ if (!v) return [];+ return (Array.isArray(v) ? v : [v]).map((s) => String(s).trim()).filter(Boolean);+}++export function resendProvider({ ProviderError }) {+ function fail(error, fallbackCode) {+ const status = Number(error?.statusCode) || 502;+ const code = error?.name || fallbackCode;+ const message = error?.message || 'The mail provider rejected the request.';+ return new ProviderError(code, message, { status: status >= 500 ? 502 : status, retryable: status >= 500 || status === 429 });+ }++ return {+ name: 'resend',++ configured() {+ return Boolean(process.env.RESEND_API_KEY);+ },++ webhookConfigured() {+ return Boolean(process.env.RESEND_WEBHOOK_SECRET);+ },++ async send({ from, to, cc = [], replyTo, subject, text, html, headers = {}, attachments = [], idempotencyKey }) {+ if (!process.env.RESEND_API_KEY) {+ throw new ProviderError('provider_not_configured', 'Outbound mail is not configured on this deployment (RESEND_API_KEY).', { status: 503 });+ }+ const payload = {+ from,+ to,+ subject,+ text,+ ...(cc.length ? { cc } : {}),+ ...(replyTo ? { replyTo } : {}),+ ...(html ? { html } : {}),+ ...(Object.keys(headers).length ? { headers } : {}),+ ...(attachments.length+ ? { attachments: attachments.map((a) => ({ filename: a.filename, content: a.content, contentType: a.contentType })) }+ : {}),+ };+ let res;+ try {+ res = await client().emails.send(payload, idempotencyKey ? { idempotencyKey } : undefined);+ } catch (err) {+ throw new ProviderError('provider_unreachable', err?.message || 'Could not reach the mail provider.', { retryable: true });+ }+ if (res?.error) throw fail(res.error, 'provider_rejected');+ if (!res?.data?.id) throw new ProviderError('provider_no_id', 'The mail provider accepted the request but returned no message id.');+ return { id: res.data.id };+ },++ verifyWebhook({ rawBody, headers }) {+ const secret = process.env.RESEND_WEBHOOK_SECRET;+ if (!secret) throw new ProviderError('webhook_not_configured', 'RESEND_WEBHOOK_SECRET is not set.', { status: 503 });+ const id = headerValue(headers, 'svix-id', 'webhook-id');+ const timestamp = headerValue(headers, 'svix-timestamp', 'webhook-timestamp');+ const signature = headerValue(headers, 'svix-signature', 'webhook-signature');+ if (!id || !timestamp || !signature) {+ throw new ProviderError('bad_signature', 'The webhook is missing its signature headers.', { status: 401 });+ }+ try {+ return client().webhooks.verify({+ payload: typeof rawBody === 'string' ? rawBody : rawBody.toString('utf8'),+ headers: { id, timestamp, signature },+ webhookSecret: secret,+ });+ } catch {+ throw new ProviderError('bad_signature', 'The webhook signature does not match.', { status: 401 });+ }+ },++ async getInbound(emailId) {+ let res;+ try {+ res = await client().emails.receiving.get(emailId);+ } catch (err) {+ throw new ProviderError('provider_unreachable', err?.message || 'Could not reach the mail provider.', { retryable: true });+ }+ if (res?.error) throw fail(res.error, 'inbound_fetch_failed');+ const e = res.data;+ return {+ id: e.id,+ from: e.from,+ to: asList(e.to),+ cc: asList(e.cc),+ replyTo: asList(e.reply_to),+ subject: e.subject || '',+ text: e.text ?? null,+ html: e.html ?? null,+ headers: e.headers || {},+ messageId: e.message_id || null,+ createdAt: e.created_at || null,+ attachments: (e.attachments || []).map((a) => ({+ id: a.id,+ filename: a.filename || 'attachment',+ size: Number(a.size) || 0,+ contentType: a.content_type || 'application/octet-stream',+ })),+ };+ },++ async downloadInboundAttachment(emailId, attachmentId, maxBytes) {+ let res;+ try {+ res = await client().emails.receiving.attachments.get({ emailId, id: attachmentId });+ } catch (err) {+ throw new ProviderError('provider_unreachable', err?.message || 'Could not reach the mail provider.', { retryable: true });+ }+ if (res?.error) throw fail(res.error, 'attachment_fetch_failed');+ const meta = res.data;+ if (Number(meta.size) > maxBytes) {+ throw new ProviderError('attachment_too_large', `Attachment is ${meta.size} bytes, over the ${maxBytes} byte limit.`, { status: 413 });+ }+ const r = await fetch(meta.download_url, { signal: AbortSignal.timeout(30_000) });+ if (!r.ok) throw new ProviderError('attachment_download_failed', `Attachment download answered ${r.status}.`, { retryable: r.status >= 500 });+ const buffer = Buffer.from(await r.arrayBuffer());+ if (buffer.length > maxBytes) {+ throw new ProviderError('attachment_too_large', `Attachment is over the ${maxBytes} byte limit.`, { status: 413 });+ }+ return { buffer, contentType: meta.content_type || 'application/octet-stream', filename: meta.filename || 'attachment' };+ },+ };+}diff --git a/api/_lib/mail/service.js b/api/_lib/mail/service.jsnew file mode 100644index 000000000..5f1790ce7--- /dev/null+++ b/api/_lib/mail/service.js@@ -0,0 +1,750 @@+// Agent mail service: provisioning, quotes, metered sends, and the inbox.+//+// Both callers, the v1 REST routes (api/_lib/mail/routes.js) and the MCP tools+// (api/_mcpagent/mail-tools.js), go through this module, so the rules are+// identical however an agent reaches its mailbox:+//+// • Ownership. Every call names an agent the caller owns; anything else is a+// 404 that does not reveal whether the agent exists.+// • Quote first. Provisioning and every send are financial. A quote binds the+// price, the payment source and, for a send, a hash of the exact content.+// The execute call must cite an unexpired, unconsumed quote and carry the+// explicit confirm flag; a send whose content differs from what was quoted+// is refused.+// • Charge once. The charge is idempotent on the quote id, on both rails:+// credits (debitCredits) or the agent's own USDC (transferUsdcGuarded, which+// runs the wallet's spend limits, freeze switch and audit trail). A send the+// provider rejects is refunded to credits.+// • Conduct. Outbound content passes checkOutboundContent, recipients are+// validated, and a warm-up throttle bounds a new mailbox's volume.++import { createHash } from 'node:crypto';+import { GetObjectCommand } from '@aws-sdk/client-s3';+import { getSignedUrl } from '@aws-sdk/s3-request-presigner';+import { sql } from '../db.js';+import { env } from '../env.js';+import { r2 } from '../r2.js';+import { debitCredits, getCreditAccount, refundCredits } from '../credits.js';+import { transferUsdcGuarded } from '../agent-usdc-transfer.js';+import { getSolanaAddressBalances } from '../agent-wallet.js';+import { currentSignatureFor } from '../real-funds-agreement.js';+import { fetchSafePublicUrlPinned } from '../ssrf-guard.js';+import { logAudit } from '../audit.js';+import {+ mailDomain,+ mailPricing,+ warmupLimits,+ QUOTE_TTL_MS,+ RESERVED_LOCAL_PARTS,+ MAX_RECIPIENTS,+ MAX_ATTACHMENTS,+ MAX_ATTACHMENT_BYTES,+ MAX_TOTAL_ATTACHMENT_BYTES,+ MAX_TEXT_CHARS,+ MAX_HTML_CHARS,+} from './config.js';+import { checkOutboundContent } from './content-rules.js';+import { isValidAddress, isValidLocalPart, localPartFrom, replyHeaders, replySubject } from './threading.js';+import { mailProvider, ProviderError } from './provider.js';++export class MailError extends Error {+ constructor(status, code, message, details = null) {+ super(message);+ this.status = status;+ this.code = code;+ this.details = details;+ }+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function usd(n) {+ return Math.round(Number(n) * 1e6) / 1e6;+}++function hashPayload(obj) {+ return createHash('sha256').update(JSON.stringify(obj)).digest('hex');+}++// ── ownership ────────────────────────────────────────────────────────────────++export async function loadOwnedAgent(agentId, userId) {+ if (!UUID_RE.test(String(agentId || ''))) throw new MailError(404, 'agent_not_found', 'No agent with that id is on your account.');+ const [row] = await sql`+ select id, user_id, name, meta+ from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!row || row.user_id !== userId) throw new MailError(404, 'agent_not_found', 'No agent with that id is on your account.');+ return row;+}++export async function activeMailbox(agentId) {+ const [row] = await sql`+ select * from agent_mailboxes where agent_id = ${agentId} and status = 'active' limit 1+ `;+ return row || null;+}++async function outboundCounts(mailboxId) {+ const [row] = await sql`+ select+ count(*) filter (where created_at > now() - interval '1 hour')::int as last_hour,+ count(*) filter (where created_at > now() - interval '1 day')::int as last_day+ from agent_mail_sends+ where mailbox_id = ${mailboxId} and kind = 'send'+ and status not in ('charge_failed', 'refunded')+ `;+ return { lastHour: row?.last_hour ?? 0, lastDay: row?.last_day ?? 0 };+}++export async function mailboxView(mb) {+ if (!mb) return null;+ const limits = warmupLimits(mb.created_at);+ const [counts, [unread]] = await Promise.all([+ outboundCounts(mb.id),+ sql`+ select count(*)::int as n from agent_mail_messages+ where mailbox_id = ${mb.id} and direction = 'in' and read_at is null and deleted_at is null+ and coalesce(spam_score, 0) < 6+ `,+ ]);+ return {+ id: mb.id,+ address: mb.address,+ display_name: mb.display_name,+ status: mb.status,+ created_at: mb.created_at,+ unread: unread?.n ?? 0,+ limits: {+ per_hour: limits.perHour,+ per_day: limits.perDay,+ warming_up: limits.warming,+ sent_last_hour: counts.lastHour,+ sent_last_day: counts.lastDay,+ },+ };+}++// ── payment source ───────────────────────────────────────────────────────────++async function fundingView(userId, agent) {+ const credits = await getCreditAccount(userId).catch(() => ({ balanceUsd: 0 }));+ const address = agent.meta?.solana_address || null;+ let walletUsdc = null;+ if (address) {+ const b = await getSolanaAddressBalances(address, 'mainnet').catch(() => null);+ walletUsdc = b?.usdc != null ? Number(b.usdc) : null;+ }+ return {+ credits_usd: usd(credits.balanceUsd),+ wallet_address: address,+ wallet_usdc: walletUsdc,+ wallet_payable: Boolean(address && agent.meta?.encrypted_solana_secret && env.X402_PAY_TO_SOLANA),+ };+}++function choosePaymentSource(requested, price, funding) {+ const creditsOk = funding.credits_usd >= price;+ const walletOk = funding.wallet_payable && (funding.wallet_usdc ?? 0) >= price;+ if (requested === 'credits') {+ if (!creditsOk) throw new MailError(402, 'insufficient_credits', `This costs $${price} and your credit balance is $${funding.credits_usd}. Top up at /credits or pay from the agent wallet.`, { funding, price_usd: price });+ return 'credits';+ }+ if (requested === 'wallet') {+ if (!funding.wallet_payable) throw new MailError(409, 'wallet_unavailable', 'This agent has no custodial Solana wallet that can pay. Provision one, or pay with credits.', { funding });+ if (!walletOk) throw new MailError(402, 'insufficient_wallet_usdc', `This costs $${price} USDC and the agent wallet holds ${funding.wallet_usdc ?? 0} USDC.`, { funding, price_usd: price });+ return 'wallet';+ }+ if (creditsOk) return 'credits';+ if (walletOk) return 'wallet';+ throw new MailError(402, 'insufficient_funds', `This costs $${price}. Add credits at /credits or fund the agent wallet with USDC.`, { funding, price_usd: price });+}++// ── quotes ───────────────────────────────────────────────────────────────────++async function insertQuote({ userId, agentId, kind, price, source, payload }) {+ const expiresAt = new Date(Date.now() + QUOTE_TTL_MS);+ const [row] = await sql`+ insert into agent_mail_quotes (user_id, agent_id, kind, price_usd, payment_source, payload_hash, payload, expires_at)+ values (${userId}, ${agentId}, ${kind}, ${String(price)}, ${source}, ${hashPayload(payload)},+ ${JSON.stringify(payload)}::jsonb, ${expiresAt.toISOString()})+ returning id, expires_at+ `;+ return row;+}++/**+ * Atomically consume a quote. Refuses a missing, foreign, stale, used or+ * mismatched quote with an error that names the preview tool to call again.+ */+async function consumeQuote({ quoteId, userId, agentId, kind, payload }) {+ const redo = kind === 'create' ? 'agent_mail_quote with action "create"' : 'agent_mail_quote with action "send"';+ if (!UUID_RE.test(String(quoteId || ''))) {+ throw new MailError(400, 'quote_required', `Call ${redo} first and pass its quote_id.`);+ }+ const [q] = await sql`select * from agent_mail_quotes where id = ${quoteId} limit 1`;+ if (!q || q.user_id !== userId || q.agent_id !== agentId || q.kind !== kind) {+ throw new MailError(400, 'quote_invalid', `That quote does not belong to this ${kind}. Call ${redo} again.`);+ }+ if (q.consumed_at) throw new MailError(409, 'quote_used', `That quote was already used. Call ${redo} for a new one.`);+ if (new Date(q.expires_at).getTime() < Date.now()) {+ throw new MailError(410, 'quote_expired', `That quote expired (quotes last 10 minutes). Call ${redo} again.`);+ }+ if (payload && q.payload_hash !== hashPayload(payload)) {+ throw new MailError(409, 'quote_mismatch', `The ${kind === 'send' ? 'message' : 'request'} differs from what was quoted. Call ${redo} with the final content.`);+ }+ const [claimed] = await sql`+ update agent_mail_quotes set consumed_at = now()+ where id = ${quoteId} and consumed_at is null+ returning id+ `;+ if (!claimed) throw new MailError(409, 'quote_used', `That quote was already used. Call ${redo} for a new one.`);+ return { ...q, price_usd: Number(q.price_usd) };+}++async function requireAgreementForWallet(userId) {+ const sig = await currentSignatureFor(userId).catch(() => {+ throw new MailError(503, 'agreement_check_unavailable', 'Could not verify your signed real-funds agreements, so nothing was charged. Try again in a moment.');+ });+ if (!sig) {+ throw new MailError(403, 'risk_ack_required', 'Sign the real-funds agreements at /legal/sign before paying from the agent wallet, or pay with credits.');+ }+}++// ── charging ─────────────────────────────────────────────────────────────────++async function charge({ quote, agent, userId, kind }) {+ const idempotencyKey = `agent-mail:${quote.id}`;+ if (quote.payment_source === 'credits') {+ const debit = await debitCredits({+ userId,+ amountUsd: quote.price_usd,+ action: `agent_mail.${kind}`,+ refType: 'agent_mail_quote',+ refId: quote.id,+ idempotencyKey,+ meta: { agent_id: agent.id },+ });+ return { creditLedgerId: debit.ledgerId, signature: null };+ }+ await requireAgreementForWallet(userId);+ const paid = await transferUsdcGuarded({+ fromAgentId: agent.id,+ fromUserId: userId,+ fromMeta: agent.meta || {},+ toAddress: env.X402_PAY_TO_SOLANA,+ usdc: quote.price_usd,+ network: 'mainnet',+ category: 'x402',+ idempotencyKey,+ rowMeta: { purpose: 'agent_mail', kind, quote_id: quote.id },+ });+ if (paid.status === 'paid' || paid.status === 'replayed') return { creditLedgerId: null, signature: paid.signature };+ if (paid.status === 'blocked') {+ throw new MailError(403, paid.code || 'spend_blocked', paid.message || 'The agent wallet spend policy blocked this payment.');+ }+ throw new MailError(402, paid.code || 'wallet_payment_failed', `The USDC payment from the agent wallet did not settle (${paid.code || 'failed'}). Nothing was sent.`);+}++// A failed delivery is made whole in credits on either rail: credits come back+// as credits, and a settled USDC payment is refunded as the same USD in credits.+async function refund({ quote, userId, kind, reason }) {+ await refundCredits({+ userId,+ amountUsd: quote.price_usd,+ action: `agent_mail.${kind}.refund`,+ refType: 'agent_mail_quote',+ refId: quote.id,+ idempotencyKey: `agent-mail-refund:${quote.id}`,+ meta: { reason, paid_with: quote.payment_source },+ });+}++async function recordSend(fields) {+ const [row] = await sql`+ insert into agent_mail_sends+ (mailbox_id, agent_id, user_id, kind, quote_id, cost_usd, payment_source, status)+ values (${fields.mailboxId}, ${fields.agentId}, ${fields.userId}, ${fields.kind}, ${fields.quoteId},+ ${String(fields.cost)}, ${fields.source}, 'charging')+ returning id+ `;+ return row.id;+}++async function updateSend(id, patch) {+ await sql`+ update agent_mail_sends set+ status = coalesce(${patch.status ?? null}, status),+ mailbox_id = coalesce(${patch.mailboxId ?? null}::uuid, mailbox_id),+ credit_ledger_id = coalesce(${patch.creditLedgerId ?? null}::uuid, credit_ledger_id),+ signature = coalesce(${patch.signature ?? null}, signature),+ provider = coalesce(${patch.provider ?? null}, provider),+ provider_id = coalesce(${patch.providerId ?? null}, provider_id),+ message_row_id = coalesce(${patch.messageRowId ?? null}::uuid, message_row_id),+ error_code = ${patch.errorCode ?? null},+ error_message = ${patch.errorMessage ?? null},+ updated_at = now()+ where id = ${id}+ `;+}++// ── provisioning ─────────────────────────────────────────────────────────────++async function pickLocalPart(agent, requested) {+ if (requested != null && requested !== '') {+ const lp = String(requested).trim().toLowerCase();+ if (!isValidLocalPart(lp)) {+ throw new MailError(400, 'invalid_local_part', 'Use 3 to 32 lowercase letters, digits, dots or hyphens, starting and ending with a letter or digit.');+ }+ if (RESERVED_LOCAL_PARTS.has(lp)) throw new MailError(409, 'local_part_reserved', `"${lp}" is a reserved role address. Pick another.`);+ const [taken] = await sql`select 1 from agent_mailboxes where local_part = ${lp} and domain = ${mailDomain()} limit 1`;+ if (taken) throw new MailError(409, 'address_taken', `${lp}@${mailDomain()} is taken. Pick another.`);+ return lp;+ }+ const base = localPartFrom(agent.name) || `agent-${String(agent.id).slice(0, 8)}`;+ const stem = RESERVED_LOCAL_PARTS.has(base) ? `${base}-agent` : base;+ for (let i = 0; i < 20; i++) {+ const candidate = i === 0 ? stem : `${stem.slice(0, 28)}-${i + 1}`;+ const [taken] = await sql`select 1 from agent_mailboxes where local_part = ${candidate} and domain = ${mailDomain()} limit 1`;+ if (!taken) return candidate;+ }+ return `${stem.slice(0, 22)}-${String(agent.id).slice(0, 8)}`;+}++function cleanDisplayName(name, agent) {+ const s = String(name ?? agent.name ?? '').replace(/[<>"\r\n]/g, '').trim().slice(0, 64);+ return s || null;+}++export async function quoteCreate({ userId, agentId, localPart, displayName, paymentSource }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const existing = await activeMailbox(agent.id);+ if (existing) {+ throw new MailError(409, 'mailbox_exists', `This agent already has ${existing.address}.`, { address: existing.address });+ }+ const lp = await pickLocalPart(agent, localPart);+ const pricing = await mailPricing();+ const price = pricing.create_usd;+ const funding = await fundingView(userId, agent);+ const source = choosePaymentSource(paymentSource, price, funding);+ const payload = { local_part: lp, display_name: cleanDisplayName(displayName, agent) };+ const q = await insertQuote({ userId, agentId: agent.id, kind: 'create', price, source, payload });+ return {+ quote_id: q.id,+ action: 'create',+ price_usd: price,+ payment_source: source,+ expires_at: q.expires_at,+ address: `${lp}@${mailDomain()}`,+ display_name: payload.display_name,+ funding,+ confirm_with: { tool: 'agent_mail_create', flag: 'confirm_spend', quote_id: q.id },+ };+}++export async function createMailbox({ userId, agentId, quoteId, confirm }) {+ if (confirm !== true) {+ throw new MailError(400, 'confirm_required', 'Provisioning charges the account. Show the quote to the user, then call again with confirm_spend: true.');+ }+ const agent = await loadOwnedAgent(agentId, userId);+ const quote = await consumeQuote({ quoteId, userId, agentId: agent.id, kind: 'create' });+ const { local_part: lp, display_name: displayName } = quote.payload || {};+ const domain = mailDomain();+ const sendId = await recordSend({ mailboxId: null, agentId: agent.id, userId, kind: 'create', quoteId: quote.id, cost: quote.price_usd, source: quote.payment_source });++ let paid;+ try {+ paid = await charge({ quote, agent, userId, kind: 'create' });+ } catch (err) {+ await updateSend(sendId, { status: 'charge_failed', errorCode: err.code || 'charge_failed', errorMessage: err.message });+ throw err;+ }++ let mb;+ try {+ [mb] = await sql`+ insert into agent_mailboxes (agent_id, user_id, address, local_part, domain, display_name)+ values (${agent.id}, ${userId}, ${`${lp}@${domain}`}, ${lp}, ${domain}, ${displayName})+ returning *+ `;+ } catch (err) {+ await refund({ quote, userId, kind: 'create', reason: 'address_conflict' });+ await updateSend(sendId, { status: 'refunded', errorCode: 'address_conflict', errorMessage: err.message, ...paid });+ throw new MailError(409, 'address_taken', `${lp}@${domain} was claimed a moment ago. You were refunded in credits; quote again.`);+ }+ await updateSend(sendId, { status: 'provisioned', mailboxId: mb.id, creditLedgerId: paid.creditLedgerId, signature: paid.signature });+ logAudit({ userId, action: 'agent_mail.create', resourceId: agent.id, meta: { address: mb.address, paid_with: quote.payment_source, cost_usd: quote.price_usd } });+ return { mailbox: await mailboxView(mb), charge: { cost_usd: quote.price_usd, payment_source: quote.payment_source, signature: paid.signature, credit_ledger_id: paid.creditLedgerId } };+}++// ── drafting and sending ─────────────────────────────────────────────────────++function asList(v) {+ if (v == null || v === '') return [];+ return (Array.isArray(v) ? v : String(v).split(',')).map((s) => String(s).trim().toLowerCase()).filter(Boolean);+}++/**+ * Validate and canonicalize a draft. The canonical form is what gets hashed+ * into the quote, so the confirmed send is byte-for-byte what was previewed.+ */+async function canonicalDraft(mb, draft) {+ const to = [...new Set(asList(draft.to))];+ const cc = [...new Set(asList(draft.cc))].filter((a) => !to.includes(a));+ if (!to.length) throw new MailError(400, 'recipient_required', 'Name at least one recipient in "to".');+ if (to.length + cc.length > MAX_RECIPIENTS) throw new MailError(400, 'too_many_recipients', `At most ${MAX_RECIPIENTS} recipients per message.`);+ const bad = [...to, ...cc].filter((a) => !isValidAddress(a));+ if (bad.length) throw new MailError(400, 'invalid_recipient', `Not a valid email address: ${bad.join(', ')}.`, { invalid: bad });+ if ([...to, ...cc].includes(mb.address)) throw new MailError(400, 'self_send', 'An agent cannot email its own address.');++ let parent = null;+ if (draft.in_reply_to) {+ if (!UUID_RE.test(String(draft.in_reply_to))) throw new MailError(400, 'invalid_reply', 'in_reply_to must be the id of a message in this mailbox.');+ [parent] = await sql`+ select id, thread_id, message_id, references_ids, subject from agent_mail_messages+ where id = ${draft.in_reply_to} and mailbox_id = ${mb.id} and deleted_at is null limit 1+ `;+ if (!parent) throw new MailError(404, 'reply_target_not_found', 'The message you are replying to is not in this mailbox.');+ }++ const subject = String(draft.subject ?? (parent ? replySubject(parent.subject) : '')).trim();+ const text = String(draft.text ?? '').trim();+ const html = draft.html ? String(draft.html) : null;+ if (text.length > MAX_TEXT_CHARS) throw new MailError(400, 'text_too_long', `The text body is over ${MAX_TEXT_CHARS} characters.`);+ if (html && html.length > MAX_HTML_CHARS) throw new MailError(400, 'html_too_long', `The HTML body is over ${MAX_HTML_CHARS} characters.`);+ if (!text) throw new MailError(400, 'text_required', 'Every message needs a plain-text body (html is optional and additional).');++ const verdict = checkOutboundContent({ subject, text, html, isReply: Boolean(parent) });+ if (!verdict.ok) {+ throw new MailError(422, 'content_rejected', verdict.violations.map((v) => v.message).join(' '), { violations: verdict.violations });+ }++ const attachments = Array.isArray(draft.attachments) ? draft.attachments : [];+ if (attachments.length > MAX_ATTACHMENTS) throw new MailError(400, 'too_many_attachments', `At most ${MAX_ATTACHMENTS} attachments per message.`);+ const atts = attachments.map((a, i) => {+ const url = String(a?.url || '').trim();+ let parsed;+ try { parsed = new URL(url); } catch { throw new MailError(400, 'invalid_attachment', `Attachment ${i + 1} needs a public https url.`); }+ if (parsed.protocol !== 'https:') throw new MailError(400, 'invalid_attachment', `Attachment ${i + 1} must be served over https.`);+ const filename = String(a?.filename || decodeURIComponent(parsed.pathname.split('/').pop() || '') || `attachment-${i + 1}`)+ .replace(/[\\/\r\n"]/g, '_')+ .slice(0, 120);+ return { url, filename };+ });++ return {+ canonical: { to, cc, subject, text, html, attachments: atts, in_reply_to: parent?.id || null },+ parent,+ };+}++async function assertThrottle(mb) {+ const limits = warmupLimits(mb.created_at);+ const counts = await outboundCounts(mb.id);+ if (counts.lastHour >= limits.perHour) {+ throw new MailError(429, 'mailbox_hourly_limit', `This mailbox sent ${counts.lastHour} messages in the last hour, its limit${limits.warming ? ' while warming up' : ''}. Try again later.`, { limits, counts });+ }+ if (counts.lastDay >= limits.perDay) {+ throw new MailError(429, 'mailbox_daily_limit', `This mailbox reached its ${limits.perDay} messages per day limit${limits.warming ? ' while warming up' : ''}.`, { limits, counts });+ }+ return { limits, counts };+}++async function requireMailbox(agent) {+ const mb = await activeMailbox(agent.id);+ if (!mb) throw new MailError(404, 'no_mailbox', 'This agent has no mailbox yet. Quote one with agent_mail_quote (action "create").');+ return mb;+}++export async function quoteSend({ userId, agentId, draft, paymentSource }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const { canonical } = await canonicalDraft(mb, draft || {});+ const throttle = await assertThrottle(mb);+ const pricing = await mailPricing();+ const price = pricing.send_usd;+ const funding = await fundingView(userId, agent);+ const source = choosePaymentSource(paymentSource, price, funding);+ const q = await insertQuote({ userId, agentId: agent.id, kind: 'send', price, source, payload: canonical });+ return {+ quote_id: q.id,+ action: 'send',+ price_usd: price,+ payment_source: source,+ expires_at: q.expires_at,+ preview: {+ from: fromHeader(mb),+ to: canonical.to,+ cc: canonical.cc,+ subject: canonical.subject,+ text: canonical.text,+ has_html: Boolean(canonical.html),+ attachments: canonical.attachments,+ in_reply_to: canonical.in_reply_to,+ },+ limits: { per_hour: throttle.limits.perHour, per_day: throttle.limits.perDay, sent_last_hour: throttle.counts.lastHour, sent_last_day: throttle.counts.lastDay },+ funding,+ confirm_with: { tool: 'agent_mail_send', flag: 'confirm_send', quote_id: q.id },+ };+}++function fromHeader(mb) {+ return mb.display_name ? `"${mb.display_name}" <${mb.address}>` : mb.address;+}++async function fetchAttachments(list) {+ const out = [];+ let total = 0;+ for (const [i, a] of list.entries()) {+ let res;+ try {+ res = await fetchSafePublicUrlPinned(a.url, { signal: AbortSignal.timeout(20_000) }, { maxBytes: MAX_ATTACHMENT_BYTES });+ } catch (err) {+ throw new MailError(422, 'attachment_fetch_failed', `Attachment ${i + 1} (${a.filename}) could not be fetched: ${err?.message || 'blocked'}.`);+ }+ if (!res.ok) throw new MailError(422, 'attachment_fetch_failed', `Attachment ${i + 1} (${a.filename}) answered HTTP ${res.status}.`);+ const buf = Buffer.from(await res.arrayBuffer());+ total += buf.length;+ if (total > MAX_TOTAL_ATTACHMENT_BYTES) throw new MailError(413, 'attachments_too_large', `Attachments total over ${MAX_TOTAL_ATTACHMENT_BYTES / 1024 / 1024} MB.`);+ out.push({ filename: a.filename, content: buf, contentType: res.headers.get('content-type') || 'application/octet-stream', size: buf.length });+ }+ return out;+}++export async function sendMail({ userId, agentId, quoteId, draft, confirm }) {+ if (confirm !== true) {+ throw new MailError(400, 'confirm_required', 'Sending is outward-facing and metered. Show the quote preview to the user, then call again with confirm_send: true.');+ }+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const { canonical, parent } = await canonicalDraft(mb, draft || {});+ await assertThrottle(mb);+ const quote = await consumeQuote({ quoteId, userId, agentId: agent.id, kind: 'send', payload: canonical });++ // Fetch attachments before charging, so an unreachable file costs nothing.+ const files = await fetchAttachments(canonical.attachments);++ const sendId = await recordSend({ mailboxId: mb.id, agentId: agent.id, userId, kind: 'send', quoteId: quote.id, cost: quote.price_usd, source: quote.payment_source });+ let paid;+ try {+ paid = await charge({ quote, agent, userId, kind: 'send' });+ } catch (err) {+ await updateSend(sendId, { status: 'charge_failed', errorCode: err.code || 'charge_failed', errorMessage: err.message });+ throw err;+ }+ await updateSend(sendId, { status: 'sending', creditLedgerId: paid.creditLedgerId, signature: paid.signature });++ const provider = mailProvider();+ const domain = mailDomain();+ const messageId = `${quote.id}@${domain}`;+ const headers = { 'Message-ID': `<${messageId}>`, ...(parent ? replyHeaders(parent) : {}) };+ let sent;+ try {+ sent = await provider.send({+ from: fromHeader(mb),+ to: canonical.to,+ cc: canonical.cc,+ subject: canonical.subject,+ text: canonical.text,+ html: canonical.html,+ headers,+ attachments: files,+ idempotencyKey: `agent-mail-send:${quote.id}`,+ });+ } catch (err) {+ const code = err instanceof ProviderError ? err.code : 'provider_error';+ await refund({ quote, userId, kind: 'send', reason: code });+ await updateSend(sendId, { status: 'refunded', provider: provider.name, errorCode: code, errorMessage: err.message });+ throw new MailError(502, 'send_failed', `The mail provider did not accept the message (${err.message}). You were refunded $${quote.price_usd} in credits; fix the issue and retry.`, { provider_code: code, retryable: Boolean(err.retryable) });+ }++ const references = parent ? [...(parent.references_ids || []), parent.message_id].filter(Boolean).slice(-20) : [];+ const [msg] = await sql`+ insert into agent_mail_messages+ (mailbox_id, direction, thread_id, from_address, from_name, to_addresses, cc_addresses, subject,+ text_body, html_body, attachments, message_id, in_reply_to, references_ids, provider,+ provider_message_id, read_at, delivery_status)+ values+ (${mb.id}, 'out', ${parent?.thread_id || quote.id}, ${mb.address}, ${mb.display_name}, ${canonical.to}, ${canonical.cc},+ ${canonical.subject}, ${canonical.text}, ${canonical.html},+ ${JSON.stringify(files.map((f) => ({ filename: f.filename, size: f.size, content_type: f.contentType })))}::jsonb,+ ${messageId}, ${parent?.message_id || null}, ${references}, ${provider.name}, ${sent.id}, now(), 'sent')+ returning id, thread_id, created_at+ `;+ await updateSend(sendId, { status: 'sent', provider: provider.name, providerId: sent.id, messageRowId: msg.id });+ logAudit({ userId, action: 'agent_mail.send', resourceId: agent.id, meta: { to: canonical.to, cc: canonical.cc, message_id: msg.id, paid_with: quote.payment_source, cost_usd: quote.price_usd } });+ return {+ message: { id: msg.id, thread_id: msg.thread_id, created_at: msg.created_at, status: 'sent', provider_id: sent.id },+ charge: { cost_usd: quote.price_usd, payment_source: quote.payment_source, signature: paid.signature, credit_ledger_id: paid.creditLedgerId },+ };+}++// ── inbox reads ──────────────────────────────────────────────────────────────++function summaryRow(r) {+ return {+ id: r.id,+ direction: r.direction,+ thread_id: r.thread_id,+ from: r.from_address,+ from_name: r.from_name,+ to: r.to_addresses,+ cc: r.cc_addresses,+ subject: r.subject,+ snippet: String(r.text_body || '').replace(/\s+/g, ' ').trim().slice(0, 180),+ attachment_count: Array.isArray(r.attachments) ? r.attachments.length : 0,+ read: Boolean(r.read_at),+ spam: r.spam_score != null && Number(r.spam_score) >= 6,+ spam_score: r.spam_score != null ? Number(r.spam_score) : null,+ delivery_status: r.delivery_status,+ created_at: r.created_at,+ };+}++export async function getMailboxForAgent({ userId, agentId }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await activeMailbox(agent.id);+ const pricing = await mailPricing();+ return { agent: { id: agent.id, name: agent.name }, mailbox: await mailboxView(mb), pricing, domain: mailDomain() };+}++/**+ * List messages newest first. Cursor is the id of the last row of the previous+ * page. folder: inbox (received, not spam) | sent | spam | all.+ */+export async function listMessages({ userId, agentId, folder = 'inbox', unread = false, q = '', limit = 25, cursor = null }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const cap = Math.min(Math.max(Number(limit) || 25, 1), 100);+ const f = ['inbox', 'sent', 'spam', 'all'].includes(folder) ? folder : 'inbox';+ const search = String(q || '').trim().slice(0, 120);+ const pattern = search ? `%${search.replace(/[\\%_]/g, (c) => `\\${c}`)}%` : null;++ let beforeTs = null;+ let beforeId = null;+ if (cursor && UUID_RE.test(String(cursor))) {+ const [anchor] = await sql`select created_at from agent_mail_messages where id = ${cursor} and mailbox_id = ${mb.id}`;+ if (anchor) {+ beforeTs = anchor.created_at;+ beforeId = cursor;+ }+ }+ const rows = await sql`+ select id, direction, thread_id, from_address, from_name, to_addresses, cc_addresses, subject,+ left(text_body, 400) as text_body, attachments, read_at, spam_score, delivery_status, created_at+ from agent_mail_messages+ where mailbox_id = ${mb.id} and deleted_at is null+ and (${f} = 'all'+ or (${f} = 'inbox' and direction = 'in' and coalesce(spam_score, 0) < 6)+ or (${f} = 'spam' and direction = 'in' and coalesce(spam_score, 0) >= 6)+ or (${f} = 'sent' and direction = 'out'))+ and (${unread === true} = false or (direction = 'in' and read_at is null))+ and (${pattern}::text is null+ or subject ilike ${pattern} or from_address ilike ${pattern} or text_body ilike ${pattern}+ or array_to_string(to_addresses, ' ') ilike ${pattern})+ and (${beforeTs}::timestamptz is null+ or created_at < ${beforeTs}::timestamptz+ or (created_at = ${beforeTs}::timestamptz and id < ${beforeId}::uuid))+ order by created_at desc, id desc+ limit ${cap + 1}+ `;+ const hasMore = rows.length > cap;+ const items = (hasMore ? rows.slice(0, cap) : rows).map(summaryRow);+ return { items, hasMore, nextCursor: hasMore ? items[items.length - 1].id : null, mailbox: { address: mb.address } };+}++async function loadMessage(mb, messageId) {+ if (!UUID_RE.test(String(messageId || ''))) throw new MailError(404, 'message_not_found', 'No message with that id in this mailbox.');+ const [row] = await sql`+ select * from agent_mail_messages where id = ${messageId} and mailbox_id = ${mb.id} and deleted_at is null limit 1+ `;+ if (!row) throw new MailError(404, 'message_not_found', 'No message with that id in this mailbox.');+ return row;+}++export async function readMessage({ userId, agentId, messageId, markRead = true }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const row = await loadMessage(mb, messageId);+ if (markRead && row.direction === 'in' && !row.read_at) {+ await sql`update agent_mail_messages set read_at = now() where id = ${row.id} and read_at is null`;+ row.read_at = new Date().toISOString();+ }+ const thread = await sql`+ select id, direction, from_address, subject, created_at+ from agent_mail_messages+ where mailbox_id = ${mb.id} and thread_id = ${row.thread_id} and deleted_at is null+ order by created_at asc limit 50+ `;+ let send = null;+ if (row.direction === 'out') {+ [send] = await sql`+ select status, cost_usd, payment_source, signature, error_code, error_message+ from agent_mail_sends where message_row_id = ${row.id} limit 1+ `;+ }+ return {+ ...summaryRow(row),+ reply_to: row.reply_to,+ text: row.text_body,+ html: row.html_body,+ message_id: row.message_id,+ in_reply_to: row.in_reply_to,+ attachments: (row.attachments || []).map((a, i) => ({+ index: i,+ filename: a.filename,+ size: a.size,+ content_type: a.content_type,+ stored: Boolean(a.key),+ quarantined: Boolean(a.quarantined),+ })),+ spam_verdict: row.spam_verdict,+ virus_verdict: row.virus_verdict,+ auth_results: row.auth_results,+ send: send ? { ...send, cost_usd: Number(send.cost_usd) } : null,+ thread: thread.map((t) => ({ id: t.id, direction: t.direction, from: t.from_address, subject: t.subject, created_at: t.created_at })),+ untrusted: row.direction === 'in',+ };+}++export async function setRead({ userId, agentId, messageId, read }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const row = await loadMessage(mb, messageId);+ await sql`update agent_mail_messages set read_at = ${read ? new Date().toISOString() : null} where id = ${row.id}`;+ return { id: row.id, read: Boolean(read) };+}++export async function deleteMessage({ userId, agentId, messageId }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const row = await loadMessage(mb, messageId);+ await sql`update agent_mail_messages set deleted_at = now() where id = ${row.id}`;+ return { id: row.id, deleted: true };+}++/**+ * A short-lived download URL for one stored attachment, always served with+ * Content-Disposition: attachment and a neutral content type, so a hostile+ * file is saved, never rendered in the browser.+ */+export async function attachmentDownloadUrl({ userId, agentId, messageId, index }) {+ const agent = await loadOwnedAgent(agentId, userId);+ const mb = await requireMailbox(agent);+ const row = await loadMessage(mb, messageId);+ const att = (row.attachments || [])[Number(index)];+ if (!att) throw new MailError(404, 'attachment_not_found', 'No attachment at that index.');+ if (att.quarantined) throw new MailError(451, 'attachment_quarantined', 'This attachment was flagged by the malware scan and was not stored.');+ if (!att.key) throw new MailError(404, 'attachment_not_stored', att.skipped_reason || 'This attachment was not stored.');+ const safeName = String(att.filename || 'attachment').replace(/[^\w.\- ]+/g, '_').slice(0, 120);+ const cmd = new GetObjectCommand({+ Bucket: env.S3_BUCKET,+ Key: att.key,+ ResponseContentDisposition: `attachment; filename="${safeName}"`,+ ResponseContentType: 'application/octet-stream',+ });+ const url = await getSignedUrl(r2, cmd, { expiresIn: 300 });+ return { url, filename: att.filename, size: att.size, expires_in: 300 };+}diff --git a/api/_lib/mail/spam.js b/api/_lib/mail/spam.jsnew file mode 100644index 000000000..c1e6e5236--- /dev/null+++ b/api/_lib/mail/spam.js@@ -0,0 +1,69 @@+// Inbound spam and malware verdicts for agent mail.+//+// The provider receives on Amazon SES infrastructure, which stamps every+// message with verdict headers before we see it:+// X-SES-Spam-Verdict PASS | FAIL | GRAY | PROCESSING_FAILED+// X-SES-Virus-Verdict PASS | FAIL | GRAY | PROCESSING_FAILED+// Authentication-Results spf=, dkim=, dmarc= results for the sender+// scoreInbound() folds those into one 0 to 10 score we store and show. Nothing+// here trusts the sender: a missing header counts as "unknown", never as a pass.++function header(headers, name) {+ if (!headers) return null;+ const want = name.toLowerCase();+ for (const [k, v] of Object.entries(headers)) {+ if (String(k).toLowerCase() === want) return Array.isArray(v) ? v.join(', ') : String(v);+ }+ return null;+}++function verdict(v) {+ const s = String(v || '').trim().toUpperCase();+ if (!s) return 'UNKNOWN';+ if (['PASS', 'FAIL', 'GRAY', 'PROCESSING_FAILED'].includes(s)) return s;+ return 'UNKNOWN';+}++/** Parse spf/dkim/dmarc results out of an Authentication-Results header. */+export function parseAuthResults(value) {+ const out = { spf: 'none', dkim: 'none', dmarc: 'none' };+ const s = String(value || '');+ for (const key of Object.keys(out)) {+ const m = s.match(new RegExp(`\\b${key}\\s*=\\s*([a-z]+)`, 'i'));+ if (m) out[key] = m[1].toLowerCase();+ }+ return out;+}++/**+ * @param {Record<string,string>|null} headers the message headers as delivered+ * @returns {{ score: number, spamVerdict: string, virusVerdict: string,+ * auth: { spf: string, dkim: string, dmarc: string }, isSpam: boolean, quarantineAttachments: boolean }}+ */+export function scoreInbound(headers) {+ const spamVerdict = verdict(header(headers, 'x-ses-spam-verdict'));+ const virusVerdict = verdict(header(headers, 'x-ses-virus-verdict'));+ const auth = parseAuthResults(header(headers, 'authentication-results'));++ let score = 0;+ if (spamVerdict === 'FAIL') score += 6;+ else if (spamVerdict === 'GRAY') score += 3;+ else if (spamVerdict !== 'PASS') score += 1;+ if (auth.dmarc === 'fail') score += 3;+ if (auth.spf === 'fail' || auth.spf === 'softfail') score += 1;+ if (auth.dkim === 'fail') score += 1;+ if (virusVerdict === 'FAIL') score += 4;+ score = Math.min(10, score);++ return {+ score,+ spamVerdict,+ virusVerdict,+ auth,+ isSpam: score >= 6,+ // A positive malware verdict keeps the files out of storage entirely.+ // Anything else is stored and only ever served as a download+ // (Content-Disposition: attachment), never rendered inline.+ quarantineAttachments: virusVerdict === 'FAIL',+ };+}diff --git a/api/_lib/mail/threading.js b/api/_lib/mail/threading.jsnew file mode 100644index 000000000..f612dd44a--- /dev/null+++ b/api/_lib/mail/threading.js@@ -0,0 +1,112 @@+// Email threading and address helpers for agent mail. Pure: no I/O, so every+// rule here is covered directly by tests/agent-mail.test.js.+//+// A thread is found the way mail clients do it (RFC 5322 section 3.6.4): the+// In-Reply-To and References headers name earlier Message-IDs, and a message+// joins the thread that owns any of them. When a sender's client drops those+// headers, a normalized subject with the same counterparty inside a recent+// window is the fallback.++/** Strip angle brackets and whitespace from a Message-ID. */+export function normalizeMessageId(id) {+ const s = String(id || '').trim();+ if (!s) return null;+ const m = s.match(/<([^>]+)>/);+ return (m ? m[1] : s).trim().toLowerCase() || null;+}++/** Split a References header (or an array of ids) into normalized ids. */+export function parseReferences(value) {+ if (!value) return [];+ const raw = Array.isArray(value) ? value.join(' ') : String(value);+ const bracketed = raw.match(/<[^>]+>/g);+ const parts = bracketed || raw.split(/[\s,]+/);+ const out = [];+ for (const p of parts) {+ const id = normalizeMessageId(p);+ if (id && !out.includes(id)) out.push(id);+ }+ return out;+}++/** Subject with every leading Re:/Fwd: (and bracketed list tags) removed, lowercased. */+export function normalizeSubject(subject) {+ let s = String(subject || '').trim();+ let prev;+ do {+ prev = s;+ s = s.replace(/^(\[[^\]]{1,40}\]\s*)?(re|fwd?|fw|aw|sv|vs)\s*(\[\d+\])?\s*:\s*/i, '').trim();+ } while (s !== prev);+ return s.replace(/\s+/g, ' ').toLowerCase();+}++/** The ids a new message points back at, nearest parent first. */+export function threadCandidates({ inReplyTo, references }) {+ const ids = [];+ const parent = normalizeMessageId(inReplyTo);+ if (parent) ids.push(parent);+ for (const r of parseReferences(references).reverse()) if (!ids.includes(r)) ids.push(r);+ return ids;+}++/**+ * Headers for a reply to `parent` (a stored message row). References carries+ * the parent's chain plus the parent itself, capped so a long thread never+ * grows the header without bound.+ */+export function replyHeaders(parent) {+ if (!parent?.message_id) return {};+ const parentId = normalizeMessageId(parent.message_id);+ const chain = [...(parent.references_ids || []).map(normalizeMessageId).filter(Boolean)];+ if (!chain.includes(parentId)) chain.push(parentId);+ const capped = chain.slice(-20);+ return {+ 'In-Reply-To': `<${parentId}>`,+ References: capped.map((id) => `<${id}>`).join(' '),+ };+}++/** "Re: <subject>" unless it already carries a reply prefix. */+export function replySubject(subject) {+ const s = String(subject || '').trim();+ return /^re\s*:/i.test(s) ? s : `Re: ${s || '(no subject)'}`;+}++/** Parse `"Name" <addr@host>` or a bare address into { name, address }. */+export function parseAddress(value) {+ const s = String(value || '').trim();+ const m = s.match(/^\s*(?:"?([^"<]*?)"?\s*)?<([^>]+)>\s*$/);+ const address = (m ? m[2] : s).trim().toLowerCase();+ const name = m && m[1] ? m[1].trim() : null;+ return { name: name || null, address };+}++const ADDRESS_RE = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;++/** True for a syntactically valid single mailbox address. */+export function isValidAddress(addr) {+ const s = String(addr || '').trim();+ return s.length <= 254 && ADDRESS_RE.test(s);+}++/**+ * A valid local part derived from an agent's name: lowercase letters, digits,+ * dots and hyphens, 3 to 32 characters, no leading, trailing or doubled dots.+ */+export function localPartFrom(name) {+ const s = String(name || '')+ .normalize('NFKD')+ .replace(/[̀-ͯ]/g, '')+ .toLowerCase()+ .replace(/[^a-z0-9.-]+/g, '-')+ .replace(/[-.]{2,}/g, '-')+ .replace(/^[-.]+|[-.]+$/g, '')+ .slice(0, 32)+ .replace(/[-.]+$/g, '');+ return s.length >= 3 ? s : null;+}++/** True when a caller-chosen local part meets the same rules. */+export function isValidLocalPart(s) {+ return typeof s === 'string' && /^[a-z0-9](?:[a-z0-9.-]{1,30}[a-z0-9])$/.test(s) && !/[-.]{2}/.test(s);+}diff --git a/api/_lib/migrations/20260922170000_agent_mail.sql b/api/_lib/migrations/20260922170000_agent_mail.sqlnew file mode 100644index 000000000..66b314365--- /dev/null+++ b/api/_lib/migrations/20260922170000_agent_mail.sql@@ -0,0 +1,125 @@+-- Agent mail: a real email inbox for every agent (api/_lib/mail/, docs/agent-mail.md).+--+-- An owner provisions one mailbox per agent, <local>@agents.three.ws. Inbound+-- mail arrives through the provider's signed webhook (api/mail/inbound.js);+-- outbound mail is metered per send and charged from the owner's credits or the+-- agent's own USDC wallet, always after a quote the caller confirmed.+--+-- agent_mailboxes one row per provisioned address. status 'active' is+-- the only state that receives or sends; 'disabled'+-- keeps the history and frees nothing (addresses are+-- never reissued to a different agent).+-- agent_mail_messages every message in and out. Bodies are stored as the+-- provider delivered them and are untrusted data+-- everywhere they are read. Attachments live in object+-- storage; `attachments` holds their keys and metadata.+-- thread_id groups a conversation (In-Reply-To and+-- References first, normalized subject as a fallback).+-- agent_mail_sends the billing and delivery record for each outbound+-- message and for the provisioning charge: what it+-- cost, how it was paid (a credit ledger id or an+-- on-chain signature), and the provider's delivery+-- status as its webhooks report it.+-- agent_mail_quotes the preview a financial action must cite. A quote+-- binds the price, the payment source and (for a send)+-- a hash of the exact content, expires after ten+-- minutes, and is consumed once.++create table if not exists agent_mailboxes (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ address text not null unique,+ local_part text not null,+ domain text not null,+ display_name text,+ status text not null default 'active' check (status in ('active', 'disabled')),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create unique index if not exists agent_mailboxes_one_active_per_agent+ on agent_mailboxes (agent_id) where status = 'active';+create index if not exists agent_mailboxes_user_idx on agent_mailboxes (user_id);++create table if not exists agent_mail_messages (+ id uuid primary key default gen_random_uuid(),+ mailbox_id uuid not null references agent_mailboxes(id) on delete cascade,+ direction text not null check (direction in ('in', 'out')),+ thread_id uuid not null,+ from_address text not null,+ from_name text,+ to_addresses text[] not null default '{}',+ cc_addresses text[] not null default '{}',+ reply_to text[] not null default '{}',+ subject text not null default '',+ text_body text,+ html_body text,+ attachments jsonb not null default '[]'::jsonb,+ message_id text,+ in_reply_to text,+ references_ids text[] not null default '{}',+ provider text not null,+ provider_message_id text,+ read_at timestamptz,+ spam_score real,+ spam_verdict text,+ virus_verdict text,+ auth_results jsonb not null default '{}'::jsonb,+ delivery_status text,+ deleted_at timestamptz,+ created_at timestamptz not null default now()+);++create unique index if not exists agent_mail_messages_provider_uniq+ on agent_mail_messages (mailbox_id, direction, provider_message_id)+ where provider_message_id is not null;+create index if not exists agent_mail_messages_mailbox_idx+ on agent_mail_messages (mailbox_id, created_at desc) where deleted_at is null;+create index if not exists agent_mail_messages_thread_idx on agent_mail_messages (mailbox_id, thread_id);+create index if not exists agent_mail_messages_message_id_idx+ on agent_mail_messages (mailbox_id, message_id) where message_id is not null;+create index if not exists agent_mail_messages_unread_idx+ on agent_mail_messages (mailbox_id) where direction = 'in' and read_at is null and deleted_at is null;++create table if not exists agent_mail_quotes (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ kind text not null check (kind in ('create', 'send')),+ price_usd numeric(20, 6) not null,+ payment_source text not null check (payment_source in ('credits', 'wallet')),+ payload_hash text not null,+ payload jsonb not null default '{}'::jsonb,+ expires_at timestamptz not null,+ consumed_at timestamptz,+ created_at timestamptz not null default now()+);++create index if not exists agent_mail_quotes_expires_idx on agent_mail_quotes (expires_at);++create table if not exists agent_mail_sends (+ id uuid primary key default gen_random_uuid(),+ mailbox_id uuid references agent_mailboxes(id) on delete set null,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ kind text not null check (kind in ('create', 'send')),+ quote_id uuid unique references agent_mail_quotes(id) on delete set null,+ message_row_id uuid references agent_mail_messages(id) on delete set null,+ cost_usd numeric(20, 6) not null,+ payment_source text not null check (payment_source in ('credits', 'wallet')),+ credit_ledger_id uuid,+ signature text,+ status text not null default 'charging'+ check (status in ('charging', 'charge_failed', 'sending', 'sent', 'delivered',+ 'delayed', 'bounced', 'complained', 'failed', 'provisioned', 'refunded')),+ provider text,+ provider_id text,+ error_code text,+ error_message text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists agent_mail_sends_provider_idx on agent_mail_sends (provider_id) where provider_id is not null;+create index if not exists agent_mail_sends_mailbox_idx on agent_mail_sends (mailbox_id, created_at desc);