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(channel_bots): infer Macro agent invocation in agent threads (#5605)
Eric Hayes8a50fbfd7b94
diff --git a/Cargo.lock b/Cargo.lockindex 189b039bcf..178df37956 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2780,6 +2780,8 @@ dependencies = ["macro_user_id","models_pagination","prompt",+ "serde",+ "serde_json","tokio","tracing","uuid",diff --git a/crates/channel_bots/Cargo.toml b/crates/channel_bots/Cargo.tomlindex ea511002eb..17173783bc 100644--- a/crates/channel_bots/Cargo.toml+++ b/crates/channel_bots/Cargo.toml@@ -16,6 +16,8 @@ channels = { path = "../channels", features = ["inbound", "outbound"] }futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }prompt = { path = "../prompt" }+serde = { workspace = true }+serde_json = { workspace = true }tokio = { workspace = true, features = ["rt", "sync"] }tracing = { workspace = true }uuid = { workspace = true }diff --git a/crates/channel_bots/src/domain/mod.rs b/crates/channel_bots/src/domain/mod.rsindex fe0bba6896..dbcc2378e8 100644--- a/crates/channel_bots/src/domain/mod.rs+++ b/crates/channel_bots/src/domain/mod.rs@@ -3,3 +3,24 @@pub mod models;pub mod ports;pub mod service;+pub mod trigger_detector;++/// Human-readable label for a message sender storage id.+pub(crate) fn sender_label(sender_id: &str) -> String {+ if let Ok(bot) = bot_id::BotIdStr::parse_from_str(sender_id) {+ return if bot.bot_id() == bot_id::MACRO_AI_BOT_ID {+ bot_id::MACRO_AI_NAME.to_string()+ } else {+ "Bot".to_string()+ };+ }+ // User ids look like `macro|<email>`; show the email's local part.+ sender_id+ .rsplit('|')+ .next()+ .unwrap_or(sender_id)+ .split('@')+ .next()+ .unwrap_or(sender_id)+ .to_string()+}diff --git a/crates/channel_bots/src/domain/models.rs b/crates/channel_bots/src/domain/models.rsindex dd3ad76eb2..c66b41e09a 100644--- a/crates/channel_bots/src/domain/models.rs+++ b/crates/channel_bots/src/domain/models.rs@@ -1,5 +1,6 @@//! Domain models for channel bot triggers.+use bot_id::BotId;use channels::domain::models::MutatedMessage;use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;@@ -9,6 +10,18 @@ use uuid::Uuid;pub enum BotTrigger {/// The bot was `@`-mentioned in a channel message.Mention,+ /// A classifier inferred that a thread message expects the bot to respond+ /// even though it was not `@`-mentioned.+ Inferred,+}++/// A decision to invoke a bot for a candidate message.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BotInvocation {+ /// The bot to invoke.+ pub bot_id: BotId,+ /// Why the bot is being invoked.+ pub trigger: BotTrigger,}/// A normalized trigger delivered to a system bot handler.@@ -26,3 +39,14 @@ pub struct BotEvent {/// The user who triggered the bot.pub requesting_user: MacroUserIdStr<'static>,}++/// A thread message rendered for trigger inference, oldest-first.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TranscriptMessage {+ /// Whether the agent itself authored the message.+ pub from_agent: bool,+ /// Display label for the sender.+ pub sender: String,+ /// Message body.+ pub content: String,+}diff --git a/crates/channel_bots/src/domain/ports.rs b/crates/channel_bots/src/domain/ports.rsindex 6ef7cf94f8..545c2b45c5 100644--- a/crates/channel_bots/src/domain/ports.rs+++ b/crates/channel_bots/src/domain/ports.rs@@ -1,6 +1,10 @@//! Port definitions for channel bot domain dependencies.use async_trait::async_trait;+use channels::domain::side_effects::ChannelBotTrigger;+use macro_user_id::user_id::MacroUserIdStr;++use super::models::{BotInvocation, TranscriptMessage};/// Produces an assistant response for a channel message.#[async_trait]@@ -8,3 +12,24 @@ pub trait AgentResponder: Send + Sync {/// Run the agent on behalf of `user_id` with `prompt`, returning the reply.async fn respond(&self, user_id: &str, prompt: String) -> anyhow::Result<String>;}++/// Decides whether a candidate channel message should invoke any bots.+#[async_trait]+pub trait TriggerDetector: Send + Sync {+ /// Resolve the bot invocations for a candidate message. An empty result+ /// means the message triggers nothing.+ async fn detect(&self, candidate: &ChannelBotTrigger) -> Vec<BotInvocation>;+}++/// Classifies whether a thread message expects an agent response without an+/// explicit mention.+#[async_trait]+pub trait InferredTriggerClassifier: Send + Sync {+ /// Whether the last message in `thread` (oldest-first) expects the agent+ /// to respond. `requesting_user` is the author of that message.+ async fn expects_response(+ &self,+ requesting_user: &MacroUserIdStr<'static>,+ thread: &[TranscriptMessage],+ ) -> anyhow::Result<bool>;+}diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rsindex 102480b8ab..d13c67f16e 100644--- a/crates/channel_bots/src/domain/service.rs+++ b/crates/channel_bots/src/domain/service.rs@@ -11,8 +11,9 @@ use channels::domain::models::{use channels::domain::ports::{ChannelMutationErr, ChannelService};use uuid::Uuid;-use super::models::BotEvent;+use super::models::{BotEvent, BotTrigger};use super::ports::AgentResponder;+use super::sender_label;/// How many channel messages to include around the trigger.///@@ -23,39 +24,24 @@ const CONTEXT_MESSAGES_AFTER: i64 = 4;/// Inline marker appended to the sender label of the triggering message so the/// model can tell it apart from surrounding context.-const TRIGGER_MARKER: &str = " [this message mentioned you]";+const MENTION_TRIGGER_MARKER: &str = " [this message mentioned you]";+const INFERRED_TRIGGER_MARKER: &str = " [respond to this message]";-const THREAD_INSTRUCTION: &str = "This is the thread you were mentioned in (oldest to newest). \-Interpret the mention in the context of this thread: words like \"this\" or \"it\" in the \-mention refer to this thread unless the mention says otherwise.";+const MENTION_THREAD_INSTRUCTION: &str = "This is the thread you were mentioned in (oldest to \+newest). Interpret the mention in the context of this thread: words like \"this\" or \"it\" in \+the mention refer to this thread unless the mention says otherwise.";++const INFERRED_THREAD_INSTRUCTION: &str = "This is the thread the message was posted in (oldest \+to newest). Interpret the message in the context of this thread: words like \"this\" or \"it\" \+refer to this thread unless the message says otherwise.";const CHANNEL_BACKGROUND_INSTRUCTION: &str = "Other recent messages in the same channel, outside \the thread above (oldest to newest). Background only — do not treat these as the subject of the \-mention.";+triggering message.";const CHANNEL_CONTEXT_INSTRUCTION: &str = "Recent messages in the channel around the mention \(oldest to newest).";-/// Human-readable label for a message sender storage id.-fn sender_label(sender_id: &str) -> String {- if let Ok(bot) = bot_id::BotIdStr::parse_from_str(sender_id) {- return if bot.bot_id() == bot_id::MACRO_AI_BOT_ID {- bot_id::MACRO_AI_NAME.to_string()- } else {- "Bot".to_string()- };- }- // User ids look like `macro|<email>`; show the email's local part.- sender_id- .rsplit('|')- .next()- .unwrap_or(sender_id)- .split('@')- .next()- .unwrap_or(sender_id)- .to_string()-}-/// A single message rendered into the prompt.struct PromptLine {sender: String,@@ -75,13 +61,19 @@ fn trigger_line(event: &BotEvent) -> PromptLine {/// Write a tagged context block: an instruction line followed by one message/// per line, labeled by sender. Skipped entirely when there are no messages.-fn append_block(prompt: &mut String, tag: &str, instruction: &str, lines: &[PromptLine]) {+fn append_block(+ prompt: &mut String,+ tag: &str,+ instruction: &str,+ trigger_marker: &str,+ lines: &[PromptLine],+) {if lines.is_empty() {return;}let _ = write!(prompt, "\n<{tag}>\n{instruction}\n\n");for line in lines {- let marker = if line.is_trigger { TRIGGER_MARKER } else { "" };+ let marker = if line.is_trigger { trigger_marker } else { "" };let _ = writeln!(prompt, "{}{marker}: {}", line.sender, line.content);}let _ = writeln!(prompt, "</{tag}>");@@ -195,12 +187,24 @@ wherelet mut prompt = String::new();if let Some(parent_id) = event.message.thread_id {- let _ = writeln!(- prompt,- "{mentioner} mentioned you (@macro) in a channel thread."- );+ let (intro, thread_instruction, marker) = match event.trigger {+ BotTrigger::Mention => (+ format!("{mentioner} mentioned you (@macro) in a channel thread."),+ MENTION_THREAD_INSTRUCTION,+ MENTION_TRIGGER_MARKER,+ ),+ BotTrigger::Inferred => (+ format!(+ "{mentioner} replied in a channel thread you are part of. They did not \+ @-mention you, but their message appears to be addressed to you."+ ),+ INFERRED_THREAD_INSTRUCTION,+ INFERRED_TRIGGER_MARKER,+ ),+ };+ let _ = writeln!(prompt, "{intro}");let (thread, thread_ids) = self.thread_lines(event, parent_id).await;- append_block(&mut prompt, "thread", THREAD_INSTRUCTION, &thread);+ append_block(&mut prompt, "thread", thread_instruction, marker, &thread);let background: Vec<PromptLine> = nearby.iter()@@ -220,6 +224,7 @@ where&mut prompt,"channel_background",CHANNEL_BACKGROUND_INSTRUCTION,+ marker,&background,);} else {@@ -242,6 +247,7 @@ where&mut prompt,"channel_context",CHANNEL_CONTEXT_INSTRUCTION,+ MENTION_TRIGGER_MARKER,&lines,);}diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rsindex 71fe503c02..97eacdc1e2 100644--- a/crates/channel_bots/src/domain/service/tests.rs+++ b/crates/channel_bots/src/domain/service/tests.rs@@ -320,9 +320,27 @@ fn mention_event(thread_id: Option<Uuid>,sender_email: &str,content: &str,+) -> BotEvent {+ bot_event(+ BotTrigger::Mention,+ channel_id,+ trigger_id,+ thread_id,+ sender_email,+ content,+ )+}++fn bot_event(+ trigger: BotTrigger,+ channel_id: Uuid,+ trigger_id: Uuid,+ thread_id: Option<Uuid>,+ sender_email: &str,+ content: &str,) -> BotEvent {BotEvent {- trigger: BotTrigger::Mention,+ trigger,channel_id,message: MutatedMessage {id: trigger_id,@@ -530,6 +548,45 @@ async fn thread_prompt_puts_thread_first_and_demotes_channel_noise() {assert!(prompt.ends_with("Reply to austin."));}+#[tokio::test]+async fn inferred_thread_prompt_does_not_claim_a_mention() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let trigger_id = Uuid::new_v4();+ let macro_ai = bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string();++ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: vec![context_message(+ channel_id,+ parent_id,+ "macro|[email protected]",+ "notifications are broken",+ )],+ thread_replies: vec![+ thread_reply(Uuid::new_v4(), ¯o_ai, "what is broken exactly?"),+ thread_reply(trigger_id, "macro|[email protected]", "it fires twice"),+ ],+ });+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let event = bot_event(+ BotTrigger::Inferred,+ channel_id,+ trigger_id,+ Some(parent_id),+ "[email protected]",+ "it fires twice",+ );++ let prompt = handler.build_prompt(&event).await;++ assert!(prompt.contains("alice replied in a channel thread you are part of."));+ assert!(!prompt.contains("mentioned you (@macro)"));+ assert!(prompt.contains("alice [respond to this message]: it fires twice"));+ assert!(!prompt.contains("[this message mentioned you]"));+ assert!(prompt.ends_with("Reply to alice."));+}+#[tokio::test]async fn thread_prompt_includes_trigger_when_reply_fetch_fails_to_return_it() {let channel_id = Uuid::new_v4();diff --git a/crates/channel_bots/src/domain/trigger_detector.rs b/crates/channel_bots/src/domain/trigger_detector.rsnew file mode 100644index 0000000000..3d3d6cc799--- /dev/null+++ b/crates/channel_bots/src/domain/trigger_detector.rs@@ -0,0 +1,154 @@+//! Trigger detection for candidate channel messages.++use std::sync::Arc;++use async_trait::async_trait;+use channels::domain::ports::ChannelService;+use channels::domain::side_effects::ChannelBotTrigger;+use uuid::Uuid;++use super::models::{BotInvocation, BotTrigger, TranscriptMessage};+use super::ports::{InferredTriggerClassifier, TriggerDetector};+use super::sender_label;++/// Detects both explicit `@`-mention triggers and inferred triggers.+///+/// A message that mentions bots triggers exactly those bots. A message that+/// mentions none is considered for an inferred Macro AI trigger, which fires+/// only when all of the following hold:+///+/// * the message is a thread reply (never a top-level message),+/// * the thread already contains a Macro AI message,+/// * the classifier judges that the message expects an agent response.+///+/// Bot-authored messages never trigger anything; classifier failures resolve+/// to no trigger.+pub struct MentionOrInferredDetector<C, I> {+ channels: Arc<C>,+ classifier: Arc<I>,+}++impl<C, I> MentionOrInferredDetector<C, I>+where+ C: ChannelService,+ I: InferredTriggerClassifier,+{+ /// Create a detector from the channel read service and a classifier.+ pub fn new(channels: Arc<C>, classifier: Arc<I>) -> Self {+ Self {+ channels,+ classifier,+ }+ }++ /// Load the thread (parent + replies, oldest-first) as a transcript. The+ /// candidate message is appended if the reply fetch does not include it+ /// yet.+ async fn thread_transcript(+ &self,+ candidate: &ChannelBotTrigger,+ parent_id: Uuid,+ ) -> Vec<TranscriptMessage> {+ let mut transcript = Vec::new();++ let parent = self+ .channels+ .get_message_context(candidate.channel_id, parent_id, 0, 0)+ .await+ .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread parent"))+ .unwrap_or_default()+ .into_iter()+ .find(|message| message.id == parent_id);+ if let Some(parent) = parent+ && parent.deleted_at.is_none()+ && !parent.content.trim().is_empty()+ {+ transcript.push(transcript_message(&parent.sender_id, &parent.content));+ }++ let replies = self+ .channels+ .get_thread_replies(candidate.channel_id, parent_id)+ .await+ .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread replies"))+ .unwrap_or_default();+ let mut candidate_included = false;+ for reply in replies {+ if reply.content.trim().is_empty() {+ continue;+ }+ candidate_included |= reply.id == candidate.message.id;+ transcript.push(transcript_message(&reply.sender_id, &reply.content));+ }+ if !candidate_included {+ transcript.push(transcript_message(+ candidate.message.sender_id.as_ref(),+ &candidate.message.content,+ ));+ }+ transcript+ }++ async fn infer(&self, candidate: &ChannelBotTrigger) -> Option<BotInvocation> {+ let requesting_user = candidate.message.sender_id.as_user()?;+ let parent_id = candidate.message.thread_id?;++ let transcript = self.thread_transcript(candidate, parent_id).await;+ if !transcript.iter().any(|message| message.from_agent) {+ return None;+ }++ match self+ .classifier+ .expects_response(requesting_user, &transcript)+ .await+ {+ Ok(true) => Some(BotInvocation {+ bot_id: bot_id::MACRO_AI_BOT_ID,+ trigger: BotTrigger::Inferred,+ }),+ Ok(false) => None,+ Err(err) => {+ tracing::warn!(error=?err, "inferred trigger classification failed");+ None+ }+ }+ }+}++fn transcript_message(sender_id: &str, content: &str) -> TranscriptMessage {+ let from_agent = bot_id::BotIdStr::parse_from_str(sender_id)+ .is_ok_and(|bot| bot.bot_id() == bot_id::MACRO_AI_BOT_ID);+ TranscriptMessage {+ from_agent,+ sender: sender_label(sender_id),+ content: content.trim().to_string(),+ }+}++#[async_trait]+impl<C, I> TriggerDetector for MentionOrInferredDetector<C, I>+where+ C: ChannelService,+ I: InferredTriggerClassifier,+{+ async fn detect(&self, candidate: &ChannelBotTrigger) -> Vec<BotInvocation> {+ if candidate.message.sender_id.as_user().is_none() {+ return Vec::new();+ }+ if !candidate.mentioned_bot_ids.is_empty() {+ return candidate+ .mentioned_bot_ids+ .iter()+ .map(|bot_id| BotInvocation {+ bot_id: *bot_id,+ trigger: BotTrigger::Mention,+ })+ .collect();+ }+ self.infer(candidate).await.into_iter().collect()+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/channel_bots/src/domain/trigger_detector/tests.rs b/crates/channel_bots/src/domain/trigger_detector/tests.rsnew file mode 100644index 0000000000..b331cce92f--- /dev/null+++ b/crates/channel_bots/src/domain/trigger_detector/tests.rs@@ -0,0 +1,467 @@+use std::sync::{Arc, Mutex};++use async_trait::async_trait;+use channels::domain::models::{+ AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,+ ChannelParticipant, MessagePageDirection, MutatedMessage, ResolvedChannelMessage, Sender,+ ThreadReply,+};+use channels::domain::ports::{+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesQueryResult, ChannelService,+};+use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use models_pagination::{CreatedAt, Query};++use super::*;++struct TestChannelService {+ parent: Option<ChannelContextMessage>,+ thread_replies: Vec<ThreadReply>,+}++impl ChannelService for TestChannelService {+ fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _direction: MessagePageDirection,+ _limit: u16,+ _filters: &ChannelMessageFilters,+ _notification_user_id: Option<MacroUserIdStr<'static>>,+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for detector tests") }+ }++ fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ _attachment_type: Option<ChannelAttachmentType>,+ ) -> impl Future<Output = Result<ChannelAttachmentsPage, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for detector tests") }+ }++ fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for detector tests") }+ }++ fn get_message_context(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _before: i64,+ _after: i64,+ ) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {+ let messages = self.parent.clone().into_iter().collect::<Vec<_>>();+ async move { Ok(messages) }+ }++ fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send+ {+ async move { unimplemented!("not needed for detector tests") }+ }++ fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _limit: u16,+ ) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for detector tests") }+ }++ fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {+ let replies = self.thread_replies.clone();+ async move { Ok(replies) }+ }++ fn resolve_message(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> impl Future<Output = Result<ResolvedChannelMessage, ChannelMessagesErr>> + Send {+ async move { unimplemented!("not needed for detector tests") }+ }+}++struct TestClassifier {+ result: anyhow::Result<bool>,+ received: Mutex<Option<Vec<TranscriptMessage>>>,+}++impl TestClassifier {+ fn returning(result: anyhow::Result<bool>) -> Self {+ Self {+ result,+ received: Mutex::new(None),+ }+ }++ fn received_thread(&self) -> Option<Vec<TranscriptMessage>> {+ self.received.lock().unwrap().clone()+ }+}++#[async_trait]+impl InferredTriggerClassifier for TestClassifier {+ async fn expects_response(+ &self,+ _requesting_user: &MacroUserIdStr<'static>,+ thread: &[TranscriptMessage],+ ) -> anyhow::Result<bool> {+ *self.received.lock().unwrap() = Some(thread.to_vec());+ match &self.result {+ Ok(value) => Ok(*value),+ Err(err) => anyhow::bail!("{err}"),+ }+ }+}++fn user_id(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|{email}")).unwrap()+}++fn macro_ai_sender_id() -> String {+ bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string()+}++fn candidate(+ channel_id: Uuid,+ thread_id: Option<Uuid>,+ sender: Sender,+ content: &str,+ mentioned_bot_ids: Vec<bot_id::BotId>,+) -> ChannelBotTrigger {+ let now = Utc::now();+ ChannelBotTrigger {+ channel_id,+ message: MutatedMessage {+ id: Uuid::new_v4(),+ channel_id,+ thread_id,+ sender_id: sender,+ triggered_by: None,+ content: content.to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ deleted_at: None,+ },+ mentioned_bot_ids,+ }+}++fn parent_message(+ channel_id: Uuid,+ id: Uuid,+ sender_id: &str,+ content: &str,+) -> ChannelContextMessage {+ let now = Utc::now();+ ChannelContextMessage {+ id,+ channel_id,+ thread_id: None,+ sender_id: sender_id.to_string(),+ triggered_by: None,+ bot_profile: None,+ content: content.to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ deleted_at: None,+ }+}++fn thread_reply(sender_id: &str, content: &str) -> ThreadReply {+ let now = Utc::now();+ ThreadReply {+ id: Uuid::new_v4(),+ sender_id: sender_id.to_string(),+ triggered_by: None,+ bot_profile: None,+ content: content.to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ reactions: Vec::new(),+ attachments: Vec::new(),+ }+}++fn detector(+ channels: TestChannelService,+ classifier: Arc<TestClassifier>,+) -> MentionOrInferredDetector<TestChannelService, TestClassifier> {+ MentionOrInferredDetector::new(Arc::new(channels), classifier)+}++fn thread_with_agent_reply(channel_id: Uuid, parent_id: Uuid) -> TestChannelService {+ TestChannelService {+ parent: Some(parent_message(+ channel_id,+ parent_id,+ "macro|[email protected]",+ "notifications are broken",+ )),+ thread_replies: vec![thread_reply(+ ¯o_ai_sender_id(),+ "what is broken exactly?",+ )],+ }+}++#[tokio::test]+async fn mention_triggers_each_mentioned_bot_without_classification() {+ let channel_id = Uuid::new_v4();+ let other_bot = bot_id::BotId::new_from_uuid(Uuid::new_v4());+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ TestChannelService {+ parent: None,+ thread_replies: Vec::new(),+ },+ classifier.clone(),+ );++ let invocations = detector+ .detect(&candidate(+ channel_id,+ None,+ Sender::new_from_user(user_id("[email protected]")),+ "@macro help",+ vec![bot_id::MACRO_AI_BOT_ID, other_bot],+ ))+ .await;++ assert_eq!(+ invocations,+ vec![+ BotInvocation {+ bot_id: bot_id::MACRO_AI_BOT_ID,+ trigger: BotTrigger::Mention,+ },+ BotInvocation {+ bot_id: other_bot,+ trigger: BotTrigger::Mention,+ },+ ]+ );+ assert!(classifier.received_thread().is_none());+}++#[tokio::test]+async fn bot_authored_message_never_triggers() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ thread_with_agent_reply(channel_id, parent_id),+ classifier.clone(),+ );++ let invocations = detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),+ "I fixed it",+ Vec::new(),+ ))+ .await;++ assert!(invocations.is_empty());+ assert!(classifier.received_thread().is_none());+}++#[tokio::test]+async fn top_level_message_is_never_inferred() {+ let channel_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ TestChannelService {+ parent: None,+ thread_replies: Vec::new(),+ },+ classifier.clone(),+ );++ let invocations = detector+ .detect(&candidate(+ channel_id,+ None,+ Sender::new_from_user(user_id("[email protected]")),+ "macro agent respond",+ Vec::new(),+ ))+ .await;++ assert!(invocations.is_empty());+ assert!(classifier.received_thread().is_none());+}++#[tokio::test]+async fn thread_without_agent_message_is_never_inferred() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ TestChannelService {+ parent: Some(parent_message(+ channel_id,+ parent_id,+ "macro|[email protected]",+ "anyone looked at this?",+ )),+ thread_replies: vec![thread_reply("macro|[email protected]", "not yet")],+ },+ classifier.clone(),+ );++ let invocations = detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_user(user_id("[email protected]")),+ "can someone respond",+ Vec::new(),+ ))+ .await;++ assert!(invocations.is_empty());+ assert!(classifier.received_thread().is_none());+}++#[tokio::test]+async fn thread_reply_after_agent_message_infers_when_classifier_agrees() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ thread_with_agent_reply(channel_id, parent_id),+ classifier.clone(),+ );++ let invocations = detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_user(user_id("[email protected]")),+ "it fires twice per message",+ Vec::new(),+ ))+ .await;++ assert_eq!(+ invocations,+ vec![BotInvocation {+ bot_id: bot_id::MACRO_AI_BOT_ID,+ trigger: BotTrigger::Inferred,+ }]+ );++ let thread = classifier.received_thread().expect("classifier called");+ assert_eq!(+ thread,+ vec![+ TranscriptMessage {+ from_agent: false,+ sender: "alice".to_string(),+ content: "notifications are broken".to_string(),+ },+ TranscriptMessage {+ from_agent: true,+ sender: bot_id::MACRO_AI_NAME.to_string(),+ content: "what is broken exactly?".to_string(),+ },+ TranscriptMessage {+ from_agent: false,+ sender: "alice".to_string(),+ content: "it fires twice per message".to_string(),+ },+ ]+ );+}++#[tokio::test]+async fn classifier_rejection_yields_no_trigger() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(false)));+ let detector = detector(thread_with_agent_reply(channel_id, parent_id), classifier);++ let invocations = detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_user(user_id("[email protected]")),+ "thanks, I'll take it from here",+ Vec::new(),+ ))+ .await;++ assert!(invocations.is_empty());+}++#[tokio::test]+async fn classifier_failure_yields_no_trigger() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Err(anyhow::anyhow!(+ "model down"+ ))));+ let detector = detector(thread_with_agent_reply(channel_id, parent_id), classifier);++ let invocations = detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_user(user_id("[email protected]")),+ "it fires twice per message",+ Vec::new(),+ ))+ .await;++ assert!(invocations.is_empty());+}++#[tokio::test]+async fn candidate_message_is_appended_when_missing_from_replies() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let classifier = Arc::new(TestClassifier::returning(Ok(true)));+ let detector = detector(+ thread_with_agent_reply(channel_id, parent_id),+ classifier.clone(),+ );++ detector+ .detect(&candidate(+ channel_id,+ Some(parent_id),+ Sender::new_from_user(user_id("[email protected]")),+ "u so dumb",+ Vec::new(),+ ))+ .await;++ let thread = classifier.received_thread().expect("classifier called");+ let last = thread.last().expect("non-empty transcript");+ assert_eq!(last.sender, "bob");+ assert_eq!(last.content, "u so dumb");+ assert!(!last.from_agent);+}diff --git a/crates/channel_bots/src/inbound/bot_trigger_router.rs b/crates/channel_bots/src/inbound/bot_trigger_router.rsindex f398ef4d66..4b6f9947ed 100644--- a/crates/channel_bots/src/inbound/bot_trigger_router.rs+++ b/crates/channel_bots/src/inbound/bot_trigger_router.rs@@ -7,82 +7,90 @@ use channels::domain::side_effects::ChannelBotTrigger;use tokio::sync::mpsc::UnboundedReceiver;use crate::domain::{- models::{BotEvent, BotTrigger},- ports::AgentResponder,+ models::BotEvent,+ ports::{AgentResponder, TriggerDetector},service::MacroAiHandler,};-/// Resolves the bots mentioned in a channel message and runs their handlers.+/// Resolves the bot invocations for a candidate channel message and runs their+/// handlers.///-/// Receives triggers derived by the channel side-effect service. Dispatch is-/// fire-and-forget: each trigger is handled on a spawned task.+/// Receives trigger candidates derived by the channel side-effect service. A+/// [`TriggerDetector`] decides which bots each candidate invokes — explicit+/// `@`-mentions or an inferred invocation. Dispatch is fire-and-forget: each+/// candidate is handled on a spawned task.////// System bots are defined in code and require no database row. Unknown bot ids/// are ignored here; only Macro AI is handled by this branch. Non-system bots/// are notified of mentions out of process via the `channel.mentioned`/// webhook event instead (see the `webhook` crate).-pub struct BotTriggerRouter<C, R> {+pub struct BotTriggerRouter<C, R, D> {macro_ai: Arc<MacroAiHandler<C, R>>,+ detector: Arc<D>,}-impl<C, R> Clone for BotTriggerRouter<C, R> {+impl<C, R, D> Clone for BotTriggerRouter<C, R, D> {fn clone(&self) -> Self {Self {macro_ai: self.macro_ai.clone(),+ detector: self.detector.clone(),}}}-impl<C, R> BotTriggerRouter<C, R>+impl<C, R, D> BotTriggerRouter<C, R, D>whereC: ChannelService,R: AgentResponder,+ D: TriggerDetector,{/// Create a router with the built-in system bots registered.- pub fn new(channels: Arc<C>, responder: Arc<R>) -> Self {+ pub fn new(channels: Arc<C>, responder: Arc<R>, detector: Arc<D>) -> Self {Self {macro_ai: Arc::new(MacroAiHandler::new(channels, responder)),+ detector,}}- /// Start consuming channel bot triggers.- pub fn spawn(self, mut triggers: UnboundedReceiver<ChannelBotTrigger>)+ /// Start consuming channel bot trigger candidates.+ pub fn spawn(self, mut candidates: UnboundedReceiver<ChannelBotTrigger>)whereR: 'static,+ D: 'static,{tokio::spawn(async move {- while let Some(trigger) = triggers.recv().await {+ while let Some(candidate) = candidates.recv().await {let router = self.clone();tokio::spawn(async move {- router.run(trigger).await;+ router.run(candidate).await;});}});}- async fn run(&self, trigger: ChannelBotTrigger) {+ async fn run(&self, candidate: ChannelBotTrigger) {// Guarded upstream, but double-check: only user messages trigger bots.- let Some(requesting_user) = trigger.message.sender_id.as_user().cloned() else {+ let Some(requesting_user) = candidate.message.sender_id.as_user().cloned() else {return;};- let reply_thread_id = trigger.message.thread_id.unwrap_or(trigger.message.id);+ let reply_thread_id = candidate.message.thread_id.unwrap_or(candidate.message.id);- for id in &trigger.bot_ids {+ for invocation in self.detector.detect(&candidate).await {let event = BotEvent {- trigger: BotTrigger::Mention,- channel_id: trigger.channel_id,- message: trigger.message.clone(),+ trigger: invocation.trigger,+ channel_id: candidate.channel_id,+ message: candidate.message.clone(),reply_thread_id,requesting_user: requesting_user.clone(),};// System bots are defined in code — no database lookup required.- if *id == bot_id::MACRO_AI_BOT_ID {+ if invocation.bot_id == bot_id::MACRO_AI_BOT_ID {if let Err(err) = self.macro_ai.handle(&event).await {- tracing::error!(error=?err, bot_id = %id, "system bot handler failed");+ tracing::error!(error=?err, bot_id = %invocation.bot_id, "system bot handler failed");}} else {- tracing::debug!(bot_id = %id, "no system bot handler registered for bot trigger");+ tracing::debug!(bot_id = %invocation.bot_id, "no system bot handler registered for bot trigger");}}}diff --git a/crates/channel_bots/src/lib.rs b/crates/channel_bots/src/lib.rsindex fdf4fa1c05..e14a266046 100644--- a/crates/channel_bots/src/lib.rs+++ b/crates/channel_bots/src/lib.rs@@ -2,10 +2,15 @@//! Channel bots: trigger built-in bot behavior from channel events.//!-//! Channels emit [`ChannelBotTrigger`](channels::domain::side_effects::ChannelBotTrigger)s-//! when a user message mentions one or more bots. The inbound-//! [`BotTriggerRouter`](inbound::BotTriggerRouter) resolves each mentioned-//! system bot and runs the appropriate domain service:+//! Channels emit a [`ChannelBotTrigger`](channels::domain::side_effects::ChannelBotTrigger)+//! candidate for every user-authored message. The inbound+//! [`BotTriggerRouter`](inbound::BotTriggerRouter) resolves each candidate+//! through a [`TriggerDetector`](domain::ports::TriggerDetector) — an explicit+//! `@`-mention triggers the mentioned bots, and a thread reply with no mention+//! may trigger an *inferred* Macro AI invocation when the thread already+//! contains an agent message and a fast-model classifier judges that the+//! message expects an agent response — and runs the appropriate domain+//! service://!//! * **System bots** (defined inside Macro) run in-process. The only one today//! is Macro AI, handled bydiff --git a/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs b/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rsnew file mode 100644index 0000000000..c5a10aeb72--- /dev/null+++ b/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs@@ -0,0 +1,120 @@+//! Fast-model adapter for inferred trigger classification.++use std::fmt::Write as _;+use std::sync::Arc;++use agent::structured_output::{DynamicSchema, dynamic_structured_completion};+use agent::{Message, PredefinedModel};+use async_trait::async_trait;+use macro_user_id::user_id::MacroUserIdStr;+use serde::Deserialize;+use serde_json::json;++use crate::domain::models::TranscriptMessage;+use crate::domain::ports::InferredTriggerClassifier;++static SYSTEM_PROMPT: &str = r#"You decide whether the latest message in a channel thread expects a response from Macro, an AI agent participating in the thread. The agent normally only responds when explicitly @-mentioned; your job is to catch messages that are clearly directed at the agent without a mention.++Answer true only when the latest message is addressed to the agent, for example:+- it asks the agent a question or gives it an instruction+- it answers a question the agent just asked+- it reacts to the agent's last message in a way that invites a reply (a correction, a complaint about the agent's answer, a follow-up)++Answer false when:+- the message is addressed to another person in the thread+- the message is general discussion between people that the agent happens to be able to see+- the message closes the conversation and invites no reply (e.g. "thanks", "got it")+- it is ambiguous who the message is addressed to++When in doubt, answer false: an unwanted agent reply is worse than a missed one."#;++/// [`InferredTriggerClassifier`] backed by a one-shot completion on the fast+/// model.+pub struct FastModelTriggerClassifier {+ model: PredefinedModel,+ recorder: Arc<dyn ai_usage::UsageRecorder>,+}++#[derive(Debug, Deserialize)]+struct ClassifierOutput {+ expects_response: bool,+ reason: String,+}++impl FastModelTriggerClassifier {+ /// Create a classifier using the fast agent model.+ pub fn new(recorder: Arc<dyn ai_usage::UsageRecorder>) -> Self {+ Self {+ model: PredefinedModel::Fast,+ recorder,+ }+ }+}++fn render_thread(thread: &[TranscriptMessage]) -> String {+ let mut rendered = String::new();+ for message in thread {+ let role = if message.from_agent {+ " (the agent)"+ } else {+ ""+ };+ let _ = writeln!(rendered, "{}{role}: {}", message.sender, message.content);+ }+ rendered+}++#[async_trait]+impl InferredTriggerClassifier for FastModelTriggerClassifier {+ #[tracing::instrument(skip(self, thread), err)]+ async fn expects_response(+ &self,+ requesting_user: &MacroUserIdStr<'static>,+ thread: &[TranscriptMessage],+ ) -> anyhow::Result<bool> {+ let prompt = format!(+ "Thread (oldest to newest; the last message is the one to judge):\n\n{}",+ render_thread(thread)+ );+ let schema = DynamicSchema {+ name: "InferredTriggerOutput".to_string(),+ description: Some(+ "Judgement for whether the latest thread message expects an agent response."+ .to_string(),+ ),+ schema: json!({+ "type": "object",+ "additionalProperties": false,+ "required": ["expects_response", "reason"],+ "properties": {+ "expects_response": {+ "type": "boolean",+ "description": "True only if the latest message is addressed to the agent and expects it to respond."+ },+ "reason": {+ "type": "string",+ "description": "A concise reason for the judgement."+ }+ }+ }),+ };++ let value = dynamic_structured_completion(+ self.model,+ SYSTEM_PROMPT,+ vec![Message::user(prompt)],+ schema,+ self.recorder.as_ref(),+ ai_usage::UsageContext::new(ai_usage::AiFeature::ChannelBot, requesting_user.clone()),+ )+ .await?;++ let output: ClassifierOutput = serde_json::from_value(value)?;+ tracing::debug!(+ expects_response = output.expects_response,+ reason = %output.reason,+ "inferred trigger classification"+ );+ Ok(output.expects_response)+ }+}diff --git a/crates/channel_bots/src/outbound/mod.rs b/crates/channel_bots/src/outbound/mod.rsindex 628915d71b..aaa6f5b8fb 100644--- a/crates/channel_bots/src/outbound/mod.rs+++ b/crates/channel_bots/src/outbound/mod.rs@@ -1,5 +1,7 @@//! Outbound adapters for channel bot dependencies.mod agent_loop_responder;+mod fast_model_trigger_classifier;pub use agent_loop_responder::AgentLoopResponder;+pub use fast_model_trigger_classifier::FastModelTriggerClassifier;diff --git a/crates/channels/src/domain/side_effects.rs b/crates/channels/src/domain/side_effects.rsindex fa67de9678..1d10e6e0da 100644--- a/crates/channels/src/domain/side_effects.rs+++ b/crates/channels/src/domain/side_effects.rs@@ -30,18 +30,23 @@ use uuid::Uuid;/// Entity type used by message mentions that target a bot.pub const BOT_MENTION_ENTITY_TYPE: &str = "bot";-/// A trigger derived from a channel message that mentions one or more bots.+/// A bot-trigger candidate derived from a user-authored channel message.+///+/// Every user-authored message is a candidate; whether it actually triggers a+/// bot (explicit mention or inferred invocation) is decided downstream by the+/// consumer.#[derive(Debug, Clone)]pub struct ChannelBotTrigger {- /// Channel containing the triggering message.+ /// Channel containing the candidate message.pub channel_id: Uuid,- /// The user-authored message that mentioned the bot(s).+ /// The user-authored message.pub message: MutatedMessage,- /// Bots mentioned in the message.- pub bot_ids: Vec<BotId>,+ /// Bots explicitly mentioned in the message that are active in the+ /// channel. Empty when the message mentions no bot.+ pub mentioned_bot_ids: Vec<BotId>,}-/// Sender for bot triggers derived from channel messages.+/// Sender for bot-trigger candidates derived from channel messages.pub type ChannelBotTriggerSender = UnboundedSender<ChannelBotTrigger>;/// Collect the bot ids mentioned in a message.@@ -392,7 +397,7 @@ impl<C, R, N, K, B> ChannelSideEffectService<C, R, N, K, B> {}}- /// Dispatch bot triggers for any bots mentioned in a user-authored message.+ /// Dispatch a bot-trigger candidate for a user-authored message.fn dispatch_bot_triggers(&self,channel_id: Uuid,@@ -405,17 +410,13 @@ impl<C, R, N, K, B> ChannelSideEffectService<C, R, N, K, B> {if message.sender_id.as_user().is_none() {return;}- let bot_ids = active_bot_mention_ids(mentions, participants);- if bot_ids.is_empty() {- return;- }if let Some(bot_triggers) = &self.bot_triggers&& bot_triggers.send(ChannelBotTrigger {channel_id,message: message.clone(),- bot_ids,+ mentioned_bot_ids: active_bot_mention_ids(mentions, participants),}).is_err(){diff --git a/crates/channels/src/domain/side_effects/test.rs b/crates/channels/src/domain/side_effects/test.rsindex e4781698ee..d5ff0a8595 100644--- a/crates/channels/src/domain/side_effects/test.rs+++ b/crates/channels/src/domain/side_effects/test.rs@@ -821,12 +821,12 @@ async fn user_message_with_bot_mention_enqueues_bot_trigger() {.expect("expected bot trigger");assert_eq!(trigger.channel_id, channel_id);assert_eq!(trigger.message.id, message_id);- assert_eq!(trigger.bot_ids, vec![bot_id::MACRO_AI_BOT_ID]);+ assert_eq!(trigger.mentioned_bot_ids, vec![bot_id::MACRO_AI_BOT_ID]);assert!(bot_trigger_receiver.try_recv().is_err());}#[tokio::test]-async fn user_message_with_uninstalled_bot_mention_does_not_enqueue_bot_trigger() {+async fn user_message_with_uninstalled_bot_mention_enqueues_candidate_without_that_bot() {let channel_id = Uuid::new_v4();let bot_id = BotId::new_from_uuid(Uuid::new_v4());let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();@@ -876,6 +876,33 @@ async fn user_message_with_uninstalled_bot_mention_does_not_enqueue_bot_trigger(}).await;+ let trigger = bot_trigger_receiver+ .try_recv()+ .expect("expected bot trigger candidate");+ assert!(trigger.mentioned_bot_ids.is_empty());+}++#[tokio::test]+async fn bot_message_never_enqueues_bot_trigger() {+ let channel_id = Uuid::new_v4();+ let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();+ let service = ChannelSideEffectService::new(+ FakeContext::default(),+ FakeRealtime::default(),+ FakeNotifications::default(),+ FakeContacts::default(),+ )+ .with_bot_trigger_sender(bot_trigger_sender);++ service+ .handle(bot_message_posted_event(+ channel_id,+ Uuid::new_v4(),+ Some(Uuid::new_v4()),+ &["macro|[email protected]"],+ ))+ .await;+assert!(bot_trigger_receiver.try_recv().is_err());}diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex c830c7cfcc..21f145584e 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -929,6 +929,14 @@ async fn main() -> anyhow::Result<()> {macro_agent_tool_context,macro_agent_tools,)),+ Arc::new(+ channel_bots::domain::trigger_detector::MentionOrInferredDetector::new(+ channels_service.clone(),+ Arc::new(channel_bots::outbound::FastModelTriggerClassifier::new(+ ai_usage::pg_recorder(db.clone()),+ )),+ ),+ ),);bot_trigger_router.spawn(bot_trigger_receiver);