1use 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
69const AUTH_FRESHNESS: chrono::Duration = chrono::Duration::hours(24);
71
72#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75#[non_exhaustive]
76pub struct Mailbox {
77 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub name: Option<String>,
80 pub address: String,
82}
83
84impl Mailbox {
85 pub fn new(address: impl Into<String>) -> Self {
87 Self { name: None, address: address.into().trim().to_string() }
88 }
89
90 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
100#[serde(rename_all = "camelCase")]
101#[non_exhaustive]
102pub enum InboundKind {
103 Message,
105 Bounce,
107 Complaint,
109 Unsubscribe,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase")]
117#[non_exhaustive]
118pub struct InboundEmail {
119 pub id: String,
121 pub thread: String,
123 pub from: Mailbox,
125 pub to: Vec<Mailbox>,
127 #[serde(default, skip_serializing_if = "Vec::is_empty")]
129 pub cc: Vec<Mailbox>,
130 pub subject: String,
132 pub text: String,
134 pub received_at: DateTime<Utc>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub in_reply_to: Option<String>,
139 #[serde(default, skip_serializing_if = "Vec::is_empty")]
141 pub references: Vec<String>,
142 pub kind: InboundKind,
144 #[serde(default)]
146 pub auto_submitted: bool,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub report_recipient: Option<String>,
150}
151
152impl InboundEmail {
153 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 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187#[non_exhaustive]
188pub struct InboxPage {
189 pub messages: Vec<InboundEmail>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub cursor: Option<String>,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "camelCase")]
199#[non_exhaustive]
200pub struct OutboundEmail {
201 pub message_id: String,
203 pub from: Mailbox,
205 pub to: Vec<Mailbox>,
207 pub subject: String,
209 pub text: String,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub in_reply_to: Option<String>,
214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
216 pub references: Vec<String>,
217 #[serde(default, skip_serializing_if = "Vec::is_empty")]
219 pub headers: Vec<(String, String)>,
220}
221
222impl OutboundEmail {
223 pub fn to_wire(&self, date: DateTime<Utc>) -> Result<Vec<u8>> {
230 mime::render_message(self, date)
231 }
232}
233
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "camelCase")]
237#[non_exhaustive]
238pub struct SentEmail {
239 pub message_id: String,
241 pub accepted: Vec<String>,
243 pub at: DateTime<Utc>,
245}
246
247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "camelCase")]
250#[non_exhaustive]
251pub struct DeliveryStats {
252 pub sent: u64,
254 pub rejected: u64,
256 pub bounced: u64,
258 pub complaints: u64,
260}
261
262#[async_trait]
267pub trait EmailDriver: Send + Sync {
268 fn name(&self) -> &str;
270
271 async fn inbox(&self, cursor: Option<&str>, limit: usize) -> Result<InboxPage>;
278
279 async fn send(&self, message: &OutboundEmail) -> Result<SentEmail>;
286
287 async fn delivery_stats(&self, from: DateTime<Utc>, to: DateTime<Utc>)
293 -> Result<DeliveryStats>;
294}
295
296#[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 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#[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 pub fn new() -> Self {
371 Self::default()
372 }
373
374 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 pub fn sent(&self) -> Vec<OutboundEmail> {
382 self.sent.lock().unwrap_or_else(PoisonError::into_inner).clone()
383 }
384
385 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
443#[serde(rename_all = "camelCase")]
444#[non_exhaustive]
445pub enum SendKind {
446 Reply,
448 Sequence,
450 Newsletter,
452}
453
454impl SendKind {
455 pub fn is_bulk(self) -> bool {
457 matches!(self, Self::Sequence | Self::Newsletter)
458 }
459}
460
461#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
473#[serde(rename_all = "camelCase")]
474#[non_exhaustive]
475pub struct NewsletterReport {
476 pub sent: Vec<String>,
478 pub skipped: Vec<(String, String)>,
480}
481
482pub type UnsubscribeLink = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
485
486pub 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
537pub struct EmailOutboxBuilder {
539 outbox: EmailOutbox,
540}
541
542impl EmailOutboxBuilder {
543 #[must_use]
545 pub fn suppressions(mut self, suppressions: Arc<dyn SuppressionList>) -> Self {
546 self.outbox.suppressions = suppressions;
547 self
548 }
549
550 #[must_use]
553 pub fn consent(mut self, consent: Arc<dyn ConsentCheck>) -> Self {
554 self.outbox.consent = consent;
555 self
556 }
557
558 #[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 #[must_use]
568 pub fn templates(mut self, templates: ReplyTemplates) -> Self {
569 self.outbox.templates = templates;
570 self
571 }
572
573 #[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 #[must_use]
584 pub fn unsubscribe_link(mut self, link: UnsubscribeLink) -> Self {
585 self.outbox.unsubscribe_link = Some(link);
586 self
587 }
588
589 pub fn build(self) -> EmailOutbox {
591 self.outbox
592 }
593}
594
595impl EmailOutbox {
596 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 pub fn driver(&self) -> &Arc<dyn EmailDriver> {
623 &self.driver
624 }
625
626 pub fn suppressions(&self) -> &Arc<dyn SuppressionList> {
628 &self.suppressions
629 }
630
631 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 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 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 pub async fn domain_report(&self) -> Option<DomainAuthReport> {
724 self.report.lock().await.clone()
725 }
726
727 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 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 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 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 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 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
952pub 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 pub fn metrics(&self) -> Vec<String> {
965 EMAIL_METRICS.iter().map(|metric| (*metric).to_string()).collect()
966 }
967
968 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
1075pub 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
1139pub(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
1147fn 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
1161pub 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}