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(ai): grant llm access to soup ast (#3443)
Sean Ayeb77e6004f11f
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 fc64bfd16c..cf10cc1b39 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@@ -431,6 +431,13 @@ export const ListCallRecordsResponse = z.object({});export const ListEntities = z.object({+ callf: z.any().default(null),+ cf: z.any().default(null),+ chanf: z.any().default(null),+ df: z.any().default(null),+ ef: z.any().default(null),+ emailPreset: z.union([z.literal('signal'), z.null()]).optional(),+ emailView: z.union([z.string(), z.null()]).default(null),includeTypes: z.union([z.array(@@ -439,6 +446,9 @@ export const ListEntities = z.object({z.null(),]).optional(),+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),+ pf: z.any().default(null),+ propf: z.any().default(null),sortBy: z.enum(['recently_viewed', 'recently_updated', 'recently_created']).optional(),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 cde61de82b..87042ddbcd 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@@ -87,6 +87,7 @@ export type DocumentContentState = 'unknown' | 'pending' | 'ready';* These values should match the `document_sub_type_value` table in macrodb.*/export type DocumentSubType = 'task';+export type EmailPreset = 'signal';export type EntityItem =| {id: string;@@ -1160,9 +1161,63 @@ export interface ListCallRecordsResponse {*/export interface ListEntities {/**- * Filter to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails.+ * Full soup AST call filter (callf).+ */+ callf?: {+ [k: string]: unknown;+ };+ /**+ * Full soup AST AI chat filter (cf).+ */+ cf?: {+ [k: string]: unknown;+ };+ /**+ * Full soup AST channel filter (chanf).+ */+ chanf?: {+ [k: string]: unknown;+ };+ /**+ * Full soup AST document filter (df). Use the same shape as /items/soup/ast, e.g. {"l":{"id":"..."}}.+ */+ df?: {+ [k: string]: unknown;+ };+ /**+ * Advanced full soup AST email filter (ef). Prefer emailPreset="signal" for common requests. Signal emails and important emails are synonymous; they use {"&":[{"l":{"Importance":true}},{"l":{"Shared":"exclude"}}]}.+ */+ ef?: {+ [k: string]: unknown;+ };+ /**+ * High-level email filter preset. Use "signal" for signal emails. Signal emails and important emails are synonymous: if the user asks for important emails, use emailPreset="signal". This expands to the email AST {"&":[{"l":{"Importance":true}},{"l":{"Shared":"exclude"}}]} and defaults results to emails if includeTypes is omitted.+ */+ emailPreset?: EmailPreset | null;+ /**+ * Email view to use for email results: inbox (default), sent, drafts, starred, all, important, other, or user:<label>.+ */+ emailView?: string | null;+ /**+ * Filter returned items to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails. This is folded into the AST and applied as part of cursor-level filtering.*/includeTypes?: ItemType[] | null;+ /**+ * Maximum number of items to return. Defaults to 50; max 500.+ */+ limit?: number | null;+ /**+ * Full soup AST project filter (pf).+ */+ pf?: {+ [k: string]: unknown;+ };+ /**+ * Full soup AST property filter (propf).+ */+ propf?: {+ [k: string]: unknown;+ };sortBy?: SortBy;}export interface ListEntitiesResponse {diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex 0bfd50a3a7..c9fd07c005 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -30,7 +30,7 @@ axum = ["models_soup/schema",]inbound = ["email/inbound", "entity_access/inbound", "ports"]-outbound = ["dep:readonly_pool", "dep:sqlx", "ports"]+outbound = ["crm/outbound", "dep:readonly_pool", "dep:sqlx", "ports"]ports = ["dep:tokio", "frecency/ports"]@@ -68,6 +68,7 @@ recursion = { workspace = true }rootcause = { workspace = true }schemars = { workspace = true, optional = true }serde = { workspace = true }+serde_json = { workspace = true }sqlx = { workspace = true, optional = true }system_properties = { path = "../system_properties" }thiserror = { workspace = true }@@ -88,7 +89,6 @@ macro_db_migrator = { path = "../macro_db_migrator" }mockall = { workspace = true }ordered-float = { workspace = true }rootcause = { workspace = true }-serde_json = { workspace = true }tokio = { workspace = true }tower = { workspace = true }diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rsindex bab48e3992..b0f28b0cd6 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs@@ -7,7 +7,15 @@ use crate::domain::{use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use email::domain::{models::PreviewView, ports::EmailService};-use item_filters::EntityFilters;+use filter_ast::Expr;+use item_filters::{+ SharedEmailFilter,+ ast::{+ EntityFilterAst, LiteralTree, call::CallLiteral, channel::ChannelLiteral,+ chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral, project::ProjectLiteral,+ properties::PropertiesLiteral,+ },+};use models_pagination::{SimpleSortMethod, TypeEraseCursor};use models_soup::item::SoupItem;use schemars::JsonSchema;@@ -15,11 +23,13 @@ use serde::{Deserialize, Serialize};use uuid::Uuid;use cowlike::CowLike;+use std::sync::Arc;use super::SoupToolContext;/// Internal limit for results - not exposed to agentsconst RESULT_LIMIT: u16 = 50;+const MAX_RESULT_LIMIT: u16 = 500;#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]@@ -40,6 +50,23 @@ impl From<SortBy> for SimpleSortMethod {}}+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum EmailPreset {+ Signal,+}++impl EmailPreset {+ fn filter(self) -> Expr<EmailLiteral> {+ match self {+ EmailPreset::Signal => Expr::and(+ Expr::val(EmailLiteral::Importance(true)),+ Expr::val(EmailLiteral::Shared(SharedEmailFilter::Exclude)),+ ),+ }+ }+}+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema, PartialEq, Eq)]#[serde(rename_all = "snake_case")]pub enum ItemType {@@ -68,19 +95,6 @@ pub enum EntityItem {Call { id: Uuid, created_by: String },}-impl EntityItem {- fn item_type(&self) -> ItemType {- match self {- EntityItem::Document { .. } => ItemType::Document,- EntityItem::AiChat { .. } => ItemType::AiChat,- EntityItem::Project { .. } => ItemType::Project,- EntityItem::Email { .. } => ItemType::Email,- EntityItem::Channel { .. } => ItemType::Channel,- EntityItem::Call { .. } => ItemType::Call,- }- }-}-impl From<SoupItem> for EntityItem {fn from(item: SoupItem) -> Self {match item {@@ -127,16 +141,161 @@ pub struct ListEntitiesResponse {)]pub struct ListEntities {#[schemars(- description = "Filter to specific item types. If not provided, returns all types. Example: [\"document\", \"email\"] returns only documents and emails."+ description = "Filter returned items to specific item types. If not provided, returns all types. Example: [\"document\", \"email\"] returns only documents and emails. This is folded into the AST and applied as part of cursor-level filtering.")]#[serde(default)]pub include_types: Option<Vec<ItemType>>,#[schemars(- description = "How to sort results: recently_viewed (default), recently_updated, or recently_created."+ description = "How to sort results: recently_viewed (default), recently_updated, or recently_created. Use recently_updated for updated_at-style soup results.")]#[serde(default)]pub sort_by: SortBy,++ #[schemars(+ description = "Full soup AST document filter (df). Use the same shape as /items/soup/ast, e.g. {\"l\":{\"id\":\"...\"}}.",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "df")]+ pub document_filter: LiteralTree<DocumentLiteral>,++ #[schemars(+ description = "Full soup AST project filter (pf).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "pf")]+ pub project_filter: LiteralTree<ProjectLiteral>,++ #[schemars(+ description = "Full soup AST AI chat filter (cf).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "cf")]+ pub chat_filter: LiteralTree<ChatLiteral>,++ #[schemars(+ description = "High-level email filter preset. Use \"signal\" for signal emails. Signal emails and important emails are synonymous: if the user asks for important emails, use emailPreset=\"signal\". This expands to the email AST {\"&\":[{\"l\":{\"Importance\":true}},{\"l\":{\"Shared\":\"exclude\"}}]} and defaults results to emails if includeTypes is omitted."+ )]+ #[serde(default)]+ pub email_preset: Option<EmailPreset>,++ #[schemars(+ description = "Advanced full soup AST email filter (ef). Prefer emailPreset=\"signal\" for common requests. Signal emails and important emails are synonymous; they use {\"&\":[{\"l\":{\"Importance\":true}},{\"l\":{\"Shared\":\"exclude\"}}]}.",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "ef")]+ pub email_filter: LiteralTree<EmailLiteral>,++ #[schemars(+ description = "Full soup AST channel filter (chanf).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "chanf")]+ pub channel_filter: LiteralTree<ChannelLiteral>,++ #[schemars(+ description = "Full soup AST call filter (callf).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "callf")]+ pub call_filter: LiteralTree<CallLiteral>,++ #[schemars(+ description = "Full soup AST property filter (propf).",+ with = "Option<serde_json::Value>"+ )]+ #[serde(default, rename = "propf")]+ pub properties_filter: LiteralTree<PropertiesLiteral>,++ #[schemars(+ description = "Email view to use for email results: inbox (default), sent, drafts, starred, all, important, other, or user:<label>."+ )]+ #[serde(default, rename = "emailView")]+ pub email_view: Option<String>,++ #[schemars(description = "Maximum number of items to return. Defaults to 50; max 500.")]+ #[serde(default)]+ pub limit: Option<u16>,+}++impl ListEntities {+ pub(super) fn entity_filter_ast(&self) -> EntityFilterAst {+ let ast = EntityFilterAst {+ document_filter: self.document_filter.clone(),+ project_filter: self.project_filter.clone(),+ chat_filter: self.chat_filter.clone(),+ email_filter: match self.email_preset {+ Some(preset) => Some(Arc::new(preset.filter())),+ None => self.email_filter.clone(),+ },+ channel_filter: self.channel_filter.clone(),+ call_filter: self.call_filter.clone(),+ properties_filter: self.properties_filter.clone(),+ };++ self.apply_include_types_to_ast(ast)+ }++ fn apply_include_types_to_ast(&self, ast: EntityFilterAst) -> EntityFilterAst {+ let Some(include_types) = self+ .effective_include_types()+ .filter(|types| !types.is_empty())+ else {+ return ast;+ };++ EntityFilterAst {+ document_filter: if include_types.contains(&ItemType::Document) {+ ast.document_filter+ } else {+ Some(Arc::new(Expr::val(DocumentLiteral::Id(Uuid::nil()))))+ },+ project_filter: if include_types.contains(&ItemType::Project) {+ ast.project_filter+ } else {+ Some(Arc::new(Expr::val(ProjectLiteral::ProjectId(Uuid::nil()))))+ },+ chat_filter: if include_types.contains(&ItemType::AiChat) {+ ast.chat_filter+ } else {+ Some(Arc::new(Expr::val(ChatLiteral::ChatId(Uuid::nil()))))+ },+ email_filter: if include_types.contains(&ItemType::Email) {+ ast.email_filter+ } else {+ Some(Arc::new(Expr::val(EmailLiteral::ThreadId(Uuid::nil()))))+ },+ channel_filter: if include_types.contains(&ItemType::Channel) {+ ast.channel_filter+ } else {+ Some(Arc::new(Expr::val(ChannelLiteral::ChannelId(Uuid::nil()))))+ },+ call_filter: if include_types.contains(&ItemType::Call) {+ ast.call_filter+ } else {+ Some(Arc::new(Expr::val(CallLiteral::CallId(Uuid::nil()))))+ },+ properties_filter: ast.properties_filter,+ }+ }++ pub(super) fn email_view(&self) -> ToolResult<PreviewView> {+ self.email_view+ .as_deref()+ .map(|view| view.parse::<PreviewView>())+ .transpose()+ .map(|view| view.unwrap_or_default())+ .map_err(|e| ToolCallError {+ description: format!("Invalid emailView: {e}"),+ internal_error: anyhow::anyhow!(e),+ })+ }++ pub(super) fn effective_include_types(&self) -> Option<Vec<ItemType>> {+ self.include_types+ .clone()+ .or_else(|| self.email_preset.is_some().then_some(vec![ItemType::Email]))+ }}#[async_trait]@@ -156,6 +315,12 @@ wheretracing::info!(params=?self, "List entities");let sort_method = SimpleSortMethod::from(self.sort_by);+ let filters = self.entity_filter_ast();+ let email_preview_view = self.email_view()?;+ let limit = self+ .limit+ .unwrap_or(RESULT_LIMIT)+ .clamp(1, MAX_RESULT_LIMIT);let link_id = service_context.email_service@@ -172,10 +337,10 @@ where.get_user_soup(SoupRequest {soup_type: SoupType::Expanded,- limit: RESULT_LIMIT,- cursor: SoupQuery::new_sort_simple(sort_method, EntityFilters::default()),+ limit,+ cursor: SoupQuery::new_sort_simple(sort_method, filters),user: request_context.user_id,- email_preview_view: PreviewView::default(),+ email_preview_view,link_id,},None,@@ -189,23 +354,14 @@ wherelet paginated = result.type_erase();let has_more = paginated.next_cursor.is_some();- // Convert and filter items- let all_items: Vec<EntityItem> = paginated+ let items: Vec<EntityItem> = paginated.items.into_iter().map(|FrecencySoupItem { item, .. }| EntityItem::from(item)).collect();- let items: Vec<EntityItem> = match &self.include_types {- Some(types) if !types.is_empty() => all_items- .into_iter()- .filter(|item| types.contains(&item.item_type()))- .collect(),- _ => all_items,- };-// Build summary- let summary = build_summary(&items, has_more, &self.include_types);+ let summary = build_summary(&items, has_more, &self.effective_include_types());Ok(ListEntitiesResponse { items, summary })}diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rsindex 9b9ab327dd..a03d87ccea 100644--- a/rust/cloud-storage/soup/src/inbound/toolset/test.rs+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs@@ -3,6 +3,7 @@ use super::list_entities::build_summary;use super::*;use ai::generate_tool_input_schema;use ai::tool::types::tool_object::validate_tool_schema;+use non_empty::IsEmpty;use uuid::Uuid;#[test]@@ -30,6 +31,65 @@ fn test_default_values() {assert!(matches!(list.sort_by, SortBy::RecentlyViewed));}+#[test]+fn test_full_ast_input_deserializes() {+ let input = serde_json::json!({+ "callf": {"l": {"CallId": "00000000-0000-0000-0000-000000000000"}},+ "cf": {"l": {"cid": "00000000-0000-0000-0000-000000000000"}},+ "chanf": {"l": {"ChannelId": "00000000-0000-0000-0000-000000000000"}},+ "df": {"l": {"id": "00000000-0000-0000-0000-000000000000"}},+ "ef": {"&": [+ {"l": {"Importance": true}},+ {"l": {"Shared": "exclude"}}+ ]},+ "emailView": "inbox",+ "limit": 100,+ "pf": {"l": {"pid": "00000000-0000-0000-0000-000000000000"}},+ "sortBy": "recently_updated"+ });++ let list: ListEntities = serde_json::from_value(input).unwrap();+ assert_eq!(list.limit, Some(100));+ assert!(matches!(list.sort_by, SortBy::RecentlyUpdated));+ assert!(!list.entity_filter_ast().is_empty());+ assert_eq!(+ list.email_view().unwrap(),+ email::domain::models::PreviewView::default()+ );+}++#[test]+fn test_email_preset_defaults_to_email_results() {+ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "emailPreset": "signal"+ }))+ .unwrap();++ let ast = list.entity_filter_ast();+ assert!(ast.email_filter.is_some());+ assert!(ast.document_filter.is_some());+ assert!(ast.project_filter.is_some());+ assert!(ast.chat_filter.is_some());+ assert!(ast.channel_filter.is_some());+ assert!(ast.call_filter.is_some());+ assert_eq!(list.effective_include_types(), Some(vec![ItemType::Email]));+}++#[test]+fn test_include_types_document_without_filter_keeps_document_unfiltered() {+ let list: ListEntities = serde_json::from_value(serde_json::json!({+ "includeTypes": ["document"]+ }))+ .unwrap();++ let ast = list.entity_filter_ast();+ assert!(ast.document_filter.is_none());+ assert_eq!(+ list.effective_include_types(),+ Some(vec![ItemType::Document])+ );+}+#[test]fn test_build_summary_empty() {let summary = build_summary(&[], false, &None);