Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): add SetSenderPolicy AI tool (#5935)
teo641355f94bee
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex 45c8152475..4317383080 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -70,6 +70,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [SendChannelMessage](/AI/mcp/tools/send-channel-message)- [SendEmail](/AI/mcp/tools/send-email)- [SetEntityProperty](/AI/mcp/tools/set-entity-property)+- [SetSenderPolicy](/AI/mcp/tools/set-sender-policy)- [Subagent](/AI/mcp/tools/subagent)- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)diff --git a/apps/docs/AI/mcp/tools/set-sender-policy.mdx b/apps/docs/AI/mcp/tools/set-sender-policy.mdxnew file mode 100644index 0000000000..7d7ec0e441--- /dev/null+++ b/apps/docs/AI/mcp/tools/set-sender-policy.mdx@@ -0,0 +1,26 @@+---+title: SetSenderPolicy+description: "Set where future mail from a sender lands in one of the user's inboxes. This is the same control a human has in the inbox menus: Sender → Signal, Sender → Noise, and Block Sender. Policies: - `signal`: the sender's future mail shows in the Signal view. Use for senders the user says are important. - `noise`: the sender's future mail shows in the Noise view. Mail still arrives and stays searchable. Use for newsletters, promos, and other low-value senders. - `block`: ALL future mail from the sender is sent straight to trash and never reaches the inbox. This is much stronger than noise. Only use it when the user explicitly asks to block a sender; when they just call mail unwanted or spammy, prefer `noise`. Policies are per inbox. When acting on a specific thread (e.g. after GetThread), pass `thread_id` so the policy applies to the inbox that owns that thread, which matters for delegated or secondary inboxes. Otherwise pass `inbox` (an inbox email address from ListInboxes) to name one, or omit both to use the primary inbox. Get `sender_email` from GetThread (`from.email`) or ListEntities (`sender_email`); do not guess addresses. Calling again with a different policy overwrites the previous one. Repeating a call with the same arguments is safe."+---++# SetSenderPolicy++Set where future mail from a sender lands in one of the user's inboxes. This is the same control a human has in the inbox menus: Sender → Signal, Sender → Noise, and Block Sender.++Policies:+- `signal`: the sender's future mail shows in the Signal view. Use for senders the user says are important.+- `noise`: the sender's future mail shows in the Noise view. Mail still arrives and stays searchable. Use for newsletters, promos, and other low-value senders.+- `block`: ALL future mail from the sender is sent straight to trash and never reaches the inbox. This is much stronger than noise. Only use it when the user explicitly asks to block a sender; when they just call mail unwanted or spammy, prefer `noise`.++Policies are per inbox. When acting on a specific thread (e.g. after GetThread), pass `thread_id` so the policy applies to the inbox that owns that thread, which matters for delegated or secondary inboxes. Otherwise pass `inbox` (an inbox email address from ListInboxes) to name one, or omit both to use the primary inbox.++Get `sender_email` from GetThread (`from.email`) or ListEntities (`sender_email`); do not guess addresses. Calling again with a different policy overwrites the previous one. Repeating a call with the same arguments is safe.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `sender_email` | string | Yes | The sender's email address, e.g. `from.email` on a GetThread message or `sender_email` on a ListEntities email row. Exact address, not a domain. |+| `policy` | `"signal"` \| `"noise"` \| `"block"` | Yes | Where future mail from this sender lands: `signal`, `noise`, or `block`. |+| `thread_id` | string | No | Apply the policy to the inbox that owns this thread (same UUID returned by ListEntities, search, or GetThread). Takes precedence over `inbox`. |+| `inbox` | string | No | Apply the policy to a specific inbox by its email address (from ListInboxes). Ignored when `thread_id` is set. Omit both to use the primary inbox. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex 287cdb672b..ed9cbfb6dd 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -61,6 +61,7 @@"AI/mcp/tools/send-channel-message","AI/mcp/tools/send-email","AI/mcp/tools/set-entity-property",+ "AI/mcp/tools/set-sender-policy","AI/mcp/tools/subagent","AI/mcp/tools/text-editor-code-execution","AI/mcp/tools/update-calendar-event",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 971f24359d..44f0e363f3 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -131,6 +131,7 @@"AI/mcp/tools/send-channel-message","AI/mcp/tools/send-email","AI/mcp/tools/set-entity-property",+ "AI/mcp/tools/set-sender-policy","AI/mcp/tools/subagent","AI/mcp/tools/text-editor-code-execution","AI/mcp/tools/update-calendar-event",diff --git a/apps/web/src/lib/core/component/AI/component/tool/SetSenderPolicy.tsx b/apps/web/src/lib/core/component/AI/component/tool/SetSenderPolicy.tsxnew file mode 100644index 0000000000..835c531ceb--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/SetSenderPolicy.tsx@@ -0,0 +1,58 @@+import Funnel from '@phosphor-icons/core/regular/funnel.svg';+import type { ToolSenderPolicy } from '@service-cognition/generated/tools/types';+import { createSignal } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++const POLICY_LABEL: Record<ToolSenderPolicy, string> = {+ signal: 'Sender → Signal',+ noise: 'Sender → Noise',+ block: 'Block Sender',+};++const POLICY_STATUS: Record<ToolSenderPolicy, string> = {+ signal: 'Signal',+ noise: 'Noise',+ block: 'Block',+};++const handler = createToolRenderer({+ name: 'SetSenderPolicy',+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const summary = () => ctx.response?.data.summary;+ const hasResults = () => Boolean(summary());+ const statusText = () => {+ if (!ctx.response) return undefined;+ return POLICY_STATUS[ctx.response.data.policy];+ };++ return (+ <BaseTool+ icon={Funnel}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <p class="text-xs text-ink">{summary()}</p>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ {POLICY_LABEL[ctx.tool.data.policy]}+ </span>+ <Tool.ResultToggle+ expanded={isExpanded()}+ onToggle={() => setIsExpanded((expanded) => !expanded)}+ showToggle={hasResults()}+ status={statusText()}+ />+ </div>+ </BaseTool>+ );+ },+});++export const setSenderPolicyHandler = handler;diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex bb89be582c..b6781a6bc8 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -78,6 +78,7 @@ import { searchToolsHandler } from './SearchTools';import { selfKnowledgeHandler } from './SelfKnowledge';import { sendChannelMessageHandler } from './SendChannelMessage';import { sendEmailHandler } from './SendEmail';+import { setSenderPolicyHandler } from './SetSenderPolicy';import { subagentHandler } from './Subagent';import { textEditorCodeExecutionHandler } from './TextEditorCodeExecution';import {@@ -152,6 +153,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {SelfKnowledge: selfKnowledgeHandler,SendChannelMessage: sendChannelMessageHandler,SendEmail: sendEmailHandler,+ SetSenderPolicy: setSenderPolicyHandler,SetEntityProperty: setEntityPropertyHandler,BulkSetEntityPropertyOptions: bulkSetEntityPropertyOptionsHandler,Subagent: subagentHandler,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex e76f1829d8..f94be2647a 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -4085,6 +4085,62 @@ export const SetEntityPropertyResponse = z.object({message: z.string(),});+export const SetSenderPolicy = z.object({+ sender_email: z.string(),+ policy: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('signal'),+ z.literal('noise'),+ z.literal('block'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ thread_id: z.union([z.string().uuid(), z.null()]).optional(),+ inbox: z.union([z.string(), z.null()]).optional(),+});++export const SetSenderPolicyResponse = z.object({+ senderEmail: z.string(),+ policy: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('signal'),+ z.literal('noise'),+ z.literal('block'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ inbox: z.string(),+ summary: z.string(),+});+export const Subagent = z.object({ task: z.string() });export const SubagentResponse = z.object({ result: z.string() });diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex d063332b8e..232dcc0018 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -192,6 +192,10 @@ type ToolParserMap = {call: types.SetEntityProperty;response: types.SetEntityPropertyResponse;};+ SetSenderPolicy: {+ call: types.SetSenderPolicy;+ response: types.SetSenderPolicyResponse;+ };Subagent: { call: types.Subagent; response: types.SubagentResponse };TextEditorCodeExecution: {call: types.TextEditorCodeExecution;@@ -422,6 +426,10 @@ const toolParserMap = {call: schemas.SetEntityProperty,response: schemas.SetEntityPropertyResponse,},+ SetSenderPolicy: {+ call: schemas.SetSenderPolicy,+ response: schemas.SetSenderPolicyResponse,+ },Subagent: { call: schemas.Subagent, response: schemas.SubagentResponse },TextEditorCodeExecution: {call: schemas.TextEditorCodeExecution,@@ -636,6 +644,10 @@ type ToolDataMap = {call: types.SetEntityProperty;response: types.SetEntityPropertyResponse;};+ SetSenderPolicy: {+ call: types.SetSenderPolicy;+ response: types.SetSenderPolicyResponse;+ };Subagent: { call: types.Subagent; response: types.SubagentResponse };TextEditorCodeExecution: {call: types.TextEditorCodeExecution;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 2db6bfd8ff..c795b56ec6 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -744,6 +744,10 @@ export type ToolEntityType =| 'call'| 'user'| 'company';+/**+ * Where future mail from this sender lands: `signal`, `noise`, or `block`.+ */+export type ToolSenderPolicy = 'signal' | 'noise' | 'block';/*** Content of a text editor code execution response - either a result or an error*/@@ -4920,6 +4924,52 @@ export interface SetEntityPropertyResponse {success: boolean;message: string;}+/**+ * Set where future mail from a sender lands in one of the user's inboxes. This is the same control a human has in the inbox menus: Sender → Signal, Sender → Noise, and Block Sender.+ *+ * Policies:+ * - `signal`: the sender's future mail shows in the Signal view. Use for senders the user says are important.+ * - `noise`: the sender's future mail shows in the Noise view. Mail still arrives and stays searchable. Use for newsletters, promos, and other low-value senders.+ * - `block`: ALL future mail from the sender is sent straight to trash and never reaches the inbox. This is much stronger than noise. Only use it when the user explicitly asks to block a sender; when they just call mail unwanted or spammy, prefer `noise`.+ *+ * Policies are per inbox. When acting on a specific thread (e.g. after GetThread), pass `thread_id` so the policy applies to the inbox that owns that thread, which matters for delegated or secondary inboxes. Otherwise pass `inbox` (an inbox email address from ListInboxes) to name one, or omit both to use the primary inbox.+ *+ * Get `sender_email` from GetThread (`from.email`) or ListEntities (`sender_email`); do not guess addresses. Calling again with a different policy overwrites the previous one. Repeating a call with the same arguments is safe.+ */+export interface SetSenderPolicy {+ /**+ * The sender's email address, e.g. `from.email` on a GetThread message or+ * `sender_email` on a ListEntities email row. Exact address, not a domain.+ */+ sender_email: string;+ policy: ToolSenderPolicy;+ /**+ * Apply the policy to the inbox that owns this thread (same UUID returned+ * by ListEntities, search, or GetThread). Takes precedence over `inbox`.+ */+ thread_id?: string | null;+ /**+ * Apply the policy to a specific inbox by its email address (from+ * ListInboxes). Ignored when `thread_id` is set. Omit both to use the+ * primary inbox.+ */+ inbox?: string | null;+}+export interface SetSenderPolicyResponse {+ /**+ * The sender the policy now applies to.+ */+ senderEmail: string;+ policy: ToolSenderPolicy;+ /**+ * The email address of the inbox the policy was applied to.+ */+ inbox: string;+ /**+ * A human-readable summary of the change.+ */+ summary: string;+}/*** Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, calls, and channel tools. Use this for tasks that require multiple tool calls or independent research.*/diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 69edc7aa22..1a9587b3a0 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -7,8 +7,9 @@ use email::domain::models::{AttachmentDraft, AttachmentForwarded, CreateDraftInput, CreatedDraft, EmailErr, EmailFilter,EmailSyncStatus, EmailThreadMetadata, EnrichedEmailThreadPreview, GetEmailsRequest,LabelListVisibility, LabelType, Link, LinkLabel, Message, MessageAttachment,- MessageListVisibility, ParsedMessage, ParsedThread, Thread, UpdateThreadLabelsResult,- UpsertEmailFilterInput, UserEmailLink, UserEmailLinkSettings, UserProvider,+ MessageListVisibility, ParsedMessage, ParsedThread, SenderPolicy, Thread,+ UpdateThreadLabelsResult, UpsertEmailFilterInput, UserEmailLink, UserEmailLinkSettings,+ UserProvider,};use entity_access::domain::models::{AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,@@ -419,6 +420,15 @@ impl EmailService for CountingEmailService {Err(test_email_err())}+ async fn set_sender_policy(+ &self,+ _link: &Link,+ _sender_email: &str,+ _policy: SenderPolicy,+ ) -> Result<(), EmailErr> {+ Err(test_email_err())+ }+async fn delete_email_filter(&self, _link: &Link, _filter_id: Uuid) -> Result<bool, EmailErr> {Err(test_email_err())}diff --git a/crates/email/src/domain/models/mod.rs b/crates/email/src/domain/models/mod.rsindex 11526d7308..156aa7d7aa 100644--- a/crates/email/src/domain/models/mod.rs+++ b/crates/email/src/domain/models/mod.rs@@ -8,6 +8,7 @@ pub mod link;pub mod message;pub mod parsed_message;pub mod preview;+pub mod sender_policy;pub mod thread;#[cfg(test)]@@ -35,4 +36,5 @@ pub use preview::{EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery,PreviewView, PreviewViewStandardLabel,};+pub use sender_policy::SenderPolicy;pub use thread::{EmailThreadMetadata, Thread, ThreadRow};diff --git a/crates/email/src/domain/models/sender_policy.rs b/crates/email/src/domain/models/sender_policy.rsnew file mode 100644index 0000000000..b89a8cc81e--- /dev/null+++ b/crates/email/src/domain/models/sender_policy.rs@@ -0,0 +1,7 @@+/// Where future mail from a sender lands for one inbox.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SenderPolicy {+ Signal,+ Noise,+ Block,+}diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex 4600ed05c4..5835a5107e 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -3,9 +3,9 @@ use crate::domain::models::{CreatedDraft, EmailErr, EmailFilter, EmailInboxDetails, EmailThreadMetadata,EmailThreadPreview, EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link, LinkLabel,Message, MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, ParsedMessage,- ParsedThread, PreviewCursorQuery, RecipientType, ResolvedDraftInput, SimpleMessage,- SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult, UpsertEmailFilterInput,- UpsertedContacts, UserEmailLink, UserProvider,+ ParsedThread, PreviewCursorQuery, RecipientType, ResolvedDraftInput, SenderPolicy,+ SimpleMessage, SimpleMessageInfo, Thread, ThreadRow, UpdateThreadLabelsResult,+ UpsertEmailFilterInput, UpsertedContacts, UserEmailLink, UserProvider,};use chrono::{DateTime, Utc};use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};@@ -38,6 +38,20 @@ pub trait EmailMessageEnqueuer: Send + Sync + 'static {labels_to_add: Vec<String>,labels_to_remove: Vec<String>,) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Enqueue a Gmail-ops BlockSender operation for the link.+ fn enqueue_gmail_ops_block_sender(+ &self,+ link_id: Uuid,+ email_address: String,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Enqueue a Gmail-ops UnblockSender operation for the link.+ fn enqueue_gmail_ops_unblock_sender(+ &self,+ link_id: Uuid,+ email_address: String,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;}/// The sending inbox's signature preferences, used by the send pipeline to@@ -591,6 +605,17 @@ pub trait EmailService: Send + Sync + 'static {input: UpsertEmailFilterInput,) -> impl Future<Output = Result<EmailFilter, EmailErr>> + Send;+ /// Set where future mail from a sender lands for the given inbox.+ ///+ /// Signal and Noise also enqueue an UnblockSender so a prior Block does+ /// not keep trashing new mail.+ fn set_sender_policy(+ &self,+ link: &Link,+ sender_email: &str,+ policy: SenderPolicy,+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;+/// Delete an email filter by its ID for the given link.fn delete_email_filter(&self,@@ -667,6 +692,22 @@ impl EmailMessageEnqueuer for NoOpEnqueuer {) -> Result<(), Self::Err> {Ok(())}++ async fn enqueue_gmail_ops_block_sender(+ &self,+ _link_id: Uuid,+ _email_address: String,+ ) -> Result<(), Self::Err> {+ Ok(())+ }++ async fn enqueue_gmail_ops_unblock_sender(+ &self,+ _link_id: Uuid,+ _email_address: String,+ ) -> Result<(), Self::Err> {+ Ok(())+ }}/// No-op [`EmailService`] for binaries that need to satisfy the bound but@@ -800,6 +841,15 @@ impl EmailService for NoOpEmailService {Err(no_op_email_err())}+ async fn set_sender_policy(+ &self,+ _link: &Link,+ _sender_email: &str,+ _policy: SenderPolicy,+ ) -> Result<(), EmailErr> {+ Err(no_op_email_err())+ }+async fn delete_email_filter(&self, _link: &Link, _filter_id: Uuid) -> Result<bool, EmailErr> {Err(no_op_email_err())}diff --git a/crates/email/src/domain/service.rs b/crates/email/src/domain/service.rsindex d47cfbd7f9..91d8bf007a 100644--- a/crates/email/src/domain/service.rs+++ b/crates/email/src/domain/service.rs@@ -17,7 +17,7 @@ use crate::domain::{models::{CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EmailThreadMetadata,EnrichedEmailThreadPreview, GetEmailsRequest, Link, LinkLabel, ParsedMessage, ParsedThread,- Thread, UpdateThreadLabelsResult, UpsertEmailFilterInput,+ SenderPolicy, Thread, UpdateThreadLabelsResult, UpsertEmailFilterInput,},ports::{EmailContentService, EmailMessageEnqueuer, EmailRepo, EmailService,@@ -122,29 +122,36 @@ impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B> {}}+pub(crate) const MAX_SENDER_ADDRESS_LEN: usize = 320;+impl<T, U, E, CS, Eam, B> EmailServiceImpl<T, U, E, CS, Eam, B> {+ pub(crate) fn validate_sender_address(addr: &str) -> Result<String, EmailErr> {+ let addr = addr.trim().to_lowercase();+ if addr.is_empty() {+ return Err(EmailErr::InvalidEmailFilter(+ "Email address cannot be empty".to_string(),+ ));+ }+ if !addr.contains('@') {+ return Err(EmailErr::InvalidEmailFilter(+ "Invalid email address format".to_string(),+ ));+ }+ if addr.len() > MAX_SENDER_ADDRESS_LEN {+ return Err(EmailErr::InvalidEmailFilter(+ "Email address is too long".to_string(),+ ));+ }+ Ok(addr)+ }+/// Validate and normalize email filter input.fn validate_email_filter_input(input: UpsertEmailFilterInput,) -> Result<UpsertEmailFilterInput, EmailErr> {match (&input.email_address, &input.email_domain) {(Some(addr), None) => {- let addr = addr.trim().to_lowercase();- if addr.is_empty() {- return Err(EmailErr::InvalidEmailFilter(- "Email address cannot be empty".to_string(),- ));- }- if !addr.contains('@') {- return Err(EmailErr::InvalidEmailFilter(- "Invalid email address format".to_string(),- ));- }- if addr.len() > 320 {- return Err(EmailErr::InvalidEmailFilter(- "Email address is too long".to_string(),- ));- }+ let addr = Self::validate_sender_address(addr)?;Ok(UpsertEmailFilterInput {email_address: Some(addr),email_domain: None,@@ -452,6 +459,41 @@ where.map_err(|e| EmailErr::RepoErr(e.into()))}+ #[tracing::instrument(skip(self, link), fields(link_id = %link.id), err)]+ async fn set_sender_policy(+ &self,+ link: &Link,+ sender_email: &str,+ policy: SenderPolicy,+ ) -> Result<(), EmailErr> {+ match policy {+ SenderPolicy::Signal | SenderPolicy::Noise => {+ let addr = Self::validate_sender_address(sender_email)?;+ self.enqueuer+ .enqueue_gmail_ops_unblock_sender(link.id, addr.clone())+ .await+ .map_err(|e| EmailErr::EnqueueErr(anyhow::Error::from(e)))?;+ self.upsert_email_filter(+ link,+ UpsertEmailFilterInput {+ email_address: Some(addr),+ email_domain: None,+ is_important: matches!(policy, SenderPolicy::Signal),+ },+ )+ .await?;+ Ok(())+ }+ SenderPolicy::Block => {+ let addr = Self::validate_sender_address(sender_email)?;+ self.enqueuer+ .enqueue_gmail_ops_block_sender(link.id, addr)+ .await+ .map_err(|e| EmailErr::EnqueueErr(anyhow::Error::from(e)))+ }+ }+ }+async fn delete_email_filter(&self, link: &Link, filter_id: Uuid) -> Result<bool, EmailErr> {self.email_repo.delete_email_filter(filter_id, link.id)diff --git a/crates/email/src/domain/service/test.rs b/crates/email/src/domain/service/test.rsindex 53838b61e7..5557c83e52 100644--- a/crates/email/src/domain/service/test.rs+++ b/crates/email/src/domain/service/test.rs@@ -1,4 +1,5 @@-use super::changed_project_ids;+use super::{EmailServiceImpl, MAX_SENDER_ADDRESS_LEN, changed_project_ids};+use crate::domain::models::EmailErr;#[test]fn changed_project_ids_include_old_and_new_projects() {@@ -31,3 +32,52 @@ fn changed_project_ids_ignore_empty_and_duplicate_ids() {assert!(changed_project_ids(Some(""), None).is_empty());assert!(changed_project_ids(Some("project"), Some("project")).is_empty());}++fn validate_sender_address(addr: &str) -> Result<String, EmailErr> {+ EmailServiceImpl::<(), (), (), (), (), ()>::validate_sender_address(addr)+}++#[test]+fn validate_sender_address_rejects_empty() {+ match validate_sender_address("") {+ Err(EmailErr::InvalidEmailFilter(msg)) => {+ assert_eq!(msg, "Email address cannot be empty");+ }+ other => panic!("expected InvalidEmailFilter, got {other:?}"),+ }+ match validate_sender_address(" ") {+ Err(EmailErr::InvalidEmailFilter(msg)) => {+ assert_eq!(msg, "Email address cannot be empty");+ }+ other => panic!("expected InvalidEmailFilter, got {other:?}"),+ }+}++#[test]+fn validate_sender_address_rejects_missing_at() {+ match validate_sender_address("not-an-email") {+ Err(EmailErr::InvalidEmailFilter(msg)) => {+ assert_eq!(msg, "Invalid email address format");+ }+ other => panic!("expected InvalidEmailFilter, got {other:?}"),+ }+}++#[test]+fn validate_sender_address_rejects_too_long() {+ let addr = format!("{}@example.com", "a".repeat(MAX_SENDER_ADDRESS_LEN));+ match validate_sender_address(&addr) {+ Err(EmailErr::InvalidEmailFilter(msg)) => {+ assert_eq!(msg, "Email address is too long");+ }+ other => panic!("expected InvalidEmailFilter, got {other:?}"),+ }+}++#[test]+fn validate_sender_address_trims_and_lowercases() {+ assert_eq!(+ validate_sender_address(" [email protected] ").unwrap(),+ );+}diff --git a/crates/email/src/inbound/toolset.rs b/crates/email/src/inbound/toolset.rsindex 4b1356f972..4b24569f14 100644--- a/crates/email/src/inbound/toolset.rs+++ b/crates/email/src/inbound/toolset.rs@@ -4,6 +4,7 @@ mod get_thread;mod list_inboxes;mod list_labels;mod send_email;+mod set_sender_policy;mod update_thread_labels;#[cfg(test)]@@ -22,6 +23,7 @@ pub use get_thread::{GetThread, GetThreadResponse};pub use list_inboxes::{ListInboxes, ListInboxesResponse, ToolInbox};pub use list_labels::{ListLabels, ListLabelsResponse, ToolLabel};pub use send_email::{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@@ -167,4 +169,5 @@ where.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>>()}diff --git a/crates/email/src/inbound/toolset/set_sender_policy.rs b/crates/email/src/inbound/toolset/set_sender_policy.rsnew file mode 100644index 0000000000..6dfb2a9be2--- /dev/null+++ b/crates/email/src/inbound/toolset/set_sender_policy.rs@@ -0,0 +1,179 @@+use crate::domain::{+ models::SenderPolicy,+ ports::{EmailService, GmailTokenProvider},+};+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use ai_toolset::{ToolAnnotated, ToolAnnotations};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::user_id::MacroUserIdStr;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::EmailToolContext;++/// Where future mail from this sender lands: `signal`, `noise`, or `block`.+#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ToolSenderPolicy {+ /// Future mail from the sender appears in the Signal view.+ Signal,+ /// Future mail from the sender appears in the Noise view.+ Noise,+ /// Future mail from the sender is sent straight to trash.+ Block,+}++#[derive(Debug, Deserialize, JsonSchema, Clone)]+#[schemars(+ title = "SetSenderPolicy",+ description = "\+Set where future mail from a sender lands in one of the user's inboxes. This is the \+same control a human has in the inbox menus: Sender → Signal, Sender → Noise, \+and Block Sender.\n\+\n\+Policies:\n\+- `signal`: the sender's future mail shows in the Signal view. Use for senders the \+user says are important.\n\+- `noise`: the sender's future mail shows in the Noise view. Mail still arrives and \+stays searchable. Use for newsletters, promos, and other low-value senders.\n\+- `block`: ALL future mail from the sender is sent straight to trash and never \+reaches the inbox. This is much stronger than noise. Only use it when the user \+explicitly asks to block a sender; when they just call mail unwanted or spammy, \+prefer `noise`.\n\+\n\+Policies are per inbox. When acting on a specific thread (e.g. after GetThread), \+pass `thread_id` so the policy applies to the inbox that owns that thread, which \+matters for delegated or secondary inboxes. Otherwise pass `inbox` (an inbox email \+address from ListInboxes) to name one, or omit both to use the primary inbox.\n\+\n\+Get `sender_email` from GetThread (`from.email`) or ListEntities (`sender_email`); \+do not guess addresses. Calling again with a different policy overwrites the \+previous one. Repeating a call with the same arguments is safe."+)]+/// Set where future mail from a sender lands in one inbox.+pub struct SetSenderPolicy {+ /// The sender's email address, e.g. `from.email` on a GetThread message or+ /// `sender_email` on a ListEntities email row. Exact address, not a domain.+ pub sender_email: String,+ /// Where future mail from this sender lands: `signal`, `noise`, or `block`.+ pub policy: ToolSenderPolicy,+ /// Apply the policy to the inbox that owns this thread (same UUID returned+ /// by ListEntities, search, or GetThread). Takes precedence over `inbox`.+ #[serde(default)]+ pub thread_id: Option<Uuid>,+ /// Apply the policy to a specific inbox by its email address (from+ /// ListInboxes). Ignored when `thread_id` is set. Omit both to use the+ /// primary inbox.+ #[serde(default)]+ pub inbox: Option<String>,+}++#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct SetSenderPolicyResponse {+ /// The sender the policy now applies to.+ pub sender_email: String,+ /// The policy that was applied.+ pub policy: ToolSenderPolicy,+ /// The email address of the inbox the policy was applied to.+ pub inbox: String,+ /// A human-readable summary of the change.+ pub summary: String,+}++impl ToolAnnotated for SetSenderPolicy {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Set sender policy").with_idempotent();+}++#[async_trait]+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for SetSenderPolicy+where+ T: EmailService,+ G: GmailTokenProvider,+ E: EntityAccessService,+{+ type Output = SetSenderPolicyResponse;++ #[tracing::instrument(skip_all, fields(+ user_id=?request_context.user_id,+ sender_email=%self.sender_email,+ policy=?self.policy,+ ), err)]+ async fn call(+ &self,+ service_context: ServiceContext<EmailToolContext<T, G, E>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("Set sender policy");++ let link = match self.thread_id {+ Some(thread_id) => service_context+ .service+ .get_owned_link_for_thread(+ MacroUserIdStr((*request_context.user_id).clone()),+ thread_id,+ )+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to resolve inbox for thread: {e}"),+ internal_error: e.into(),+ })?+ .ok_or_else(|| ToolCallError {+ description: "No accessible inbox owns this thread.".to_string(),+ internal_error: anyhow::anyhow!("no owned link for thread"),+ })?,+ None => {+ let inboxes = service_context+ .service+ .get_inboxes_for_macro_id(MacroUserIdStr((*request_context.user_id).clone()))+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to resolve inboxes: {e}"),+ internal_error: e.into(),+ })?;+ let caller_macro_id = request_context.user_id.to_string();+ super::resolve_inbox_selector(&inboxes, &caller_macro_id, self.inbox.as_deref())?+ .clone()+ }+ };++ let policy = match self.policy {+ ToolSenderPolicy::Signal => SenderPolicy::Signal,+ ToolSenderPolicy::Noise => SenderPolicy::Noise,+ ToolSenderPolicy::Block => SenderPolicy::Block,+ };++ service_context+ .service+ .set_sender_policy(&link, &self.sender_email, policy)+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to set sender policy: {e}"),+ internal_error: e.into(),+ })?;++ let sender_email = self.sender_email.trim().to_lowercase();+ let inbox = link.email_address.0.as_ref().to_string();+ let summary = match self.policy {+ ToolSenderPolicy::Signal => {+ format!("Messages from {sender_email} will now appear in Signal for {inbox}.")+ }+ ToolSenderPolicy::Noise => {+ format!("Messages from {sender_email} will now appear in Noise for {inbox}.")+ }+ ToolSenderPolicy::Block => {+ format!("All new messages from {sender_email} will be trashed for {inbox}.")+ }+ };++ Ok(SetSenderPolicyResponse {+ sender_email,+ policy: self.policy,+ inbox,+ summary,+ })+ }+}diff --git a/crates/email/src/inbound/toolset/test.rs b/crates/email/src/inbound/toolset/test.rsindex 0dc950ea05..2423bdc247 100644--- a/crates/email/src/inbound/toolset/test.rs+++ b/crates/email/src/inbound/toolset/test.rs@@ -139,6 +139,39 @@ fn resolve_inbox_selector_matches_address_case_insensitively() {assert_eq!(link.email_address.0.as_ref(), "[email protected]");}+#[test]+fn test_set_sender_policy_schema_validation() {+ let result = generate_validated_input_schema::<SetSenderPolicy>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(+ validated.name, "SetSenderPolicy",+ "Tool name should match the schemars title"+ );+ assert!(+ validated.description.contains("block"),+ "Description should contain expected text"+ );+}++#[test]+fn tool_sender_policy_deserializes_snake_case_values() {+ assert_eq!(+ serde_json::from_str::<ToolSenderPolicy>("\"signal\"").unwrap(),+ ToolSenderPolicy::Signal+ );+ assert_eq!(+ serde_json::from_str::<ToolSenderPolicy>("\"noise\"").unwrap(),+ ToolSenderPolicy::Noise+ );+ assert_eq!(+ serde_json::from_str::<ToolSenderPolicy>("\"block\"").unwrap(),+ ToolSenderPolicy::Block+ );+ assert!(serde_json::from_str::<ToolSenderPolicy>("\"unknown\"").is_err());+}+#[test]fn resolve_inbox_selector_rejects_unknown_address() {let inboxes = vec![make_link("macro|[email protected]", "[email protected]", true)];diff --git a/crates/soup/src/inbound/axum_router/tests.rs b/crates/soup/src/inbound/axum_router/tests.rsindex 726b516a60..7cd04eea07 100644--- a/crates/soup/src/inbound/axum_router/tests.rs+++ b/crates/soup/src/inbound/axum_router/tests.rs@@ -342,6 +342,15 @@ impl EmailService for MockEmail {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}+ async fn set_sender_policy(+ &self,+ _link: &email::domain::models::Link,+ _sender_email: &str,+ _policy: email::domain::models::SenderPolicy,+ ) -> Result<(), EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }+async fn delete_email_filter(&self,_link: &email::domain::models::Link,@@ -765,6 +774,15 @@ impl EmailService for MockEmailLinkResult {Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))}+ async fn set_sender_policy(+ &self,+ _link: &email::domain::models::Link,+ _sender_email: &str,+ _policy: email::domain::models::SenderPolicy,+ ) -> Result<(), EmailErr> {+ Err(EmailErr::RepoErr(anyhow::anyhow!("Not implemented")))+ }+async fn delete_email_filter(&self,_link: &email::domain::models::Link,diff --git a/crates/sqs_client/src/email.rs b/crates/sqs_client/src/email.rsindex 38adcf04f2..2b9df57aa2 100644--- a/crates/sqs_client/src/email.rs+++ b/crates/sqs_client/src/email.rs@@ -176,6 +176,40 @@ impl EmailMessageEnqueuer for SQS {self.enqueue_gmail_ops_notifications_batch(gmail_ops_messages).await}++ #[tracing::instrument(skip(self, email_address), err)]+ async fn enqueue_gmail_ops_block_sender(+ &self,+ link_id: Uuid,+ email_address: String,+ ) -> Result<(), Self::Err> {+ use models_email::gmail::gmail_ops::{+ BlockSenderPayload, GmailOpsOperation, GmailOpsPubsubMessage,+ };++ self.enqueue_gmail_ops_notification(GmailOpsPubsubMessage {+ link_id,+ operation: GmailOpsOperation::BlockSender(BlockSenderPayload { email_address }),+ })+ .await+ }++ #[tracing::instrument(skip(self, email_address), err)]+ async fn enqueue_gmail_ops_unblock_sender(+ &self,+ link_id: Uuid,+ email_address: String,+ ) -> Result<(), Self::Err> {+ use models_email::gmail::gmail_ops::{+ GmailOpsOperation, GmailOpsPubsubMessage, UnblockSenderPayload,+ };++ self.enqueue_gmail_ops_notification(GmailOpsPubsubMessage {+ link_id,+ operation: GmailOpsOperation::UnblockSender(UnblockSenderPayload { email_address }),+ })+ .await+ }}#[tracing::instrument(skip(sqs_client))]