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): scope AI email tools to a specific inbox in multi-inbox setups (#4304)
gbirmanc0123cbf4340
diff --git a/js/app/packages/core/component/AI/component/tool/ListInboxes.tsx b/js/app/packages/core/component/AI/component/tool/ListInboxes.tsxnew file mode 100644index 0000000000..aa7bf87eac--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/ListInboxes.tsx@@ -0,0 +1,74 @@+import Tray from '@phosphor-icons/core/regular/tray.svg';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import { createSignal, For } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type ListInboxesItem = NamedTool<+ 'ListInboxes',+ 'response'+>['data']['inboxes'][number];++const inboxLabel = (inbox: ListInboxesItem): string => {+ if (inbox.isPrimary) return 'Primary';+ if (inbox.isDelegated) return 'Delegated';+ return 'Connected';+};++const ListInboxesToolResponse = (props: { inboxes: ListInboxesItem[] }) => (+ <Tool.List>+ <For each={props.inboxes}>+ {(inbox) => (+ <Tool.ListItem icon={<Tray class="size-4" />}>+ <div class="flex min-w-0 items-center justify-between gap-2">+ <span class="truncate text-xs text-ink">{inbox.emailAddress}</span>+ <span class="shrink-0 text-xs text-ink-extra-muted">+ {inboxLabel(inbox)}+ </span>+ </div>+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+);++const handler = createToolRenderer({+ name: 'ListInboxes',+ render: (ctx) => {+ const [isExpanded, setIsExpanded] = createSignal(false);+ const inboxes = () => ctx.response?.data.inboxes ?? [];+ const hasResults = () => inboxes().length > 0;+ const statusText = () => {+ if (!ctx.response) return undefined;+ const count = inboxes().length;+ if (count === 0) return 'No inboxes';+ return count === 1 ? '1 inbox' : `${count} inboxes`;+ };++ return (+ <BaseTool+ icon={Tray}+ renderContext={ctx.renderContext}+ type="call"+ response={+ hasResults() && isExpanded() ? (+ <ListInboxesToolResponse inboxes={inboxes()} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">List inboxes</span>+ <Tool.ResultToggle+ expanded={isExpanded()}+ onToggle={() => setIsExpanded((expanded) => !expanded)}+ showToggle={hasResults()}+ status={statusText()}+ />+ </div>+ </BaseTool>+ );+ },+});++export const listInboxesHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex 1971dee2e4..b8b5f9b8ea 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -10,6 +10,7 @@ import { displayResultsHandler } from './DisplayResults';import { getThreadHandler } from './GetThread';import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';+import { listInboxesHandler } from './ListInboxes';import { listLabelsHandler } from './ListLabels';import { listTeamMembersHandler } from './ListTeamMembers';import { loadToolsHandler } from './LoadTools';@@ -53,6 +54,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {GetEntityProperties: getEntityPropertiesHandler,ListCallRecords: listCallRecordsHandler,ListEntities: listEntitiesHandler,+ ListInboxes: listInboxesHandler,ListLabels: listLabelsHandler,ListNotifications: listNotificationsHandler,ListTeamMembers: listTeamMembersHandler,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 36bdbfb8e8..055705516e 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -84,6 +84,7 @@ export const ContentSearch = z.object({])).default([]),+ inbox: z.union([z.string(), z.null()]).default(null),query: z.string(),});@@ -586,6 +587,7 @@ export const ListEntities = z.object({emailPreset: z.union([z.literal('signal'), z.null()]).optional(),emailView: z.union([z.string(), z.null()]).default(null),fef: z.any().default(null),+ inbox: z.union([z.string(), z.null()]).default(null),includeTypes: z.union([z.array(@@ -717,7 +719,23 @@ export const ListEntitiesResponse = z.object({summary: z.string(),});-export const ListLabels = z.record(z.any());+export const ListInboxes = z.record(z.any());++export const ListInboxesResponse = z.object({+ inboxes: z.array(+ z.object({+ emailAddress: z.string(),+ isDelegated: z.boolean(),+ isPrimary: z.boolean(),+ })+ ),+ summary: z.string(),+});++export const ListLabels = z.object({+ inbox: z.union([z.string(), z.null()]).default(null),+ thread_id: z.union([z.string().uuid(), z.null()]).default(null),+});export const ListLabelsResponse = z.object({labels: z.array(@@ -829,6 +847,7 @@ export const NameSearch = z.object({])).default([]),+ inbox: z.union([z.string(), z.null()]).default(null),name: z.string(),});diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex bdc90bd556..29d0e7ac16 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -37,6 +37,7 @@ type ToolParserMap = {call: types.ListEntities;response: types.ListEntitiesResponse;};+ ListInboxes: { call: types.ListInboxes; response: types.ListInboxesResponse };ListLabels: { call: types.ListLabels; response: types.ListLabelsResponse };ListNotifications: {call: types.ListNotifications;@@ -132,6 +133,10 @@ const toolParserMap = {call: schemas.ListEntities,response: schemas.ListEntitiesResponse,},+ ListInboxes: {+ call: schemas.ListInboxes,+ response: schemas.ListInboxesResponse,+ },ListLabels: {call: schemas.ListLabels,response: schemas.ListLabelsResponse,@@ -247,6 +252,7 @@ type ToolDataMap = {call: types.ListEntities;response: types.ListEntitiesResponse;};+ ListInboxes: { call: types.ListInboxes; response: types.ListInboxesResponse };ListLabels: { call: types.ListLabels; response: types.ListLabelsResponse };ListNotifications: {call: types.ListNotifications;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 45a1a028c9..5f6ff70bee 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -854,6 +854,10 @@ export interface ContentSearch {* Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records'].*/entityTypes?: UnifiedSearchIndex[];+ /**+ * Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results.+ */+ inbox?: string | null;/*** The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a term in double quotes to force exact-token (or full-email-address) matching.*/@@ -1414,6 +1418,10 @@ export interface ListEntities {fef?: {[k: string]: unknown;};+ /**+ * Restrict email results to a single connected inbox, given as that inbox's email address. Omit to span every inbox the user can access (their own plus any delegated to them). Only set this when the user scopes the request to a specific mailbox (e.g. "my work inbox", "the shared inbox"); call ListInboxes first to get the exact address. Only affects email results.+ */+ inbox?: string | null;/*** Filter returned items to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails. Macro tasks are returned as document items, so use includeTypes=["document"] with df subtype task for task requests. This is folded into the AST and applied as part of cursor-level filtering.*/@@ -1449,6 +1457,45 @@ export interface ListEntitiesResponse {*/summary: string;}+/**+ * List the email inboxes the user can read or act on. Returns the caller's primary inbox, any other inboxes they have connected, and any inboxes delegated to them by teammates. Each entry has an `emailAddress`, `isPrimary` (the default inbox used when no inbox is specified), and `isDelegated` (true when the inbox belongs to another user).+ *+ * Use this when the user references a specific or non-default mailbox (e.g. "my work inbox", "the shared inbox", "the inbox Alex shared with me") so you can pass the exact `emailAddress` to the `inbox` parameter of ListEntities, ContentSearch, or NameSearch, or to ListLabels. Most users have a single inbox, in which case email tools operate on it by default and you do not need this tool. Do not guess inbox addresses — list them here first.+ */+export type ListInboxes = {};+/**+ * Response from the ListInboxes tool.+ */+export interface ListInboxesResponse {+ /**+ * The inboxes the caller can read or act on.+ */+ inboxes: ToolInbox[];+ /**+ * A human-readable summary of the inboxes.+ */+ summary: string;+}+/**+ * A connected inbox surfaced to the AI.+ */+export interface ToolInbox {+ /**+ * The inbox's email address. Pass this as the `inbox` parameter to scope+ * reads, searches, or label lookups to this inbox.+ */+ emailAddress: string;+ /**+ * Whether this inbox belongs to another user and was delegated to the+ * caller (versus one of the caller's own connected inboxes).+ */+ isDelegated: boolean;+ /**+ * Whether this is the caller's primary (default) inbox — the one email+ * tools use when no inbox is specified.+ */+ isPrimary: boolean;+}/*** List the user's Gmail labels. Returns both system labels (INBOX, SENT, DRAFTS, UNREAD, STARRED, TRASH, SPAM, IMPORTANT, CATEGORY_PERSONAL, CATEGORY_SOCIAL, CATEGORY_PROMOTIONS, CATEGORY_UPDATES, CATEGORY_FORUMS, etc.) and any custom user-created labels. Each label has a UUID `id` and a `name`.*@@ -1464,8 +1511,22 @@ export interface ListEntitiesResponse {* - Apply or remove a custom user label → look up the label by its display name and add/remove it** Match label names case-insensitively when searching the response. You can also use this to understand how the user's mail is organized before filtering or searching by label.+ *+ * Labels are per-inbox: each inbox has its own label `id`s, so a label id from one inbox will not work on a thread in another. When acting on a specific thread, pass its `thread_id` and this returns the labels of the inbox that owns that thread (the matching ids to pass to UpdateThreadLabels). Otherwise, in a multi-inbox setup, pass `inbox` (an inbox email address from ListInboxes) to list a specific inbox's labels; omit both to use the primary inbox.*/-export type ListLabels = {};+export interface ListLabels {+ /**+ * Restrict to a specific inbox by its email address (from ListInboxes).+ * Omit to use the primary inbox. Ignored when `thread_id` is set.+ */+ inbox?: string | null;+ /**+ * List the labels of the inbox that owns this thread. Use this when you+ * intend to add or remove a label on a specific thread so the label ids+ * match that thread's inbox. Takes precedence over `inbox`.+ */+ thread_id?: string | null;+}/*** Response from the ListLabels tool.*/@@ -1712,6 +1773,10 @@ export interface NameSearch {* Which types of items to search. Leave empty (the default) to search all types — this is almost always what you want. Only set this when the user's request clearly targets one or more specific types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records'].*/entityTypes?: UnifiedSearchIndex[];+ /**+ * Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results.+ */+ inbox?: string | null;/*** The name or title to search. Pass 1-3 keywords drawn from words that would literally appear in the title, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched against the subject. Wrap a term in double quotes to force exact-token matching.*/diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 20d54902d0..622cfdd681 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -2,7 +2,9 @@ use super::context::SearchToolContext;use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};+use macro_user_id::user_id::MacroUserIdStr;use models_search::{MatchType,unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},@@ -27,6 +29,12 @@ pub struct ContentSearch {)]#[serde(default)]pub entity_types: Vec<UnifiedSearchIndex>,++ #[schemars(+ description = "Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results."+ )]+ #[serde(default)]+ pub inbox: Option<String>,}#[async_trait]@@ -48,11 +56,34 @@ impl AsyncTool<SearchToolContext> for ContentSearch {});}+ let mut email_filters = EmailFilters {+ importance: Some(true),+ ..Default::default()+ };+ if let Some(inbox) = self+ .inbox+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ let inboxes = search_context+ .email_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();+ let link = email::inbound::toolset::resolve_inbox_selector(+ &inboxes,+ &caller_macro_id,+ Some(inbox),+ )?;+ email_filters.link_ids = vec![link.id.to_string()];+ }let base_filters = EntityFilters {- email_filters: EmailFilters {- importance: Some(true),- ..Default::default()- },+ email_filters,..Default::default()};let search_request = UnifiedSearchRequest {diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/context.rs b/rust/cloud-storage/ai_tools/src/search/search_service/context.rsindex 1e9c98b795..264e8a0409 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/context.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/context.rs@@ -1,4 +1,4 @@-use crate::tool_context::ToolServiceContext;+use crate::tool_context::{ToolEmailService, ToolServiceContext};use ai_usage::AiFeature;use axum::extract::FromRef;use search_service_client::SearchServiceClient;@@ -14,6 +14,9 @@ use uuid::Uuid;pub struct SearchToolContext {/// Client used to perform the unified search.pub search_client: Arc<SearchServiceClient>,+ /// Email service used to resolve an `inbox` selector to a link id when a+ /// search is scoped to a single inbox.+ pub email_service: Arc<ToolEmailService>,/// Entity id of the chat this request belongs to, when the request is an/// interactive chat session. `None` for every other feature, in which case/// nothing is excluded.@@ -31,6 +34,7 @@ impl FromRef<ToolServiceContext> for SearchToolContext {.flatten();SearchToolContext {search_client: ctx.search_service_client.clone(),+ email_service: ctx.email_service.clone(),self_chat_id,}}diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex f3e8cc0049..657a7a7ba9 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -2,7 +2,9 @@ use super::context::SearchToolContext;use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use email::domain::ports::EmailService;use item_filters::{EmailFilters, EntityFilters};+use macro_user_id::user_id::MacroUserIdStr;use models_search::{MatchType,unified::{UnifiedSearchIndex, UnifiedSearchRequest, entity_filters_from_include},@@ -27,6 +29,12 @@ pub struct NameSearch {)]#[serde(default)]pub entity_types: Vec<UnifiedSearchIndex>,++ #[schemars(+ description = "Restrict email results to a single connected inbox, given as that inbox's email address (from ListInboxes). Omit to search every inbox the user can access. Only set this when the user scopes the request to a specific mailbox. Only affects email results."+ )]+ #[serde(default)]+ pub inbox: Option<String>,}#[async_trait]@@ -48,11 +56,34 @@ impl AsyncTool<SearchToolContext> for NameSearch {});}+ let mut email_filters = EmailFilters {+ importance: Some(true),+ ..Default::default()+ };+ if let Some(inbox) = self+ .inbox+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ let inboxes = search_context+ .email_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();+ let link = email::inbound::toolset::resolve_inbox_selector(+ &inboxes,+ &caller_macro_id,+ Some(inbox),+ )?;+ email_filters.link_ids = vec![link.id.to_string()];+ }let base_filters = EntityFilters {- email_filters: EmailFilters {- importance: Some(true),- ..Default::default()- },+ email_filters,..Default::default()};let search_request = UnifiedSearchRequest {diff --git a/rust/cloud-storage/email/src/inbound/toolset/list_inboxes.rs b/rust/cloud-storage/email/src/inbound/toolset/list_inboxes.rsnew file mode 100644index 0000000000..3f4e51f938--- /dev/null+++ b/rust/cloud-storage/email/src/inbound/toolset/list_inboxes.rs@@ -0,0 +1,127 @@+//! ListInboxes tool for enumerating the inboxes a user can read or act on.++use crate::domain::ports::{EmailService, GmailTokenProvider};+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+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 super::EmailToolContext;++/// A connected inbox surfaced to the AI.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolInbox {+ /// The inbox's email address. Pass this as the `inbox` parameter to scope+ /// reads, searches, or label lookups to this inbox.+ pub email_address: String,+ /// Whether this is the caller's primary (default) inbox — the one email+ /// tools use when no inbox is specified.+ pub is_primary: bool,+ /// Whether this inbox belongs to another user and was delegated to the+ /// caller (versus one of the caller's own connected inboxes).+ pub is_delegated: bool,+}++/// Response from the ListInboxes tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListInboxesResponse {+ /// The inboxes the caller can read or act on.+ pub inboxes: Vec<ToolInbox>,+ /// A human-readable summary of the inboxes.+ pub summary: String,+}++/// List the email inboxes the user can access.+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]+#[schemars(+ title = "ListInboxes",+ description = "\+List the email inboxes the user can read or act on. Returns the caller's primary inbox, any \+other inboxes they have connected, and any inboxes delegated to them by teammates. Each entry \+has an `emailAddress`, `isPrimary` (the default inbox used when no inbox is specified), and \+`isDelegated` (true when the inbox belongs to another user).\n\+\n\+Use this when the user references a specific or non-default mailbox (e.g. \"my work inbox\", \+\"the shared inbox\", \"the inbox Alex shared with me\") so you can pass the exact \+`emailAddress` to the `inbox` parameter of ListEntities, ContentSearch, or NameSearch, or to \+ListLabels. Most users have a single inbox, in which case email tools operate on it by default \+and you do not need this tool. Do not guess inbox addresses — list them here first."+)]+pub struct ListInboxes {}++#[async_trait]+impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for ListInboxes+where+ T: EmailService,+ G: GmailTokenProvider,+ E: EntityAccessService,+{+ type Output = ListInboxesResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<EmailToolContext<T, G, E>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("List inboxes");++ 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 list inboxes: {e}"),+ internal_error: e.into(),+ })?;++ let caller_macro_id = request_context.user_id.to_string();+ let tool_inboxes: Vec<ToolInbox> = inboxes+ .iter()+ .map(|link| {+ let owned = link.macro_id.to_string() == caller_macro_id;+ ToolInbox {+ email_address: link.email_address.0.as_ref().to_string(),+ is_primary: owned && link.is_primary,+ is_delegated: !owned,+ }+ })+ .collect();++ let summary = build_summary(&tool_inboxes);++ Ok(ListInboxesResponse {+ inboxes: tool_inboxes,+ summary,+ })+ }+}++fn build_summary(inboxes: &[ToolInbox]) -> String {+ if inboxes.is_empty() {+ return "No email inboxes are connected.".to_string();+ }++ let delegated = inboxes.iter().filter(|i| i.is_delegated).count();+ let own = inboxes.len() - delegated;++ let mut parts = Vec::new();+ if own > 0 {+ parts.push(format!(+ "{own} connected inbox{}",+ if own == 1 { "" } else { "es" }+ ));+ }+ if delegated > 0 {+ parts.push(format!(+ "{delegated} delegated inbox{}",+ if delegated == 1 { "" } else { "es" }+ ));+ }++ format!("Found {}.", parts.join(" and "))+}diff --git a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rsindex 8260f3a5a0..8edefc4d10 100644--- a/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs+++ b/rust/cloud-storage/email/src/inbound/toolset/list_labels.rs@@ -76,11 +76,26 @@ named system label here, then call UpdateThreadLabels with that id):\n\- Apply or remove a custom user label → look up the label by its display name and add/remove it\n\\n\Match label names case-insensitively when searching the response. You can also use this to \-understand how the user's mail is organized before filtering or searching by label."+understand how the user's mail is organized before filtering or searching by label.\n\+\n\+Labels are per-inbox: each inbox has its own label `id`s, so a label id from one inbox will \+not work on a thread in another. When acting on a specific thread, pass its `thread_id` and \+this returns the labels of the inbox that owns that thread (the matching ids to pass to \+UpdateThreadLabels). Otherwise, in a multi-inbox setup, pass `inbox` (an inbox email address \+from ListInboxes) to list a specific inbox's labels; omit both to use the primary inbox.")]-#[allow(unused)]-// empty structs can't be deserialized;-pub struct ListLabels {}+pub struct ListLabels {+ /// List the labels of the inbox that owns this thread. Use this when you+ /// intend to add or remove a label on a specific thread so the label ids+ /// match that thread's inbox. Takes precedence over `inbox`.+ #[serde(default)]+ pub thread_id: Option<Uuid>,++ /// Restrict to a specific inbox by its email address (from ListInboxes).+ /// Omit to use the primary inbox. Ignored when `thread_id` is set.+ #[serde(default)]+ pub inbox: Option<String>,+}#[async_trait]impl<T, G, E> AsyncTool<EmailToolContext<T, G, E>> for ListLabels@@ -99,9 +114,36 @@ where) -> ToolResult<Self::Output> {tracing::info!("List labels");- let link = service_context- .resolve_link(MacroUserIdStr((*request_context.user_id).clone()))- .await?;+ 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 labels = service_context.servicediff --git a/rust/cloud-storage/email/src/inbound/toolset/mod.rs b/rust/cloud-storage/email/src/inbound/toolset/mod.rsindex a7d15acb62..4b1356f972 100644--- a/rust/cloud-storage/email/src/inbound/toolset/mod.rs+++ b/rust/cloud-storage/email/src/inbound/toolset/mod.rs@@ -1,6 +1,7 @@//! Toolset inbound adapter for the Email service.mod get_thread;+mod list_inboxes;mod list_labels;mod send_email;mod update_thread_labels;@@ -18,10 +19,65 @@ 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_email::{SendEmail, SendEmailResponse};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,@@ -110,4 +166,5 @@ where.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>>()}diff --git a/rust/cloud-storage/email/src/inbound/toolset/test.rs b/rust/cloud-storage/email/src/inbound/toolset/test.rsindex 784a10c99f..0dc950ea05 100644--- a/rust/cloud-storage/email/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/email/src/inbound/toolset/test.rs@@ -1,6 +1,23 @@use super::list_labels::build_summary;use super::*;+use crate::domain::models::UserProvider;use ai_toolset::schema::generate_validated_input_schema;+use chrono::Utc;+use macro_user_id::email::EmailStr;++fn make_link(macro_id: &'static str, email: &'static str, is_primary: bool) -> Link {+ Link {+ id: uuid::Uuid::new_v4(),+ macro_id: MacroUserIdStr::parse_from_str(macro_id).unwrap(),+ fusionauth_user_id: "fa-user".to_string(),+ email_address: EmailStr::parse_from_str(email).unwrap(),+ provider: UserProvider::Gmail,+ is_sync_active: true,+ is_primary,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ }+}#[test]fn test_build_summary_empty() {@@ -81,3 +98,57 @@ fn test_get_thread_schema_validation() {"Description should contain expected text");}++#[test]+fn test_list_inboxes_schema_validation() {+ let result = generate_validated_input_schema::<ListInboxes>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(+ validated.name, "ListInboxes",+ "Tool name should match the schemars title"+ );+ assert!(+ validated.description.contains("inbox"),+ "Description should contain expected text"+ );+}++#[test]+fn resolve_inbox_selector_defaults_to_caller_primary() {+ // The delegated inbox is primary for its own account but must not be chosen+ // as the caller's default — only is_primary AND owned by the caller counts.+ let inboxes = vec![+ make_link("macro|[email protected]", "[email protected]", true),+ make_link("macro|[email protected]", "[email protected]", false),+ make_link("macro|[email protected]", "[email protected]", true),+ ];+ let link = resolve_inbox_selector(&inboxes, "macro|[email protected]", None).unwrap();+ assert_eq!(link.email_address.0.as_ref(), "[email protected]");+}++#[test]+fn resolve_inbox_selector_matches_address_case_insensitively() {+ let inboxes = vec![+ make_link("macro|[email protected]", "[email protected]", true),+ make_link("macro|[email protected]", "[email protected]", true),+ ];+ let link = resolve_inbox_selector(&inboxes, "macro|[email protected]", Some("[email protected]"))+ .unwrap();+ assert_eq!(link.email_address.0.as_ref(), "[email protected]");+}++#[test]+fn resolve_inbox_selector_rejects_unknown_address() {+ let inboxes = vec![make_link("macro|[email protected]", "[email protected]", true)];+ // Avoid `unwrap_err` so the test does not require `Link: Debug`.+ let err = resolve_inbox_selector(&inboxes, "macro|[email protected]", Some("[email protected]"))+ .err()+ .expect("unknown inbox address should error");+ assert!(+ err.description.contains("No connected inbox matches"),+ "{}",+ err.description+ );+}diff --git a/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rsindex f228952869..13f1d90863 100644--- a/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs+++ b/rust/cloud-storage/email/src/inbound/toolset/update_thread_labels.rs@@ -83,9 +83,24 @@ where) -> ToolResult<Self::Output> {tracing::info!("Update thread labels");+ // Resolve the inbox from the thread itself rather than defaulting to the+ // caller's primary inbox, so label operations work on threads that live+ // in a delegated or secondary inbox.let link = service_context- .resolve_link(MacroUserIdStr((*request_context.user_id).clone()))- .await?;+ .service+ .get_owned_link_for_thread(+ MacroUserIdStr((*request_context.user_id).clone()),+ self.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"),+ })?;let access_token = service_context.resolve_access_token(&link).await?;diff --git a/rust/cloud-storage/prompt/src/email.rs b/rust/cloud-storage/prompt/src/email.rsnew file mode 100644index 0000000000..43e85036c3--- /dev/null+++ b/rust/cloud-storage/prompt/src/email.rs@@ -0,0 +1,45 @@+//! Email inbox behavior, including how the email tools handle multi-inbox setups.++use crate::types::StaticPrompt;++static TITLE: &str = "Email Inboxes";++static INSTRUCTIONS: &str = r##"## Email inboxes++- A user can have more than one email inbox: their own primary inbox, additional inboxes they+ have connected, and inboxes that teammates have delegated to them.+- By default — when you don't pass an `inbox` — reads and searches (`ListEntities`, `ContentSearch`,+ `NameSearch`) span ALL the inboxes the user can access, and per-thread actions use whichever inbox+ owns the thread. Pass an `inbox` only to narrow to a single mailbox. Most users have a single+ inbox, so for them this never matters — just use the email tools normally.++## Working across multiple inboxes++- When the user refers to a specific or non-default mailbox — e.g. "my work inbox", "the shared+ inbox", "the inbox Sam shared with me", or "search only my personal email" — call `ListInboxes`+ first to see the inboxes they can access. Each entry has an `emailAddress`, `isPrimary` (the+ default inbox), and `isDelegated` (true when it belongs to another user).+- Then pass the exact `emailAddress` as the `inbox` parameter:+ - `ListEntities`, `ContentSearch`, and `NameSearch` accept `inbox` to restrict email results to+ that one inbox. Omit `inbox` to span every inbox the user can access (this is the default).+ - Never guess an inbox address — get it from `ListInboxes`.++## Labels and per-thread actions++- Labels are per-inbox: each inbox has its own label `id`s, and a label id from one inbox does+ not work on a thread in another inbox.+- To add or remove a label on a specific thread, call `ListLabels` with that thread's `thread_id`+ to get the label ids for the inbox that owns the thread, then call `UpdateThreadLabels` with the+ same `thread_id`. `UpdateThreadLabels` figures out the right inbox from the thread automatically —+ you do not need to know or pass the inbox for it.+- Only pass `inbox` to `ListLabels` when the user asks about a specific inbox's labels in the+ abstract (not tied to a thread); otherwise prefer `thread_id`, or omit both for the primary inbox.+"##;++static INTENT: &str = "The model treats the primary inbox as the default for email tools, uses \+ListInboxes to discover other connected or delegated inboxes when the user references a \+non-default mailbox, scopes reads and searches to one inbox via the inbox parameter, and resolves \+per-thread label operations through the owning thread rather than assuming the primary inbox.";++/// The email inbox-behavior prompt.+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);diff --git a/rust/cloud-storage/prompt/src/lib.rs b/rust/cloud-storage/prompt/src/lib.rsindex 4625de6b59..86df068d2e 100644--- a/rust/cloud-storage/prompt/src/lib.rs+++ b/rust/cloud-storage/prompt/src/lib.rs@@ -10,6 +10,7 @@ pub mod channel_mention;pub mod citations;pub mod connected_toolsets;pub mod do_not;+pub mod email;pub mod math;pub mod mcp_item_links;pub mod mentions;@@ -28,9 +29,11 @@ pub static BASE_PROMPT: ComposedPrompt = tone::PROMPT.compose(&do_not::PROMPT).compose(&about_macro::PROMPT);-/// The tool-enabled prompt: [`BASE_PROMPT`] with the tool use instructions-/// appended.-pub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT.compose(&tool_usage::PROMPT);+/// The tool-enabled prompt: [`BASE_PROMPT`] with the tool use instructions and+/// email inbox behavior appended.+pub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT+ .compose(&tool_usage::PROMPT)+ .compose(&email::PROMPT);/// Citation, do-not, and Macro-terms rules surfaced to external MCP clients,/// composed together. These are static; the item-linking rules are not, becausediff --git a/rust/cloud-storage/prompt/tests/compose.rs b/rust/cloud-storage/prompt/tests/compose.rsindex b2fa29cefd..3ab6d24060 100644--- a/rust/cloud-storage/prompt/tests/compose.rs+++ b/rust/cloud-storage/prompt/tests/compose.rs@@ -43,11 +43,23 @@ fn base_prompt_includes_channel_message_mention_format() {fn tool_use_prompt_appends_tool_section_to_base() {let rendered = TOOL_USE_PROMPT.to_string();assert!(rendered.starts_with(&BASE_PROMPT.to_string()));+ assert!(rendered.contains("# Tool Use"));+ assert!(rendered.contains("read the appropriate resource using the read tool."));+ assert!(+ rendered.contains("Only fall back to searching by name if you cannot resolve an address.")+ );+}++#[test]+fn tool_use_prompt_appends_email_section_after_tool_use() {+ let rendered = TOOL_USE_PROMPT.to_string();+ assert!(rendered.contains("# Email Inboxes"));assert!(rendered.trim_end()- .ends_with("Only fall back to searching by name if you cannot resolve an address.")+ .ends_with("or omit both for the primary inbox."));- assert!(rendered.contains("# Tool Use"));- assert!(rendered.contains("read the appropriate resource using the read tool."));+ let tool_use_idx = rendered.find("# Tool Use").expect("tool use section");+ let email_idx = rendered.find("# Email Inboxes").expect("email section");+ assert!(tool_use_idx < email_idx, "email section must come last");}diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex 8bf9e033a0..31fbca4da8 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -9,6 +9,8 @@ ai_tools = ["dep:ai_toolset","dep:async-trait","dep:schemars",+ "email/ai_tools",+ "email/inbound","email/outbound","frecency/outbound","frecency/postgres",diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex 0f0ced928c..2f35b61b74 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -343,6 +343,15 @@ override the default when the user explicitly asks for a specific mailbox or lab#[serde(default, rename = "emailView")]pub email_view: Option<String>,+ /// Restrict email results to a single connected inbox.+ #[schemars(description = "\+Restrict email results to a single connected inbox, given as that inbox's email address. Omit \+to span every inbox the user can access (their own plus any delegated to them). Only set this \+when the user scopes the request to a specific mailbox (e.g. \"my work inbox\", \"the shared \+inbox\"); call ListInboxes first to get the exact address. Only affects email results.")]+ #[serde(default)]+ pub inbox: Option<String>,+/// Maximum number of items to return.#[schemars(description = "Maximum number of items to return. Defaults to 50; max 500.")]#[serde(default)]@@ -481,17 +490,35 @@ where.unwrap_or(RESULT_LIMIT).clamp(1, MAX_RESULT_LIMIT);- let link_ids: Vec<uuid::Uuid> = service_context+ let inboxes = service_context.email_service.get_inboxes_for_macro_id(request_context.user_id.copied()).await.map_err(|e| ToolCallError {description: format!("Failed to resolve email links: {e}"),internal_error: e.into(),- })?- .into_iter()- .map(|link| link.id)- .collect();+ })?;++ // An explicit inbox selector narrows to that one link; it's resolved+ // against the accessible set so a caller can't scope to an inbox they+ // don't have (soup trusts link_ids without an independent check).+ let link_ids: Vec<uuid::Uuid> = match self+ .inbox+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ Some(inbox) => {+ let caller_macro_id = request_context.user_id.to_string();+ let link = email::inbound::toolset::resolve_inbox_selector(+ &inboxes,+ &caller_macro_id,+ Some(inbox),+ )?;+ vec![link.id]+ }+ None => inboxes.iter().map(|link| link.id).collect(),+ };let result = service_context.service