Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

10.6 KB
Raw Blame
//! Toolset inbound adapter for the Email service.

mod get_thread;
mod list_inboxes;
mod list_labels;
mod send_confirmed_email;
mod send_email;
mod set_sender_policy;
mod update_thread_labels;

#[cfg(test)]
mod test;

use crate::domain::{
    models::{EmailErr, Link, ResolvedSendingInbox, SendingInboxRequest},
    ports::{
        EmailAttachmentSendService, EmailService, GmailTokenProvider, NoOpEmailAttachmentSender,
    },
};
use ai_toolset::{AsyncToolCollection, ToolCallError};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use entity_access::domain::ports::EntityAccessService;
use macro_user_id::user_id::MacroUserIdStr;
use std::sync::Arc;

pub use get_thread::{GetThread, GetThreadResponse};
pub use list_inboxes::{ListInboxes, ListInboxesResponse, ToolInbox};
pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};
pub use send_confirmed_email::SendConfirmedEmail;
pub use send_email::{EmailAttachment, EmailRecipient, SendEmail, SendEmailResponse};
pub use set_sender_policy::{SetSenderPolicy, SetSenderPolicyResponse, ToolSenderPolicy};
pub use update_thread_labels::{UpdateThreadLabels, UpdateThreadLabelsResponse};

/// The caller's default inbox: the primary link they own. Falls back to any
/// link they own, then any accessible inbox. `caller_macro_id` is the caller's
/// own macro id (e.g. `macro|[email protected]`).
pub fn caller_primary_inbox<'a>(inboxes: &'a [Link], caller_macro_id: &str) -> Option<&'a Link> {
    inboxes
        .iter()
        .find(|l| l.is_primary && l.macro_id.to_string() == caller_macro_id)
        .or_else(|| {
            inboxes
                .iter()
                .find(|l| l.macro_id.to_string() == caller_macro_id)
        })
        .or_else(|| inboxes.first())
}

/// Resolve an optional inbox selector (an inbox's email address) against the
/// caller's accessible inboxes. `None` resolves to the caller's primary inbox.
/// Errors when the address matches no accessible inbox, so a caller can never
/// scope to an inbox they don't have.
pub fn resolve_inbox_selector<'a>(
    inboxes: &'a [Link],
    caller_macro_id: &str,
    requested: Option<&str>,
) -> Result<&'a Link, ToolCallError> {
    let Some(addr) = requested.map(str::trim).filter(|s| !s.is_empty()) else {
        return caller_primary_inbox(inboxes, caller_macro_id).ok_or_else(|| ToolCallError {
            description: "No email account is linked for this user.".to_string(),
            internal_error: anyhow::anyhow!("no accessible inboxes"),
        });
    };

    let mut matches = inboxes
        .iter()
        .filter(|l| l.email_address.0.as_ref().eq_ignore_ascii_case(addr));
    match (matches.next(), matches.next()) {
        (Some(link), None) => Ok(link),
        (Some(_), Some(_)) => Err(ToolCallError {
            description: format!("Multiple connected inboxes match \"{addr}\"; cannot pick one."),
            internal_error: anyhow::anyhow!("ambiguous inbox selector: {addr}"),
        }),
        (None, _) => Err(ToolCallError {
            description: format!(
                "No connected inbox matches \"{addr}\". Connected inboxes: {}.",
                inboxes
                    .iter()
                    .map(|l| l.email_address.0.as_ref())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            internal_error: anyhow::anyhow!("unknown inbox selector: {addr}"),
        }),
    }
}

/// Service context for email AI tools.
pub struct EmailToolContext<
    T: EmailService,
    G: GmailTokenProvider = crate::domain::ports::NoOpGmailTokenProvider,
    E: EntityAccessService = entity_access::domain::service::EntityAccessServiceImpl<
        entity_access::outbound::PgAccessRepository,
    >,
> {
    /// The email service instance.
    pub service: Arc<T>,
    /// The Gmail token provider for resolving OAuth access tokens.
    pub token_provider: Arc<G>,
    /// The entity access service for verifying thread access.
    pub entity_access_service: Arc<E>,
    /// Renders model-authored markdown into the HTML an email body carries.
    pub lexical_client: Arc<lexical_client::LexicalClient>,
    /// Sends a `SendEmail` call, staging its Macro-document attachments
    /// first. [`new`](Self::new) installs a sender that refuses attachments;
    /// hosts with attachment infrastructure swap in a real one through
    /// [`with_attachment_sender`](Self::with_attachment_sender).
    pub attachment_sender: Arc<dyn EmailAttachmentSendService>,
}

impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> Clone
    for EmailToolContext<T, G, E>
{
    fn clone(&self) -> Self {
        Self {
            service: self.service.clone(),
            token_provider: self.token_provider.clone(),
            entity_access_service: self.entity_access_service.clone(),
            lexical_client: self.lexical_client.clone(),
            attachment_sender: self.attachment_sender.clone(),
        }
    }
}

impl<T: EmailService, G: GmailTokenProvider, E: EntityAccessService> EmailToolContext<T, G, E> {
    /// Create a new email tool context.
    pub fn new(
        service: Arc<T>,
        token_provider: Arc<G>,
        entity_access_service: Arc<E>,
        lexical_client: Arc<lexical_client::LexicalClient>,
    ) -> Self {
        Self {
            attachment_sender: Arc::new(NoOpEmailAttachmentSender(service.clone())),
            service,
            token_provider,
            entity_access_service,
            lexical_client,
        }
    }

