Skip to main content

adk_drivers/email/
mod.rs

1//! Email drivers (spec 3.5 §7.13): the inbox in the public partition, `reply_in_thread`,
2//! sequences and newsletters in the back office, and delivery statistics as a metric
3//! source.
4//!
5//! | Tool | Effect class | Side | Default cap |
6//! |---|---|---|---|
7//! | `email_list_inbox` | `read` | public | Read |
8//! | `email_reply_in_thread` | `send_external` | public | Within playbook |
9//! | `email_send_sequence_step` | `send_external` | back office | Within playbook and consent |
10//! | `email_send_newsletter` | `send_external` | back office | Within playbook and consent |
11//! | `email_delivery_stats` | `read` | back office | Read |
12//! | `email_check_domain` | `read` | back office | Read |
13//!
14//! An [`EmailDriver`] only moves mail. [`EmailOutbox`] keeps the rules over any of them:
15//!
16//! | Rule | Spec |
17//! |---|---|
18//! | Every outbound message ends with the [`Disclosure`] line naming the owner and saying an AI agent wrote it | A-I17 |
19//! | An unsubscribe or a revocation is read before every send, so it takes effect before the next one; an unsubscribe mail, a bounce and a complaint are recorded as the inbox is read | A-I17 |
20//! | SPF, DKIM and DMARC are checked before the first send; sequences and newsletters are refused until all three pass | §7.13 |
21//! | A sequence step or newsletter goes only to a recipient with a live consent receipt for its scope, checked at send time | A-I8 |
22//! | A reply goes to the thread's sender only — no new recipients, no attachments — from a playbook template, at a rate limit, never to an automatic message | §7.10 |
23//!
24//! | Adapter | Feature |
25//! |---|---|
26//! | [`InMemoryEmail`] | — |
27//! | `ImapSmtpEmail`: IMAP (RFC 9051) to read, SMTP (RFC 5321) to send | `imap-smtp` |
28
29use std::collections::BTreeMap;
30use std::sync::{Arc, Mutex, PoisonError};
31use std::time::Duration;
32
33use adk_core::Tool;
34use adk_kernel::drivers::EffectClass;
35use async_trait::async_trait;
36use chrono::{DateTime, Utc};
37use serde::{Deserialize, Serialize};
38use serde_json::{Value, json};
39use tokio::sync::Mutex as AsyncMutex;
40use uuid::Uuid;
41
42use crate::class::{AutonomyCap, Side, ToolSpec};
43use crate::error::{DriverError, Result};
44use crate::metrics::{KpiSource, unknown_metric};
45use crate::outbound::{
46    ConsentCheck, Disclosure, InMemoryConsent, InMemorySuppressions, Limiter, RateLimit,
47    ReplyTemplates, Suppression, SuppressionList, SuppressionScope, ThreadReplier, fields_arg,
48    str_arg,
49};
50use crate::tools::DriverTool;
51
52mod auth;
53#[cfg(feature = "imap-smtp")]
54mod imap;
55#[cfg(feature = "imap-smtp")]
56mod imap_smtp;
57pub(crate) mod mime;
58#[cfg(feature = "imap-smtp")]
59mod smtp;
60#[cfg(feature = "imap-smtp")]
61mod tls;
62
63#[cfg(feature = "system-dns")]
64pub use auth::SystemTxtLookup;
65pub use auth::{AuthCheck, DomainAuthCheck, DomainAuthReport, SenderPolicy, StaticTxt, TxtLookup};
66#[cfg(feature = "imap-smtp")]
67pub use imap_smtp::{ImapSmtpEmail, MailEndpoint, MailSecurity};
68
69/// How long a passing domain check stays good before it is run again.
70const AUTH_FRESHNESS: chrono::Duration = chrono::Duration::hours(24);
71
72/// A mailbox: an address and an optional display name.
73#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75#[non_exhaustive]
76pub struct Mailbox {
77    /// The display name.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub name: Option<String>,
80    /// The address.
81    pub address: String,
82}
83
84impl Mailbox {
85    /// The mailbox `address`.
86    pub fn new(address: impl Into<String>) -> Self {
87        Self { name: None, address: address.into().trim().to_string() }
88    }
89
90    /// Sets the display name.
91    #[must_use]
92    pub fn with_name(mut self, name: impl Into<String>) -> Self {
93        self.name = Some(name.into());
94        self
95    }
96}
97
98/// What an inbound message is (spec 3.5 §7.13).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
100#[serde(rename_all = "camelCase")]
101#[non_exhaustive]
102pub enum InboundKind {
103    /// A message from a person.
104    Message,
105    /// A delivery report that a message failed (RFC 3464).
106    Bounce,
107    /// A complaint report (RFC 5965).
108    Complaint,
109    /// A request to unsubscribe, by the `mailto` unsubscribe convention (RFC 2369).
110    Unsubscribe,
111}
112
113/// A message in the inbox (spec 3.5 §7.13): untrusted input, read in the public partition
114/// only (A-I3).
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase")]
117#[non_exhaustive]
118pub struct InboundEmail {
119    /// Its `Message-ID`, without angle brackets.
120    pub id: String,
121    /// Its thread: the first message id of `References`, or `In-Reply-To`, or its own.
122    pub thread: String,
123    /// The sender.
124    pub from: Mailbox,
125    /// The `To` recipients.
126    pub to: Vec<Mailbox>,
127    /// The `Cc` recipients.
128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
129    pub cc: Vec<Mailbox>,
130    /// The subject, at most 300 characters.
131    pub subject: String,
132    /// The plain text, at most 32,000 characters.
133    pub text: String,
134    /// When it arrived.
135    pub received_at: DateTime<Utc>,
136    /// The message it answers.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub in_reply_to: Option<String>,
139    /// Its `References`.
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub references: Vec<String>,
142    /// What it is.
143    pub kind: InboundKind,
144    /// Whether software sent it on its own (RFC 3834), so it gets no reply.
145    #[serde(default)]
146    pub auto_submitted: bool,
147    /// For a bounce or complaint, the recipient it is about.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub report_recipient: Option<String>,
150}
151
152impl InboundEmail {
153    /// A plain message from `from` with `subject` and `text`, its own thread, for tests and
154    /// the in-memory driver.
155    pub fn message(from: Mailbox, subject: impl Into<String>, text: impl Into<String>) -> Self {
156        let id = format!("{}@inbound.invalid", Uuid::new_v4().simple());
157        Self {
158            thread: id.clone(),
159            id,
160            from,
161            to: Vec::new(),
162            cc: Vec::new(),
163            subject: subject.into(),
164            text: text.into(),
165            received_at: Utc::now(),
166            in_reply_to: None,
167            references: Vec::new(),
168            kind: InboundKind::Message,
169            auto_submitted: false,
170            report_recipient: None,
171        }
172    }
173
174    /// Reads a raw RFC 5322 message that arrived at `received_at`.
175    pub fn parse(raw: &[u8], received_at: DateTime<Utc>) -> Self {
176        mime::parse_message(
177            raw,
178            received_at,
179            &format!("{}@inbound.invalid", Uuid::new_v4().simple()),
180        )
181    }
182}
183
184/// A page of the inbox, after a cursor.
185#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187#[non_exhaustive]
188pub struct InboxPage {
189    /// The messages, oldest first.
190    pub messages: Vec<InboundEmail>,
191    /// The cursor after the last message, for the next read; unchanged when there are none.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub cursor: Option<String>,
194}
195
196/// A message to send.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct OutboundEmail {
201    /// Its `Message-ID`, without angle brackets.
202    pub message_id: String,
203    /// The sender: the site's address.
204    pub from: Mailbox,
205    /// The recipients.
206    pub to: Vec<Mailbox>,
207    /// The subject.
208    pub subject: String,
209    /// The plain text.
210    pub text: String,
211    /// The message it answers.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub in_reply_to: Option<String>,
214    /// Its `References`.
215    #[serde(default, skip_serializing_if = "Vec::is_empty")]
216    pub references: Vec<String>,
217    /// Further headers, such as `List-Unsubscribe`.
218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
219    pub headers: Vec<(String, String)>,
220}
221
222impl OutboundEmail {
223    /// The message's wire form at `date` (RFC 5322), with CRLF line ends, as SMTP sends it.
224    ///
225    /// # Errors
226    ///
227    /// Returns [`DriverError::Invalid`] for a header value with a line break or a message
228    /// with no recipient.
229    pub fn to_wire(&self, date: DateTime<Utc>) -> Result<Vec<u8>> {
230        mime::render_message(self, date)
231    }
232}
233
234/// A message the driver handed on.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "camelCase")]
237#[non_exhaustive]
238pub struct SentEmail {
239    /// Its `Message-ID`.
240    pub message_id: String,
241    /// The recipients the server accepted.
242    pub accepted: Vec<String>,
243    /// When.
244    pub at: DateTime<Utc>,
245}
246
247/// Delivery statistics over a window (spec 3.5 §7.12, §7.13).
248#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "camelCase")]
250#[non_exhaustive]
251pub struct DeliveryStats {
252    /// Messages accepted by the sending server.
253    pub sent: u64,
254    /// Recipients the sending server refused.
255    pub rejected: u64,
256    /// Bounces received.
257    pub bounced: u64,
258    /// Complaints received.
259    pub complaints: u64,
260}
261
262/// An email service (spec 3.5 §7.13): reads the inbox, sends one message, counts deliveries.
263///
264/// It only moves mail; [`EmailOutbox`] keeps the rules. An adapter refuses nothing a rule
265/// would, so the conformance suite can show it moves mail faithfully.
266#[async_trait]
267pub trait EmailDriver: Send + Sync {
268    /// The adapter's name.
269    fn name(&self) -> &str;
270
271    /// The messages that arrived after `cursor` (from the start when `None`), oldest first,
272    /// at most `limit`.
273    ///
274    /// # Errors
275    ///
276    /// Returns the service's errors.
277    async fn inbox(&self, cursor: Option<&str>, limit: usize) -> Result<InboxPage>;
278
279    /// Sends `message`.
280    ///
281    /// # Errors
282    ///
283    /// Returns [`DriverError::Refused`] when the server accepted no recipient, and the
284    /// service's errors.
285    async fn send(&self, message: &OutboundEmail) -> Result<SentEmail>;
286
287    /// Delivery statistics over `[from, to)`.
288    ///
289    /// # Errors
290    ///
291    /// Returns the service's errors.
292    async fn delivery_stats(&self, from: DateTime<Utc>, to: DateTime<Utc>)
293    -> Result<DeliveryStats>;
294}
295
296/// Sends and receipts counted in process, for adapters whose service does not count them.
297#[derive(Debug, Default)]
298pub(crate) struct DeliveryLog {
299    events: Mutex<Vec<(DateTime<Utc>, DeliveryEvent)>>,
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub(crate) enum DeliveryEvent {
304    Sent,
305    Rejected,
306    Bounced,
307    Complained,
308}
309
310impl DeliveryLog {
311    pub(crate) fn record(&self, event: DeliveryEvent, at: DateTime<Utc>) {
312        self.events.lock().unwrap_or_else(PoisonError::into_inner).push((at, event));
313    }
314
315    /// Records the bounces and complaints of `messages`, once each.
316    pub(crate) fn record_reports(&self, messages: &[InboundEmail]) {
317        for message in messages {
318            match message.kind {
319                InboundKind::Bounce => self.record(DeliveryEvent::Bounced, message.received_at),
320                InboundKind::Complaint => {
321                    self.record(DeliveryEvent::Complained, message.received_at)
322                }
323                InboundKind::Message | InboundKind::Unsubscribe => {}
324            }
325        }
326    }
327
328    pub(crate) fn stats(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> DeliveryStats {
329        let events = self.events.lock().unwrap_or_else(PoisonError::into_inner);
330        let mut stats = DeliveryStats::default();
331        for (_, event) in events.iter().filter(|(at, _)| *at >= from && *at < to) {
332            match event {
333                DeliveryEvent::Sent => stats.sent += 1,
334                DeliveryEvent::Rejected => stats.rejected += 1,
335                DeliveryEvent::Bounced => stats.bounced += 1,
336                DeliveryEvent::Complained => stats.complaints += 1,
337            }
338        }
339        stats
340    }
341}
342
343/// An email service in process memory (spec 3.5 §7.13): messages delivered to it with
344/// [`deliver`](Self::deliver), and what it sent, for tests and as the hermetic reference
345/// of the [`EmailDriver`] conformance suite.
346///
347/// # Example
348///
349/// ```rust
350/// use adk_drivers::email::{EmailDriver, InMemoryEmail, InboundEmail, Mailbox};
351///
352/// # futures::executor::block_on(async {
353/// let email = InMemoryEmail::new();
354/// email.deliver(InboundEmail::message(Mailbox::new("ana@example.org"), "Hours?", "When do you open?"));
355/// let page = email.inbox(None, 10).await.unwrap();
356/// assert_eq!(page.messages.len(), 1);
357/// assert!(email.inbox(page.cursor.as_deref(), 10).await.unwrap().messages.is_empty());
358/// # });
359/// ```
360#[derive(Debug, Default)]
361pub struct InMemoryEmail {
362    inbox: Mutex<Vec<InboundEmail>>,
363    sent: Mutex<Vec<OutboundEmail>>,
364    refuse: Mutex<Vec<String>>,
365    log: DeliveryLog,
366}
367
368impl InMemoryEmail {
369    /// An empty mailbox.
370    pub fn new() -> Self {
371        Self::default()
372    }
373
374    /// Delivers `message` to the inbox.
375    pub fn deliver(&self, message: InboundEmail) {
376        self.log.record_reports(std::slice::from_ref(&message));
377        self.inbox.lock().unwrap_or_else(PoisonError::into_inner).push(message);
378    }
379
380    /// Everything sent, in order.
381    pub fn sent(&self) -> Vec<OutboundEmail> {
382        self.sent.lock().unwrap_or_else(PoisonError::into_inner).clone()
383    }
384
385    /// Makes the server refuse `address` from now on.
386    pub fn refuse(&self, address: &str) {
387        self.refuse
388            .lock()
389            .unwrap_or_else(PoisonError::into_inner)
390            .push(address.to_ascii_lowercase());
391    }
392}
393
394#[async_trait]
395impl EmailDriver for InMemoryEmail {
396    fn name(&self) -> &str {
397        "in-memory"
398    }
399
400    async fn inbox(&self, cursor: Option<&str>, limit: usize) -> Result<InboxPage> {
401        let after = match cursor {
402            Some(cursor) => cursor.parse::<usize>().map_err(|_| {
403                DriverError::invalid(format!("`{cursor}` is not a cursor this driver gave"))
404            })?,
405            None => 0,
406        };
407        let inbox = self.inbox.lock().unwrap_or_else(PoisonError::into_inner);
408        let messages: Vec<InboundEmail> = inbox.iter().skip(after).take(limit).cloned().collect();
409        Ok(InboxPage { cursor: Some((after + messages.len()).to_string()), messages })
410    }
411
412    async fn send(&self, message: &OutboundEmail) -> Result<SentEmail> {
413        let refused = self.refuse.lock().unwrap_or_else(PoisonError::into_inner).clone();
414        let at = Utc::now();
415        let mut accepted = Vec::new();
416        for recipient in &message.to {
417            if refused.contains(&recipient.address.to_ascii_lowercase()) {
418                self.log.record(DeliveryEvent::Rejected, at);
419            } else {
420                accepted.push(recipient.address.clone());
421            }
422        }
423        if accepted.is_empty() {
424            return Err(DriverError::refused("the server accepted no recipient"));
425        }
426        mime::render_message(message, at)?;
427        self.sent.lock().unwrap_or_else(PoisonError::into_inner).push(message.clone());
428        self.log.record(DeliveryEvent::Sent, at);
429        Ok(SentEmail { message_id: message.message_id.clone(), accepted, at })
430    }
431
432    async fn delivery_stats(
433        &self,
434        from: DateTime<Utc>,
435        to: DateTime<Utc>,
436    ) -> Result<DeliveryStats> {
437        Ok(self.log.stats(from, to))
438    }
439}
440
441/// What kind of send, for the rules (spec 3.5 §7.13).
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
443#[serde(rename_all = "camelCase")]
444#[non_exhaustive]
445pub enum SendKind {
446    /// A reply in the thread of a person who wrote.
447    Reply,
448    /// A step of a nurture sequence: bulk.
449    Sequence,
450    /// A newsletter: bulk.
451    Newsletter,
452}
453
454impl SendKind {
455    /// Whether it is bulk sending, refused until SPF, DKIM and DMARC pass.
456    pub fn is_bulk(self) -> bool {
457        matches!(self, Self::Sequence | Self::Newsletter)
458    }
459}
460
461/// A thread the inbox read, as the outbox remembers it for replies.
462#[derive(Debug, Clone, PartialEq, Eq)]
463struct KnownThread {
464    sender: Mailbox,
465    subject: String,
466    last_message: String,
467    references: Vec<String>,
468    automatic: bool,
469}
470
471/// One recipient's outcome in a newsletter.
472#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
473#[serde(rename_all = "camelCase")]
474#[non_exhaustive]
475pub struct NewsletterReport {
476    /// The recipients it was sent to.
477    pub sent: Vec<String>,
478    /// The recipients skipped, with the rule that skipped each.
479    pub skipped: Vec<(String, String)>,
480}
481
482/// Makes the unsubscribe link of a recipient: an opaque link the edge serves, never the
483/// address itself in the URL.
484pub type UnsubscribeLink = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
485
486/// The rules over an [`EmailDriver`] (spec 3.5 §7.10, §7.13, A-I8, A-I17); see the module
487/// documentation for the table.
488///
489/// # Example
490///
491/// ```rust
492/// use std::collections::BTreeMap;
493/// use std::sync::Arc;
494/// use adk_drivers::email::{EmailOutbox, InMemoryEmail, InboundEmail, Mailbox, SenderPolicy, StaticTxt};
495/// use adk_drivers::{Disclosure, ReplyTemplates};
496///
497/// # futures::executor::block_on(async {
498/// let mail = Arc::new(InMemoryEmail::new());
499/// let outbox = EmailOutbox::builder(mail.clone(), Mailbox::new("hello@bakery.example"), Disclosure::new("Wanjiru's Bakery").unwrap())
500///     .domain_auth(Arc::new(StaticTxt::new()), SenderPolicy::new("bakery.example", "mail", "include:_spf.mail.example"))
501///     .templates(ReplyTemplates::new().template("hours", "Hi {name}, we open at 7am."))
502///     .build();
503/// mail.deliver(InboundEmail::message(Mailbox::new("ana@example.org"), "Hours?", "When do you open?"));
504/// let page = outbox.read_inbox(None, 10).await.unwrap();
505/// let thread = page.messages[0].thread.clone();
506/// let fields = BTreeMap::from([("name".to_string(), "Ana".to_string())]);
507/// outbox.reply(&thread, "hours", &fields).await.unwrap();
508/// let sent = &mail.sent()[0];
509/// assert_eq!(sent.to, [Mailbox::new("ana@example.org")]);
510/// assert!(sent.text.ends_with("This message was written by an AI agent for Wanjiru's Bakery."));
511/// # });
512/// ```
513pub struct EmailOutbox {
514    driver: Arc<dyn EmailDriver>,
515    from: Mailbox,
516    disclosure: Disclosure,
517    suppressions: Arc<dyn SuppressionList>,
518    consent: Arc<dyn ConsentCheck>,
519    auth: Option<(DomainAuthCheck, SenderPolicy)>,
520    report: AsyncMutex<Option<DomainAuthReport>>,
521    templates: ReplyTemplates,
522    per_thread: Limiter,
523    replies: Limiter,
524    threads: Mutex<BTreeMap<String, KnownThread>>,
525    unsubscribe_link: Option<UnsubscribeLink>,
526}
527
528impl std::fmt::Debug for EmailOutbox {
529    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
530        f.debug_struct("EmailOutbox")
531            .field("driver", &self.driver.name())
532            .field("from", &self.from)
533            .finish_non_exhaustive()
534    }
535}
536
537/// Builds an [`EmailOutbox`].
538pub struct EmailOutboxBuilder {
539    outbox: EmailOutbox,
540}
541
542impl EmailOutboxBuilder {
543    /// Where unsubscribes and revocations are kept; in memory by default.
544    #[must_use]
545    pub fn suppressions(mut self, suppressions: Arc<dyn SuppressionList>) -> Self {
546        self.outbox.suppressions = suppressions;
547        self
548    }
549
550    /// Where consent receipts are checked; by default none is live, so no sequence or
551    /// newsletter goes out.
552    #[must_use]
553    pub fn consent(mut self, consent: Arc<dyn ConsentCheck>) -> Self {
554        self.outbox.consent = consent;
555        self
556    }
557
558    /// How the sending domain's SPF, DKIM and DMARC are checked. Without it the domain is
559    /// never checked, so sequences and newsletters are refused.
560    #[must_use]
561    pub fn domain_auth(mut self, lookup: Arc<dyn TxtLookup>, policy: SenderPolicy) -> Self {
562        self.outbox.auth = Some((DomainAuthCheck::new(lookup), policy));
563        self
564    }
565
566    /// The playbook's reply templates.
567    #[must_use]
568    pub fn templates(mut self, templates: ReplyTemplates) -> Self {
569        self.outbox.templates = templates;
570        self
571    }
572
573    /// The reply rate limits: per thread (3 an hour by default) and overall (60 an hour).
574    #[must_use]
575    pub fn reply_limits(mut self, per_thread: RateLimit, overall: RateLimit) -> Self {
576        self.outbox.per_thread = Limiter::new(per_thread);
577        self.outbox.replies = Limiter::new(overall);
578        self
579    }
580
581    /// Makes each recipient's one-click unsubscribe link (RFC 8058), served by the edge;
582    /// without it, sequences and newsletters offer the `mailto` unsubscribe only.
583    #[must_use]
584    pub fn unsubscribe_link(mut self, link: UnsubscribeLink) -> Self {
585        self.outbox.unsubscribe_link = Some(link);
586        self
587    }
588
589    /// The outbox.
590    pub fn build(self) -> EmailOutbox {
591        self.outbox
592    }
593}
594
595impl EmailOutbox {
596    /// An outbox sending through `driver` as `from`, every message ending with
597    /// `disclosure`.
598    pub fn builder(
599        driver: Arc<dyn EmailDriver>,
600        from: Mailbox,
601        disclosure: Disclosure,
602    ) -> EmailOutboxBuilder {
603        EmailOutboxBuilder {
604            outbox: Self {
605                driver,
606                from,
607                disclosure,
608                suppressions: Arc::new(InMemorySuppressions::new()),
609                consent: Arc::new(InMemoryConsent::new()),
610                auth: None,
611                report: AsyncMutex::new(None),
612                templates: ReplyTemplates::new(),
613                per_thread: Limiter::new(RateLimit::new(3, Duration::from_secs(3_600))),
614                replies: Limiter::new(RateLimit::new(60, Duration::from_secs(3_600))),
615                threads: Mutex::default(),
616                unsubscribe_link: None,
617            },
618        }
619    }
620
621    /// The driver.
622    pub fn driver(&self) -> &Arc<dyn EmailDriver> {
623        &self.driver
624    }
625
626    /// The suppression list.
627    pub fn suppressions(&self) -> &Arc<dyn SuppressionList> {
628        &self.suppressions
629    }
630
631    /// Reads the inbox after `cursor` (spec 3.5 §7.13, the public partition's read).
632    ///
633    /// Before the page is returned, an unsubscribe mail suppresses its sender for
634    /// marketing, a bounce suppresses the bounced address, and a complaint suppresses the
635    /// complainer for marketing (A-I17); every message's thread is remembered for
636    /// `reply_in_thread`.
637    ///
638    /// # Errors
639    ///
640    /// Returns the driver's and the suppression list's errors.
641    pub async fn read_inbox(&self, cursor: Option<&str>, limit: usize) -> Result<InboxPage> {
642        let page = self.driver.inbox(cursor, limit).await?;
643        for message in &page.messages {
644            match (message.kind, &message.report_recipient) {
645                (InboundKind::Unsubscribe, _) => {
646                    self.suppressions
647                        .suppress(Suppression::new(
648                            &message.from.address,
649                            SuppressionScope::Marketing,
650                            "mailto",
651                        ))
652                        .await?;
653                }
654                (InboundKind::Bounce, Some(recipient)) => {
655                    self.suppressions
656                        .suppress(Suppression::new(recipient, SuppressionScope::All, "bounce"))
657                        .await?;
658                }
659                (InboundKind::Complaint, Some(recipient)) => {
660                    self.suppressions
661                        .suppress(Suppression::new(
662                            recipient,
663                            SuppressionScope::Marketing,
664                            "complaint",
665                        ))
666                        .await?;
667                }
668                _ => {}
669            }
670            if message.kind == InboundKind::Message {
671                let mut references = message.references.clone();
672                if !references.contains(&message.id) {
673                    references.push(message.id.clone());
674                }
675                self.threads.lock().unwrap_or_else(PoisonError::into_inner).insert(
676                    message.thread.clone(),
677                    KnownThread {
678                        sender: message.from.clone(),
679                        subject: message.subject.clone(),
680                        last_message: message.id.clone(),
681                        references,
682                        automatic: message.auto_submitted,
683                    },
684                );
685            }
686        }
687        Ok(page)
688    }
689
690    /// Records an unsubscribe or revocation of `recipient` from `source`, such as the edge's
691    /// one-click link (A-I17). It takes effect before the next send.
692    ///
693    /// # Errors
694    ///
695    /// Returns the suppression list's error.
696    pub async fn unsubscribe(
697        &self,
698        recipient: &str,
699        scope: SuppressionScope,
700        source: &str,
701    ) -> Result<()> {
702        self.suppressions.suppress(Suppression::new(recipient, scope, source)).await
703    }
704
705    /// Checks the sending domain's SPF, DKIM and DMARC now, and keeps the report.
706    ///
707    /// # Errors
708    ///
709    /// Returns [`DriverError::Refused`] when no domain check is configured, and the
710    /// resolver's error.
711    pub async fn check_domain(&self) -> Result<DomainAuthReport> {
712        let Some((check, policy)) = &self.auth else {
713            return Err(DriverError::refused(
714                "no domain check is configured for this outbox; give it the sending domain's policy",
715            ));
716        };
717        let report = check.run(policy).await?;
718        *self.report.lock().await = Some(report.clone());
719        Ok(report)
720    }
721
722    /// The last domain check, if one ran.
723    pub async fn domain_report(&self) -> Option<DomainAuthReport> {
724        self.report.lock().await.clone()
725    }
726
727    /// Runs the domain check before the first send, again when it is stale, and refuses
728    /// bulk sending unless it passes.
729    async fn before_send(&self, kind: SendKind) -> Result<()> {
730        let report = self.report.lock().await.clone();
731        let stale =
732            report.as_ref().is_none_or(|report| Utc::now() - report.checked_at > AUTH_FRESHNESS);
733        let report =
734            if stale && self.auth.is_some() { Some(self.check_domain().await?) } else { report };
735        if kind.is_bulk() {
736            match report {
737                Some(report) if report.passes() => {}
738                Some(report) => {
739                    return Err(DriverError::refused(format!(
740                        "bulk sending waits until SPF, DKIM and DMARC pass for {}: {}",
741                        report.domain,
742                        report.failures().join("; ")
743                    )));
744                }
745                None => {
746                    return Err(DriverError::refused(
747                        "bulk sending waits until the sending domain's SPF, DKIM and DMARC are checked and pass",
748                    ));
749                }
750            }
751        }
752        Ok(())
753    }
754
755    /// Refuses `recipient` when a suppression covers `kind`.
756    async fn check_suppression(&self, recipient: &str, kind: SendKind) -> Result<()> {
757        if let Some(suppression) = self.suppressions.lookup(recipient).await? {
758            let covers = suppression.scope == SuppressionScope::All || kind != SendKind::Reply;
759            if covers {
760                return Err(DriverError::refused(format!(
761                    "{recipient} unsubscribed or revoked ({:?}, {}); nothing more goes to them",
762                    suppression.scope, suppression.source
763                )));
764            }
765        }
766        Ok(())
767    }
768
769    fn new_message_id(&self) -> String {
770        let domain = self.from.address.rsplit('@').next().unwrap_or("site.invalid");
771        format!("{}@{domain}", Uuid::new_v4().simple())
772    }
773
774    /// The unsubscribe headers and footer of a bulk message to `recipient`.
775    fn unsubscribe_parts(&self, recipient: &str) -> (Vec<(String, String)>, String) {
776        let mailto = format!("mailto:{}?subject=unsubscribe", self.from.address);
777        let link = self.unsubscribe_link.as_ref().and_then(|link| link(recipient));
778        let mut headers = Vec::new();
779        let footer = match &link {
780            Some(link) => {
781                headers.push(("List-Unsubscribe".to_string(), format!("<{link}>, <{mailto}>")));
782                headers.push((
783                    "List-Unsubscribe-Post".to_string(),
784                    "List-Unsubscribe=One-Click".to_string(),
785                ));
786                format!("Unsubscribe: {link}")
787            }
788            None => {
789                headers.push(("List-Unsubscribe".to_string(), format!("<{mailto}>")));
790                format!(
791                    "Unsubscribe: reply with the subject \"unsubscribe\" or write to {}",
792                    self.from.address
793                )
794            }
795        };
796        (headers, footer)
797    }
798
799    /// Answers thread `thread` with template `template` (spec 3.5 §7.10): to the thread's
800    /// sender only, from the playbook, at the rate limits, ending with the disclosure.
801    ///
802    /// # Errors
803    ///
804    /// Returns [`DriverError::Refused`] for a thread the inbox did not read, an automatic
805    /// message, a revoked recipient or an unknown template; [`DriverError::RateLimited`]
806    /// over a limit; and the driver's errors.
807    pub async fn reply(
808        &self,
809        thread: &str,
810        template: &str,
811        fields: &BTreeMap<String, String>,
812    ) -> Result<SentEmail> {
813        let known = self
814            .threads
815            .lock()
816            .unwrap_or_else(PoisonError::into_inner)
817            .get(thread)
818            .cloned()
819            .ok_or_else(|| {
820                DriverError::refused(
821                    "reply_in_thread answers only a thread the inbox read; it never starts one",
822                )
823            })?;
824        if known.automatic {
825            return Err(DriverError::refused(
826                "the thread's last message was sent automatically; it gets no reply",
827            ));
828        }
829        let text = self.templates.render(template, fields)?;
830        self.check_suppression(&known.sender.address, SendKind::Reply).await?;
831        self.before_send(SendKind::Reply).await?;
832        self.per_thread.take(thread, "replies in one thread")?;
833        self.replies.take("all", "replies")?;
834        let subject = if known.subject.to_ascii_lowercase().starts_with("re:") {
835            known.subject.clone()
836        } else {
837            format!("Re: {}", known.subject)
838        };
839        let message = OutboundEmail {
840            message_id: self.new_message_id(),
841            from: self.from.clone(),
842            to: vec![known.sender.clone()],
843            subject,
844            text: self.disclosure.apply(&text),
845            in_reply_to: Some(known.last_message.clone()),
846            references: known.references.clone(),
847            headers: vec![("Auto-Submitted".into(), "auto-replied".into())],
848        };
849        self.driver.send(&message).await
850    }
851
852    /// Sends step `step` of sequence `sequence` to `to` (spec 3.5 §7.13, A-I8): bulk, so
853    /// only once the domain passes, and only with a live consent receipt for
854    /// `consent_scope`.
855    ///
856    /// # Errors
857    ///
858    /// Returns [`DriverError::Refused`] for failing domain authentication, a missing
859    /// consent receipt or a suppressed recipient, and the driver's errors.
860    pub async fn send_sequence_step(
861        &self,
862        to: &Mailbox,
863        subject: &str,
864        text: &str,
865        consent_scope: &str,
866    ) -> Result<SentEmail> {
867        self.before_send(SendKind::Sequence).await?;
868        self.check_bulk_recipient(&to.address, consent_scope).await?;
869        let (headers, footer) = self.unsubscribe_parts(&to.address);
870        let message = OutboundEmail {
871            message_id: self.new_message_id(),
872            from: self.from.clone(),
873            to: vec![to.clone()],
874            subject: subject.to_string(),
875            text: self.disclosure.apply(&format!("{}\n\n{footer}", text.trim_end())),
876            in_reply_to: None,
877            references: Vec::new(),
878            headers,
879        };
880        self.driver.send(&message).await
881    }
882
883    async fn check_bulk_recipient(&self, address: &str, consent_scope: &str) -> Result<()> {
884        self.check_suppression(address, SendKind::Sequence).await?;
885        if !self.consent.is_live(address, consent_scope).await? {
886            return Err(DriverError::refused(format!(
887                "{address} holds no live consent for `{consent_scope}` (spec 3.5 A-I8)"
888            )));
889        }
890        Ok(())
891    }
892
893    /// Sends a newsletter to each of `recipients` separately (spec 3.5 §7.13): bulk, so only
894    /// once the domain passes; a recipient without a live consent receipt for
895    /// `consent_scope`, or suppressed, is skipped and named in the report.
896    ///
897    /// # Errors
898    ///
899    /// Returns [`DriverError::Refused`] for failing domain authentication; a recipient's
900    /// failure is reported, not returned.
901    pub async fn send_newsletter(
902        &self,
903        subject: &str,
904        text: &str,
905        recipients: &[Mailbox],
906        consent_scope: &str,
907    ) -> Result<NewsletterReport> {
908        self.before_send(SendKind::Newsletter).await?;
909        let mut report = NewsletterReport { sent: Vec::new(), skipped: Vec::new() };
910        for recipient in recipients {
911            if let Err(error) = self.check_bulk_recipient(&recipient.address, consent_scope).await {
912                report.skipped.push((recipient.address.clone(), error.to_string()));
913                continue;
914            }
915            let (headers, footer) = self.unsubscribe_parts(&recipient.address);
916            let message = OutboundEmail {
917                message_id: self.new_message_id(),
918                from: self.from.clone(),
919                to: vec![recipient.clone()],
920                subject: subject.to_string(),
921                text: self.disclosure.apply(&format!("{}\n\n{footer}", text.trim_end())),
922                in_reply_to: None,
923                references: Vec::new(),
924                headers,
925            };
926            match self.driver.send(&message).await {
927                Ok(_) => report.sent.push(recipient.address.clone()),
928                Err(error) => report.skipped.push((recipient.address.clone(), error.to_string())),
929            }
930        }
931        Ok(report)
932    }
933}
934
935#[async_trait]
936impl ThreadReplier for EmailOutbox {
937    fn prefix(&self) -> &str {
938        "email"
939    }
940
941    async fn reply_in_thread(
942        &self,
943        thread: &str,
944        template: &str,
945        fields: &BTreeMap<String, String>,
946    ) -> Result<Value> {
947        let sent = self.reply(thread, template, fields).await?;
948        Ok(serde_json::to_value(sent).unwrap_or_default())
949    }
950}
951
952/// The metrics of [`EmailOutbox`] as a [`KpiSource`].
953pub const EMAIL_METRICS: [&str; 6] = [
954    "email.sent",
955    "email.rejected",
956    "email.bounced",
957    "email.complaints",
958    "email.bounce_rate",
959    "email.complaint_rate",
960];
961
962impl EmailOutbox {
963    /// The metrics it measures, as KPIs name them.
964    pub fn metrics(&self) -> Vec<String> {
965        EMAIL_METRICS.iter().map(|metric| (*metric).to_string()).collect()
966    }
967
968    /// The value of `metric` over `[from, to)`; `None` when there is no data for the
969    /// window.
970    ///
971    /// # Errors
972    ///
973    /// Returns [`DriverError::Invalid`] for a metric it does
974    /// not measure, and the service's errors.
975    pub async fn measure(
976        &self,
977        metric: &str,
978        from: DateTime<Utc>,
979        to: DateTime<Utc>,
980    ) -> Result<Option<f64>> {
981        let stats = self.driver.delivery_stats(from, to).await?;
982        let rate = |count: u64| (stats.sent > 0).then(|| count as f64 / stats.sent as f64);
983        Ok(match metric {
984            "email.sent" => Some(stats.sent as f64),
985            "email.rejected" => Some(stats.rejected as f64),
986            "email.bounced" => Some(stats.bounced as f64),
987            "email.complaints" => Some(stats.complaints as f64),
988            "email.bounce_rate" => rate(stats.bounced),
989            "email.complaint_rate" => rate(stats.complaints),
990            _ => return Err(unknown_metric("email", self.metrics(), metric)),
991        })
992    }
993}
994
995#[async_trait]
996impl KpiSource for EmailOutbox {
997    fn name(&self) -> &str {
998        "email"
999    }
1000
1001    async fn read(
1002        &self,
1003        _site: Uuid,
1004        metric: &str,
1005        from: DateTime<Utc>,
1006        to: DateTime<Utc>,
1007    ) -> adk_kernel::Result<Option<f64>> {
1008        Ok(self.measure(metric, from, to).await?)
1009    }
1010}
1011
1012fn object_schema(properties: Value, required: &[&str]) -> Value {
1013    json!({ "type": "object", "properties": properties, "required": required })
1014}
1015
1016fn list_inbox_schema() -> Value {
1017    object_schema(
1018        json!({
1019            "cursor": {"type": "string", "description": "The cursor of the last read; omit to read from the start"},
1020            "limit": {"type": "integer", "minimum": 1, "maximum": 100}
1021        }),
1022        &[],
1023    )
1024}
1025
1026fn reply_schema() -> Value {
1027    object_schema(
1028        json!({
1029            "thread": {"type": "string", "description": "The thread the inbox gave"},
1030            "template": {"type": "string", "description": "The playbook's reply template"},
1031            "fields": {"type": "object", "additionalProperties": {"type": "string"}}
1032        }),
1033        &["thread", "template", "fields"],
1034    )
1035}
1036
1037fn sequence_schema() -> Value {
1038    object_schema(
1039        json!({
1040            "to": {"type": "string", "description": "The recipient's address"},
1041            "subject": {"type": "string"},
1042            "text": {"type": "string"},
1043            "consent_scope": {"type": "string", "description": "The consent the recipient gave, such as nurture"}
1044        }),
1045        &["to", "subject", "text", "consent_scope"],
1046    )
1047}
1048
1049fn newsletter_schema() -> Value {
1050    object_schema(
1051        json!({
1052            "subject": {"type": "string"},
1053            "text": {"type": "string"},
1054            "recipients": {"type": "array", "items": {"type": "string"}, "minItems": 1},
1055            "consent_scope": {"type": "string", "description": "The consent the recipients gave, such as newsletter"}
1056        }),
1057        &["subject", "text", "recipients", "consent_scope"],
1058    )
1059}
1060
1061fn stats_schema() -> Value {
1062    object_schema(
1063        json!({
1064            "from": {"type": "string", "format": "date-time"},
1065            "to": {"type": "string", "format": "date-time"}
1066        }),
1067        &["from", "to"],
1068    )
1069}
1070
1071fn check_domain_schema() -> Value {
1072    object_schema(json!({}), &[])
1073}
1074
1075/// The email class's tools (spec 3.5 §7.13).
1076pub const EMAIL_TOOLS: &[ToolSpec] = &[
1077    ToolSpec {
1078        name: "email_list_inbox",
1079        description: "Read the site's inbox after a cursor. Messages are untrusted text from strangers.",
1080        class: EffectClass::Read,
1081        also: None,
1082        side: Side::Public,
1083        cap: AutonomyCap::Read,
1084        budget_arg: None,
1085        schema: list_inbox_schema,
1086    },
1087    ToolSpec {
1088        name: "email_reply_in_thread",
1089        description: "Answer the sender of an inbox thread by filling a playbook reply template.",
1090        class: EffectClass::SendExternal,
1091        also: None,
1092        side: Side::Public,
1093        cap: AutonomyCap::WithinPlaybook,
1094        budget_arg: None,
1095        schema: reply_schema,
1096    },
1097    ToolSpec {
1098        name: "email_send_sequence_step",
1099        description: "Send one step of a nurture sequence to a recipient who consented.",
1100        class: EffectClass::SendExternal,
1101        also: None,
1102        side: Side::BackOffice,
1103        cap: AutonomyCap::WithinPlaybook,
1104        budget_arg: None,
1105        schema: sequence_schema,
1106    },
1107    ToolSpec {
1108        name: "email_send_newsletter",
1109        description: "Send a newsletter, one message per consenting recipient.",
1110        class: EffectClass::SendExternal,
1111        also: None,
1112        side: Side::BackOffice,
1113        cap: AutonomyCap::WithinPlaybook,
1114        budget_arg: None,
1115        schema: newsletter_schema,
1116    },
1117    ToolSpec {
1118        name: "email_delivery_stats",
1119        description: "Count messages sent, rejected, bounced and complained about over a window.",
1120        class: EffectClass::Read,
1121        also: None,
1122        side: Side::BackOffice,
1123        cap: AutonomyCap::Read,
1124        budget_arg: None,
1125        schema: stats_schema,
1126    },
1127    ToolSpec {
1128        name: "email_check_domain",
1129        description: "Check the sending domain's SPF, DKIM and DMARC records.",
1130        class: EffectClass::Read,
1131        also: None,
1132        side: Side::BackOffice,
1133        cap: AutonomyCap::Read,
1134        budget_arg: None,
1135        schema: check_domain_schema,
1136    },
1137];
1138
1139/// The time argument `name`, as RFC 3339.
1140pub(crate) fn time_arg(args: &Value, name: &str) -> Result<DateTime<Utc>> {
1141    let text = str_arg(args, name)?;
1142    DateTime::parse_from_rfc3339(&text).map(|time| time.with_timezone(&Utc)).map_err(|_| {
1143        DriverError::invalid(format!("`{name}` is a time such as 2026-10-01T00:00:00Z"))
1144    })
1145}
1146
1147/// The inbound message as a public agent reads it: its thread reference and its fields.
1148fn inbound_view(message: &InboundEmail) -> Value {
1149    json!({
1150        "thread": format!("email:{}", message.thread),
1151        "id": message.id,
1152        "from": message.from,
1153        "subject": message.subject,
1154        "text": message.text,
1155        "receivedAt": message.received_at,
1156        "kind": message.kind,
1157        "automatic": message.auto_submitted,
1158    })
1159}
1160
1161/// The email tools of `side` over `outbox` (spec 3.5 §7.13).
1162pub fn email_tools(outbox: Arc<EmailOutbox>, side: Side) -> Vec<Arc<dyn Tool>> {
1163    let name = format!("email/{}", outbox.driver.name());
1164    let mut tools = Vec::new();
1165    for tool in EMAIL_TOOLS.iter().filter(|tool| tool.side == side) {
1166        let outbox = Arc::clone(&outbox);
1167        let tool: Arc<dyn Tool> = match tool.name {
1168            "email_list_inbox" => DriverTool::shared(tool, &name, move |args| {
1169                let outbox = Arc::clone(&outbox);
1170                Box::pin(async move {
1171                    let cursor = args.get("cursor").and_then(Value::as_str).map(str::to_string);
1172                    let limit =
1173                        args.get("limit").and_then(Value::as_u64).unwrap_or(20).clamp(1, 100)
1174                            as usize;
1175                    let page = outbox.read_inbox(cursor.as_deref(), limit).await?;
1176                    let messages: Vec<Value> = page.messages.iter().map(inbound_view).collect();
1177                    Ok(json!({ "messages": messages, "cursor": page.cursor }))
1178                })
1179            }),
1180            "email_reply_in_thread" => DriverTool::shared(tool, &name, move |args| {
1181                let outbox = Arc::clone(&outbox);
1182                Box::pin(async move {
1183                    let thread = str_arg(&args, "thread")?;
1184                    let thread = thread.strip_prefix("email:").unwrap_or(&thread).to_string();
1185                    let sent = outbox
1186                        .reply(&thread, &str_arg(&args, "template")?, &fields_arg(&args)?)
1187                        .await?;
1188                    Ok(serde_json::to_value(sent).unwrap_or_default())
1189                })
1190            }),
1191            "email_send_sequence_step" => DriverTool::shared(tool, &name, move |args| {
1192                let outbox = Arc::clone(&outbox);
1193                Box::pin(async move {
1194                    let to = Mailbox::new(str_arg(&args, "to")?);
1195                    let sent = outbox
1196                        .send_sequence_step(
1197                            &to,
1198                            &str_arg(&args, "subject")?,
1199                            &str_arg(&args, "text")?,
1200                            &str_arg(&args, "consent_scope")?,
1201                        )
1202                        .await?;
1203                    Ok(serde_json::to_value(sent).unwrap_or_default())
1204                })
1205            }),
1206            "email_send_newsletter" => DriverTool::shared(tool, &name, move |args| {
1207                let outbox = Arc::clone(&outbox);
1208                Box::pin(async move {
1209                    let recipients: Vec<Mailbox> = args
1210                        .get("recipients")
1211                        .and_then(Value::as_array)
1212                        .ok_or_else(|| DriverError::invalid("`recipients` is a list of addresses"))?
1213                        .iter()
1214                        .filter_map(Value::as_str)
1215                        .map(Mailbox::new)
1216                        .collect();
1217                    let report = outbox
1218                        .send_newsletter(
1219                            &str_arg(&args, "subject")?,
1220                            &str_arg(&args, "text")?,
1221                            &recipients,
1222                            &str_arg(&args, "consent_scope")?,
1223                        )
1224                        .await?;
1225                    Ok(serde_json::to_value(report).unwrap_or_default())
1226                })
1227            }),
1228            "email_delivery_stats" => DriverTool::shared(tool, &name, move |args| {
1229                let outbox = Arc::clone(&outbox);
1230                Box::pin(async move {
1231                    let stats = outbox
1232                        .driver
1233                        .delivery_stats(time_arg(&args, "from")?, time_arg(&args, "to")?)
1234                        .await?;
1235                    Ok(serde_json::to_value(stats).unwrap_or_default())
1236                })
1237            }),
1238            _ => DriverTool::shared(tool, &name, move |_args| {
1239                let outbox = Arc::clone(&outbox);
1240                Box::pin(async move {
1241                    Ok(serde_json::to_value(outbox.check_domain().await?).unwrap_or_default())
1242                })
1243            }),
1244        };
1245        tools.push(tool);
1246    }
1247    tools
1248}