everruns-core 0.16.1

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
// System email abstraction.
//
// Decision: Keep email delivery as a core, system-wide service rather than an
// agent capability. Email sends are product/ops side effects owned by the host
// application, not tools exposed to agents.
// Decision: Keep provider details behind EmailSender so future SendGrid,
// Cloudflare, SES, or SMTP implementations can reuse the same call sites.
// Decision: Keep the sender fixed until product requirements justify
// per-feature or per-tenant sender identity.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use thiserror::Error;

pub mod resend;

pub use resend::{ResendEmailConfig, ResendEmailSender};

// Intentional current product sender. Keep this as `no-replay`, not `no-reply`,
// until the verified sender identity changes.
pub const SYSTEM_EMAIL_FROM: &str = "no-replay@everruns.com";
const SYSTEM_EMAIL_FROM_NAME: &str = "Everruns";

pub type EmailResult<T> = std::result::Result<T, EmailError>;

#[derive(Debug, Error)]
pub enum EmailError {
    #[error("Email configuration error: {0}")]
    Configuration(String),

    #[error("Invalid email request: {0}")]
    InvalidRequest(String),

    #[error("Email provider transport error: {0}")]
    Transport(String),

    #[error("Email provider error ({provider}, status {status}): {body}")]
    Provider {
        provider: &'static str,
        status: u16,
        body: String,
    },
}

impl EmailError {
    fn config(message: impl Into<String>) -> Self {
        Self::Configuration(message.into())
    }

    fn invalid(message: impl Into<String>) -> Self {
        Self::InvalidRequest(message.into())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailAddress {
    pub email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl EmailAddress {
    pub fn new(email: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            name: None,
        }
    }

    pub fn named(email: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            name: Some(name.into()),
        }
    }

    fn validate(&self, field: &str) -> EmailResult<()> {
        let email = self.email.trim();
        if email.is_empty() {
            return Err(EmailError::invalid(format!("{field} email is empty")));
        }
        if self.email != email {
            return Err(EmailError::invalid(format!(
                "{field} email must not include leading or trailing whitespace"
            )));
        }
        if email.contains(['\r', '\n']) {
            return Err(EmailError::invalid(format!(
                "{field} email contains a newline"
            )));
        }
        if email.contains([' ', '\t', ',', ';', '<', '>', '"', '\'', '(', ')', '[', ']']) {
            return Err(EmailError::invalid(format!(
                "{field} email must be a single mailbox address"
            )));
        }
        let mut parts = email.split('@');
        let local = parts.next().unwrap_or_default();
        let domain = parts.next().unwrap_or_default();
        let has_extra_parts = parts.next().is_some();
        if local.is_empty() || domain.is_empty() || has_extra_parts {
            return Err(EmailError::invalid(format!(
                "{field} email must be a single mailbox address"
            )));
        }
        if let Some(name) = &self.name
            && name.contains(['\r', '\n'])
        {
            return Err(EmailError::invalid(format!(
                "{field} name contains a newline"
            )));
        }
        Ok(())
    }

    fn format_for_provider(&self) -> String {
        match self.name.as_deref().filter(|name| !name.trim().is_empty()) {
            Some(name) => format!("{name} <{}>", self.email),
            None => self.email.clone(),
        }
    }
}

impl From<&str> for EmailAddress {
    fn from(email: &str) -> Self {
        Self::new(email)
    }
}

impl From<String> for EmailAddress {
    fn from(email: String) -> Self {
        Self::new(email)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailTag {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum EmailTemplate {
    Minimal(MinimalEmailTemplate),
    Basic(BasicEmailTemplate),
}

impl EmailTemplate {
    fn render(&self) -> EmailResult<RenderedEmail> {
        match self {
            Self::Minimal(template) => template.render(),
            Self::Basic(template) => template.render(),
        }
    }
}

// Validates the caller-supplied body shared by every template. Each template
// wraps this body differently, but all require non-empty text and HTML.
fn validate_body(text: &str, html: &str) -> EmailResult<()> {
    if text.trim().is_empty() {
        return Err(EmailError::invalid("email text is required"));
    }
    if html.trim().is_empty() {
        return Err(EmailError::invalid("email html is required"));
    }
    Ok(())
}

// Unbranded transactional template styled to match the app (sharp corners,
// grayscale surface, app foreground color). No Everruns wordmark, logo, or
// footer link — use this when the surrounding flow already carries branding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MinimalEmailTemplate {
    pub text: String,
    pub html: String,
}

impl MinimalEmailTemplate {
    pub fn new(text: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            html: html.into(),
        }
    }

    fn render(&self) -> EmailResult<RenderedEmail> {
        validate_body(&self.text, &self.html)?;
        Ok(RenderedEmail {
            text: self.text.clone(),
            // Neutral title keeps the minimal template free of any branding.
            html: wrap_email_html("Notification", None, &self.html, None),
        })
    }
}

// Branded transactional template. Same app styling as `MinimalEmailTemplate`,
// plus an Everruns logo + wordmark header and a footer linking to everruns.com.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BasicEmailTemplate {
    pub text: String,
    pub html: String,
}

impl BasicEmailTemplate {
    pub fn new(text: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            html: html.into(),
        }
    }