    /// Replace the sender `SendEmail` finishes through with one that can
    /// stage attachments.
    pub fn with_attachment_sender(
        mut self,
        attachment_sender: Arc<dyn EmailAttachmentSendService>,
    ) -> Self {
        self.attachment_sender = attachment_sender;
        self
    }

    /// Resolve the inbox a composed email goes out from, together with every
    /// inbox the caller can reach.
    ///
    /// The choice is the domain's; this only turns its refusals into
    /// something the model can act on - the error already names the
    /// connected addresses, which is exactly the correction it needs.
    pub async fn resolve_sending_inbox(
        &self,
        macro_id: MacroUserIdStr<'_>,
        request: SendingInboxRequest<'_>,
    ) -> Result<ResolvedSendingInbox, ToolCallError> {
        self.service
            .resolve_sending_inbox(macro_id, request)
            .await
            .map_err(|e| ToolCallError {
                description: match e {
                    EmailErr::InboxNotFound => {
                        "No email account is linked for this user.".to_owned()
                    }
                    ref other => other.to_string(),
                },
                internal_error: e.into(),
            })
    }

    /// Resolves a `SendEmail` body into base64url HTML, rendering the model's
    /// Markdown through the lexical service when no composer already did.
    pub async fn render_body(&self, body: &str) -> Result<ResolvedToolBody, ToolCallError> {
        if decode_composer_html(body).is_some() {
            return Ok(ResolvedToolBody {
                html: body.to_owned(),
                text: None,
            });
        }

        let rendered = self
            .lexical_client
            .markdown_to_html(body)
            .await
            .map_err(|e| ToolCallError {
                description: format!("Failed to render the email body: {e}"),
                internal_error: e,
            })?;

        Ok(ResolvedToolBody {
            html: URL_SAFE_NO_PAD.encode(rendered.html),
            text: Some(rendered.text),
        })
    }

    /// Resolve a Gmail OAuth access token for the given link.
    pub async fn resolve_access_token(&self, link: &Link) -> Result<String, ToolCallError> {
        self.token_provider
            .fetch_gmail_access_token(link)
            .await
            .map_err(|e| ToolCallError {
                description: format!("Failed to fetch Gmail access token: {e}"),
                internal_error: e.into(),
            })
    }
}

/// A `SendEmail` body resolved into what [`CreateDraftInput`] expects.
///
/// [`CreateDraftInput`]: crate::domain::models::CreateDraftInput
pub struct ResolvedToolBody {
    /// Base64url-encoded HTML, the encoding the domain decodes.
    pub html: String,
    /// The plain-text alternative, when this tool rendered the body and so
    /// has one. A composer-supplied body carries its own, or none.
    pub text: Option<String>,
}

/// True when `body` is the base64url HTML a composer exported, rather than
/// the Markdown the model writes.
///
/// The two hosts that finish `SendEmail` disagree about this field: the chat
/// and agent-session composers replace it with their exported HTML before the
/// tool runs, while a host that answers the review without a composer leaves
/// the model's Markdown in place. Real Markdown does not survive a base64url
/// decode - a space alone is outside the alphabet - and composer output is
/// always an element, so decoding and looking for a tag separates them.
fn decode_composer_html(body: &str) -> Option<String> {
    let decoded = URL_SAFE_NO_PAD.decode(body.as_bytes()).ok()?;
    let decoded = String::from_utf8(decoded).ok()?;
    decoded.trim_start().starts_with('<').then_some(decoded)
}

/// The full email toolset, for hosts that finish user tools: the deferring
/// `SendEmail`, which a composer or review card confirms, beside
/// `SendConfirmedEmail`, which sends on a confirmation the user already
/// gave in conversation. Both are always registered; the prompt decides
/// which fits the surface the prompt came from.
pub fn email_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
    T: EmailService,
    G: GmailTokenProvider,
    E: EntityAccessService,
{
    mcp_toolset()
        .add_user_tool::<SendEmail, EmailToolContext<T, G, E>>()
        .add_tool::<SendConfirmedEmail, EmailToolContext<T, G, E>>()
}

/// Email toolset for hosts without a composer (the MCP server and the
/// channel-mention bot) — excludes both sending tools: `SendEmail`'s draft
/// only a composer can review and send, and `SendConfirmedEmail` is for the
/// in-process agent's conversation turns, not for MCP clients with their
/// own confirmation policy.
pub fn mcp_toolset<T, G, E>() -> AsyncToolCollection<EmailToolContext<T, G, E>>
where
    T: EmailService,
    G: GmailTokenProvider,
    E: EntityAccessService,
{
    AsyncToolCollection::new()
        .add_tool::<UpdateThreadLabels, EmailToolContext<T, G, E>>()
        .add_tool::<GetThread, EmailToolContext<T, G, E>>()
        .add_tool::<ListLabels, EmailToolContext<T, G, E>>()
        .add_tool::<ListInboxes, EmailToolContext<T, G, E>>()
        .add_tool::<SetSenderPolicy, EmailToolContext<T, G, E>>()
}