Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(tools): Soup tool (#1035)

Eric Hayes71869cd4affe
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 6be0b9f0b0..cda74e7493 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -8251,7 +8251,9 @@ dependencies = [
name = "soup"
version = "0.1.0"
dependencies = [
+ "ai",
"anyhow",
+ "async-trait",
"axum",
"axum-extra",
"chrono",
@@ -8278,6 +8280,7 @@ dependencies = [
"ordered-float",
"recursion",
"rootcause",
+ "schemars",
"serde",
"serde_json",
"sqlx",
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index 9eae54feb0..5bb413e4b0 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -5,6 +5,13 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai",
+ "dep:async-trait",
+ "dep:schemars",
+ "models_soup/schema",
+ "ports",
+]
axum = [
"dep:axum",
"dep:axum-extra",
@@ -22,7 +29,9 @@ ports = ["dep:tokio", "frecency/ports"]
[dependencies]
+ai = { path = "../ai", optional = true }
anyhow = { workspace = true }
+async-trait = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
chrono = { workspace = true }
@@ -42,6 +51,7 @@ models_pagination = { path = "../models_pagination" }
models_soup = { path = "../models_soup" }
non_empty = { path = "../non_empty" }
recursion = { workspace = true }
+schemars = { workspace = true, optional = true }
serde = { workspace = true }
sqlx = { workspace = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/inbound.rs b/rust/cloud-storage/soup/src/inbound.rs
index 4272ccd078..c92ecdd06c 100644
--- a/rust/cloud-storage/soup/src/inbound.rs
+++ b/rust/cloud-storage/soup/src/inbound.rs
@@ -1,2 +1,4 @@
#[cfg(feature = "axum")]
pub mod axum_router;
+#[cfg(feature = "ai_tools")]
+pub mod toolset;
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
new file mode 100644
index 0000000000..6acc96fe5a
--- /dev/null
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -0,0 +1,258 @@
+//! ListEntities tool for browsing workspace items.
+
+use crate::domain::{
+ models::{FrecencySoupItem, SoupQuery, SoupRequest, SoupType},
+ ports::SoupService,
+};
+use ai::tool::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use email::domain::models::PreviewView;
+use models_pagination::{Query, SimpleSortMethod, TypeEraseCursor};
+use models_soup::item::SoupItem;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::SoupToolContext;
+
+/// Internal limit for results - not exposed to agents
+const RESULT_LIMIT: u16 = 50;
+
+#[derive(Debug, Clone, Copy, Default, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum SortBy {
+ #[default]
+ RecentlyViewed,
+ RecentlyUpdated,
+ RecentlyCreated,
+}
+
+impl From<SortBy> for SimpleSortMethod {
+ fn from(sort: SortBy) -> Self {
+ match sort {
+ SortBy::RecentlyViewed => SimpleSortMethod::ViewedAt,
+ SortBy::RecentlyUpdated => SimpleSortMethod::UpdatedAt,
+ SortBy::RecentlyCreated => SimpleSortMethod::CreatedAt,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum ItemType {
+ Document,
+ AiChat,
+ Project,
+ Email,
+ Channel,
+}
+
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase", tag = "type")]
+pub enum EntityItem {
+ #[serde(rename_all = "camelCase")]
+ Document { id: Uuid, name: String },
+ #[serde(rename_all = "camelCase")]
+ AiChat { id: Uuid, name: String },
+ #[serde(rename_all = "camelCase")]
+ Project { id: Uuid, name: String },
+ #[serde(rename_all = "camelCase")]
+ Email { id: Uuid, subject: Option<String> },
+ #[serde(rename_all = "camelCase")]
+ Channel { id: Uuid, name: Option<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,
+ }
+ }
+}
+
+impl From<SoupItem> for EntityItem {
+ fn from(item: SoupItem) -> Self {
+ match item {
+ SoupItem::Document(doc) => EntityItem::Document {
+ id: doc.id,
+ name: doc.name,
+ },
+ SoupItem::Chat(chat) => EntityItem::AiChat {
+ id: chat.id,
+ name: chat.name,
+ },
+ SoupItem::Project(project) => EntityItem::Project {
+ id: project.id,
+ name: project.name,
+ },
+ SoupItem::EmailThread(thread) => EntityItem::Email {
+ id: thread.thread.id,
+ subject: thread.thread.name,
+ },
+ SoupItem::Channel(channel) => EntityItem::Channel {
+ id: channel.channel.channel.id.0,
+ name: channel.channel.channel.name.clone(),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ListEntitiesResponse {
+ pub items: Vec<EntityItem>,
+ pub summary: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema, Clone, Default)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ListEntities",
+ description = "Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, and chat channels. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead."
+)]
+pub struct ListEntities {
+ #[schemars(
+ description = "Filter to specific item types. If not provided, returns all types. Example: [\"document\", \"email\"] returns only documents and emails."
+ )]
+ #[serde(default)]
+ pub include_types: Option<Vec<ItemType>>,
+
+ #[schemars(
+ description = "How to sort results: recently_viewed (default), recently_updated, or recently_created."
+ )]
+ #[serde(default)]
+ pub sort_by: SortBy,
+}
+
+#[async_trait]
+impl<T> AsyncTool<SoupToolContext<T>> for ListEntities
+where
+ T: SoupService,
+{
+ type Output = ListEntitiesResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<SoupToolContext<T>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!(params=?self, "List entities");
+
+ let sort_method = SimpleSortMethod::from(self.sort_by);
+
+ let result = service_context
+ .service
+ .get_user_soup(SoupRequest {
+ soup_type: SoupType::Expanded,
+ limit: RESULT_LIMIT,
+ cursor: SoupQuery::Simple(Query::Sort(sort_method, None)),
+ user: (*request_context.user_id).clone(),
+ email_preview_view: PreviewView::default(),
+ link_id: None,
+ })
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to list entities: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ let paginated = result.type_erase();
+ let has_more = paginated.next_cursor.is_some();
+
+ // Convert and filter items
+ let all_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);
+
+ Ok(ListEntitiesResponse { items, summary })
+ }
+}
+
+pub(super) fn build_summary(
+ items: &[EntityItem],
+ has_more: bool,
+ filter: &Option<Vec<ItemType>>,
+) -> String {
+ if items.is_empty() {
+ return match filter {
+ Some(types) if !types.is_empty() => {
+ "No items found matching the specified types.".to_string()
+ }
+ _ => "No items found in workspace.".to_string(),
+ };
+ }
+
+ // Count by type
+ let mut docs = 0;
+ let mut chats = 0;
+ let mut projects = 0;
+ let mut emails = 0;
+ let mut channels = 0;
+
+ for item in items {
+ match item {
+ EntityItem::Document { .. } => docs += 1,
+ EntityItem::AiChat { .. } => chats += 1,
+ EntityItem::Project { .. } => projects += 1,
+ EntityItem::Email { .. } => emails += 1,
+ EntityItem::Channel { .. } => channels += 1,
+ }
+ }
+
+ let mut parts = Vec::new();
+ if docs > 0 {
+ parts.push(format!(
+ "{docs} document{}",
+ if docs == 1 { "" } else { "s" }
+ ));
+ }
+ if chats > 0 {
+ parts.push(format!(
+ "{chats} AI conversation{}",
+ if chats == 1 { "" } else { "s" }
+ ));
+ }
+ if projects > 0 {
+ parts.push(format!(
+ "{projects} project{}",
+ if projects == 1 { "" } else { "s" }
+ ));
+ }
+ if emails > 0 {
+ parts.push(format!(
+ "{emails} email{}",
+ if emails == 1 { "" } else { "s" }
+ ));
+ }
+ if channels > 0 {
+ parts.push(format!(
+ "{channels} channel{}",
+ if channels == 1 { "" } else { "s" }
+ ));
+ }
+
+ let counts = parts.join(", ");
+ if has_more {
+ format!("Showing {counts}. More items available in workspace.")
+ } else {
+ format!("Found {counts}.")
+ }
+}
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/mod.rs b/rust/cloud-storage/soup/src/inbound/toolset/mod.rs
new file mode 100644
index 0000000000..f6d5e61c7e
--- /dev/null
+++ b/rust/cloud-storage/soup/src/inbound/toolset/mod.rs
@@ -0,0 +1,45 @@
+//! Toolset inbound adapter for the Soup service.
+
+mod list_entities;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::ports::SoupService;
+use ai::tool::AsyncToolSet;
+use std::sync::Arc;
+
+pub use list_entities::{EntityItem, ItemType, ListEntities, ListEntitiesResponse, SortBy};
+
+/// Service context for soup AI tools
+pub struct SoupToolContext<T> {
+ /// The soup service instance
+ pub service: Arc<T>,
+}
+
+impl<T> Clone for SoupToolContext<T> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+impl<T> SoupToolContext<T> {
+ /// Create a new soup tool context
+ pub fn new(service: T) -> Self {
+ Self {
+ service: Arc::new(service),
+ }
+ }
+}
+
+/// Create a soup toolset
+pub fn soup_toolset<T>() -> AsyncToolSet<SoupToolContext<T>>
+where
+ T: SoupService,
+{
+ AsyncToolSet::new()
+ .add_tool::<ListEntities, SoupToolContext<T>>()
+ .expect("failed to add ListEntities tool")
+}
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/test.rs b/rust/cloud-storage/soup/src/inbound/toolset/test.rs
new file mode 100644
index 0000000000..d8e964cf51
--- /dev/null
+++ b/rust/cloud-storage/soup/src/inbound/toolset/test.rs
@@ -0,0 +1,82 @@
+use super::list_entities::build_summary;
+use super::*;
+use ai::generate_tool_input_schema;
+use ai::tool::types::tool_object::validate_tool_schema;
+use uuid::Uuid;
+
+#[test]
+fn test_list_entities_schema_validation() {
+ let schema = generate_tool_input_schema!(ListEntities);
+
+ let result = validate_tool_schema(&schema);
+ assert!(result.is_ok(), "{:?}", result);
+
+ let (name, description) = result.unwrap();
+ assert_eq!(
+ name, "ListEntities",
+ "Tool name should match the schemars title"
+ );
+ assert!(
+ description.contains("Browse the user's workspace"),
+ "Description should contain expected text"
+ );
+}
+
+#[test]
+fn test_default_values() {
+ let list = ListEntities::default();
+ assert!(list.include_types.is_none());
+ assert!(matches!(list.sort_by, SortBy::RecentlyViewed));
+}
+
+#[test]
+fn test_build_summary_empty() {
+ let summary = build_summary(&[], false, &None);
+ assert_eq!(summary, "No items found in workspace.");
+
+ let summary = build_summary(&[], false, &Some(vec![ItemType::Document]));
+ assert_eq!(summary, "No items found matching the specified types.");
+}
+
+#[test]
+fn test_build_summary_with_items() {
+ let items = vec![
+ EntityItem::Document {
+ id: Uuid::new_v4(),
+ name: "test.md".to_string(),
+ },
+ EntityItem::Document {
+ id: Uuid::new_v4(),
+ name: "other.md".to_string(),
+ },
+ EntityItem::Email {
+ id: Uuid::new_v4(),
+ subject: Some("Hello".to_string()),
+ },
+ ];
+
+ let summary = build_summary(&items, false, &None);
+ assert!(summary.contains("2 documents"));
+ assert!(summary.contains("1 email"));
+ assert!(summary.starts_with("Found"));
+
+ let summary = build_summary(&items, true, &None);
+ assert!(summary.contains("More items available"));
+}
+
+// run `cargo test -p soup inbound::toolset::test::print_input_schema -- --nocapture --include-ignored`
+#[test]
+#[ignore = "prints the input schema"]
+fn print_input_schema() {
+ let schema = generate_tool_input_schema!(ListEntities);
+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
+}
+
+// run `cargo test -p soup inbound::toolset::test::print_output_schema -- --nocapture --include-ignored`
+#[test]
+#[ignore = "prints the output schema"]
+fn print_output_schema() {
+ let generator = ai::tool::minimized_output_schema_generator();
+ let schema = generator.into_root_schema_for::<ListEntitiesResponse>();
+ println!("{}", serde_json::to_string_pretty(&schema).unwrap());
+}
diff --git a/rust/cloud-storage/soup/src/lib.rs b/rust/cloud-storage/soup/src/lib.rs
index f76105df0f..9c87e37381 100644
--- a/rust/cloud-storage/soup/src/lib.rs
+++ b/rust/cloud-storage/soup/src/lib.rs
@@ -1,5 +1,5 @@
pub mod domain;
-#[cfg(feature = "inbound")]
+#[cfg(any(feature = "inbound", feature = "ai_tools"))]
pub mod inbound;
#[cfg(feature = "outbound")]
pub mod outbound;