    fn render(&self) -> EmailResult<RenderedEmail> {
        validate_body(&self.text, &self.html)?;
        Ok(RenderedEmail {
            text: format!(
                "Everruns\n\n{}\n\n\nSent by Everruns · {EVERRUNS_SITE_URL}",
                self.text
            ),
            html: wrap_email_html(
                "Everruns",
                Some(&branded_header()),
                &self.html,
                Some(&branded_footer()),
            ),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedEmail {
    pub text: String,
    pub html: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailMessage {
    pub to: Vec<EmailAddress>,
    pub subject: String,
    pub template: EmailTemplate,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<EmailTag>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

impl EmailMessage {
    pub fn minimal(
        to: impl Into<EmailAddress>,
        subject: impl Into<String>,
        text: impl Into<String>,
        html: impl Into<String>,
    ) -> Self {
        Self {
            to: vec![to.into()],
            subject: subject.into(),
            template: EmailTemplate::Minimal(MinimalEmailTemplate::new(text, html)),
            tags: Vec::new(),
            idempotency_key: None,
        }
    }

    pub fn basic(
        to: impl Into<EmailAddress>,
        subject: impl Into<String>,
        text: impl Into<String>,
        html: impl Into<String>,
    ) -> Self {
        Self {
            to: vec![to.into()],
            subject: subject.into(),
            template: EmailTemplate::Basic(BasicEmailTemplate::new(text, html)),
            tags: Vec::new(),
            idempotency_key: None,
        }
    }

    pub fn with_idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }

    pub fn with_tag(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.push(EmailTag {
            name: name.into(),
            value: value.into(),
        });
        self
    }

    fn validate(&self) -> EmailResult<RenderedEmail> {
        if self.to.is_empty() {
            return Err(EmailError::invalid("at least one to recipient is required"));
        }
        if self.subject.trim().is_empty() {
            return Err(EmailError::invalid("subject is required"));
        }
        for address in &self.to {
            address.validate("to")?;
        }
        for tag in &self.tags {
            if tag.name.trim().is_empty() {
                return Err(EmailError::invalid("email tag name is required"));
            }
            if tag.value.trim().is_empty() {
                return Err(EmailError::invalid("email tag value is required"));
            }
        }
        if let Some(key) = &self.idempotency_key
            && key.len() > 256
        {
            return Err(EmailError::invalid(
                "idempotency_key must be 256 characters or fewer",
            ));
        }
        if let Some(key) = &self.idempotency_key
            && key.chars().any(|ch| ch.is_ascii_control())
        {
            return Err(EmailError::invalid(
                "idempotency_key must not contain control characters",
            ));
        }
        self.template.render()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SentEmail {
    pub provider: &'static str,
    pub id: String,
}

#[async_trait]
pub trait EmailSender: Send + Sync {
    async fn send_email(&self, message: EmailMessage) -> EmailResult<SentEmail>;

    fn name(&self) -> &'static str {
        "EmailSender"
    }
}

#[derive(Debug, Clone, Default)]
pub struct NoopEmailSender;

#[async_trait]
impl EmailSender for NoopEmailSender {
    async fn send_email(&self, message: EmailMessage) -> EmailResult<SentEmail> {
        message.validate()?;
        Ok(SentEmail {
            provider: "noop",
            id: "noop".to_string(),
        })
    }

    fn name(&self) -> &'static str {
        "NoopEmailSender"
    }
}

#[derive(Debug, Clone, Default)]
pub struct DisabledEmailSender;

#[async_trait]
impl EmailSender for DisabledEmailSender {
    async fn send_email(&self, _message: EmailMessage) -> EmailResult<SentEmail> {
        Err(EmailError::config("system email delivery is disabled"))
    }

    fn name(&self) -> &'static str {
        "DisabledEmailSender"
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SystemEmailConfig {
    Disabled,
    Resend(ResendEmailConfig),
}

impl SystemEmailConfig {
    pub fn from_env() -> EmailResult<Self> {
        let provider = env_opt("EMAIL_PROVIDER").map(|provider| provider.to_ascii_lowercase());
        match provider.as_deref() {
            None | Some("disabled") => Ok(Self::Disabled),
            Some("resend") => ResendEmailConfig::from_env().map(Self::Resend),
            Some(provider) => Err(EmailError::config(format!(
                "unsupported EMAIL_PROVIDER '{provider}'"
            ))),
        }
    }

    pub fn into_sender(self) -> Arc<dyn EmailSender> {
        self.into_sender_with_egress(Arc::new(crate::DirectEgressService::default()))
    }

    pub fn into_sender_with_egress(
        self,
        egress_service: Arc<dyn crate::EgressService>,
    ) -> Arc<dyn EmailSender> {
        match self {
            Self::Disabled => Arc::new(DisabledEmailSender),
            Self::Resend(config) => Arc::new(ResendEmailSender::with_egress_service(
                config,
                egress_service,
            )),
        }
    }
}

pub fn system_email_from() -> EmailAddress {
    EmailAddress::named(SYSTEM_EMAIL_FROM, SYSTEM_EMAIL_FROM_NAME)
}

fn env_opt(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|value| !value.is_empty())
}

// Brand tokens mirrored from apps/ui/src/app/design-system.css. Email clients
// cannot load the Geist webfont or resolve CSS variables, so the app's colors
// and sharp-corner (0px radius) shapes are inlined here as literals. Keep these
// in sync with the design system if the brand palette changes.
const BRAND_NAVY: &str = "#0A1636";
const BRAND_GOLD: &str = "#D4A43A";
const APP_BACKGROUND: &str = "#fafafa";
const APP_SURFACE: &str = "#ffffff";
const APP_BORDER: &str = "#e0e0e0";
const APP_FOREGROUND: &str = "#1a1a1a";
const APP_MUTED_FOREGROUND: &str = "#737373";
const EMAIL_FONT_STACK: &str =
    "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";

// Public Everruns surfaces. The logo must be a hosted absolute URL (most email
// clients block SVG and inline data URIs), so we reference the PNG served by
// the marketing site rather than the in-repo SVG. The 64px asset is sized for
// the 28px header logo at 2x retina (~3 KB) to keep messages small.
const EVERRUNS_SITE_URL: &str = "https://everruns.com";
const EVERRUNS_LOGO_URL: &str = "https://everruns.com/logo-64.png";

// App-styled HTML shell shared by every template. `title` sets the document
// `<title>` (kept neutral for the unbranded minimal template, since some clients
// surface it in previews). `header` and `footer` are optional pre-rendered table
// rows so branded templates can add a logo header and a footer link while the
// minimal template stays bare.
fn wrap_email_html(
    title: &str,
    header: Option<&str>,
    inner_html: &str,
    footer: Option<&str>,
) -> String {
    let header = header.unwrap_or("");
    let footer = footer.unwrap_or("");
    format!(
        r#"<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{title}</title>
</head>
<body style="margin:0;background:{APP_BACKGROUND};color:{APP_FOREGROUND};font-family:{EMAIL_FONT_STACK};">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:{APP_BACKGROUND};padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px;background:{APP_SURFACE};border:1px solid {APP_BORDER};border-radius:0;">
{header}          <tr>
            <td style="padding:28px;font-size:15px;line-height:1.6;color:{APP_FOREGROUND};">{inner_html}</td>
          </tr>
{footer}        </table>
      </td>
    </tr>
  </table>
</body>
</html>"#
    )
}

// Logo + wordmark header row, linking to everruns.com.
fn branded_header() -> String {
    format!(
        r#"          <tr>
            <td style="padding:24px 28px;border-bottom:1px solid {APP_BORDER};">
              <a href="{EVERRUNS_SITE_URL}" style="text-decoration:none;display:inline-block;">
                <img src="{EVERRUNS_LOGO_URL}" width="28" height="28" alt="Everruns" style="vertical-align:middle;border:0;">
                <span style="vertical-align:middle;margin-left:10px;font-size:18px;font-weight:700;color:{BRAND_NAVY};letter-spacing:-0.02em;">Everruns</span>
              </a>
            </td>
          </tr>
"#
    )
}

// Footer row linking back to everruns.com, with a gold accent link.
fn branded_footer() -> String {
    format!(
        r#"          <tr>
            <td style="padding:18px 28px;border-top:1px solid {APP_BORDER};font-size:12px;line-height:1.5;color:{APP_MUTED_FOREGROUND};">
              Sent by <a href="{EVERRUNS_SITE_URL}" style="color:{BRAND_GOLD};text-decoration:none;font-weight:600;">everruns.com</a>
            </td>
          </tr>
"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn minimal_template_requires_text_content() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                "user@example.com",
                "Empty",
                "",
                "<p>Hello</p>",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("text"));
    }

    #[tokio::test]
    async fn minimal_template_requires_html_content() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                "user@example.com",
                "Empty",
                "Hello",
                "  ",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("html"));
    }

    #[tokio::test]
    async fn minimal_template_is_app_styled_without_branding() {
        let message = EmailMessage::minimal("user@example.com", "Hi", "Hello", "<p>Hello</p>");
        let rendered = message.validate().unwrap();

        // Body is passed through verbatim — no branding prefix.
        assert_eq!(rendered.text, "Hello");
        assert!(rendered.html.contains("<p>Hello</p>"));
        // App styling: sharp corners and app surface/background colors.
        assert!(rendered.html.contains("border-radius:0"));
        assert!(rendered.html.contains(APP_BACKGROUND));
        // No branding at all in the minimal template — not even the document
        // <title>, which some clients surface in previews.
        assert!(!rendered.html.contains("Everruns"));
        assert!(!rendered.html.contains(EVERRUNS_LOGO_URL));
        assert!(!rendered.html.contains(EVERRUNS_SITE_URL));
        assert!(!rendered.html.contains("Sent by"));
    }

    #[tokio::test]
    async fn basic_template_adds_branding_logo_and_site_link() {
        let message = EmailMessage::basic("user@example.com", "Hi", "Hello", "<p>Hello</p>");
        let rendered = message.validate().unwrap();

        // Branded plain text: wordmark prefix and site link footer.
        assert!(rendered.text.starts_with("Everruns\n\nHello"));
        assert!(rendered.text.contains(EVERRUNS_SITE_URL));
        // Branded HTML: shares the app shell, plus logo, wordmark, and link.
        assert!(rendered.html.contains("<p>Hello</p>"));
        assert!(rendered.html.contains("border-radius:0"));
        assert!(rendered.html.contains("Everruns"));
        assert!(rendered.html.contains(EVERRUNS_LOGO_URL));
        assert!(
            rendered
                .html
                .contains(&format!(r#"href="{EVERRUNS_SITE_URL}""#))
        );
    }

    #[tokio::test]
    async fn disabled_sender_returns_configuration_error() {
        let sender = DisabledEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                "user@example.com",
                "Hi",
                "hello",
                "<p>hello</p>",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::Configuration(_)));
        assert!(error.to_string().contains("disabled"));
    }

    #[tokio::test]
    async fn idempotency_key_rejects_control_characters() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(
                EmailMessage::minimal("user@example.com", "Hi", "hello", "<p>hello</p>")
                    .with_idempotency_key("welcome\r\nX-Other: value"),
            )
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("control characters"));
    }

    #[tokio::test]
    async fn rejects_multi_recipient_in_single_to_field() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                "victim@example.com, attacker@example.com",
                "Hi",
                "hello",
                "<p>hello</p>",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("single mailbox"));
    }

    #[tokio::test]
    async fn rejects_structured_mailbox_syntax_in_raw_email_field() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                "Victim <victim@example.com>",
                "Hi",
                "hello",
                "<p>hello</p>",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("single mailbox"));
    }

    #[tokio::test]
    async fn rejects_email_with_surrounding_whitespace() {
        let sender = NoopEmailSender;
        let error = sender
            .send_email(EmailMessage::minimal(
                " user@example.com ",
                "Hi",
                "hello",
                "<p>hello</p>",
            ))
            .await
            .unwrap_err();

        assert!(matches!(error, EmailError::InvalidRequest(_)));
        assert!(error.to_string().contains("leading or trailing whitespace"));
    }
}