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(agents): let agents hand work to other agents (#7664)
Wolf Mermelsteinb77d49932b04
diff --git a/apps/web/src/features/block-agent/state/prompt-origin.test.ts b/apps/web/src/features/block-agent/state/prompt-origin.test.tsindex adf51c92fe..a9af86d3a9 100644--- a/apps/web/src/features/block-agent/state/prompt-origin.test.ts+++ b/apps/web/src/features/block-agent/state/prompt-origin.test.ts@@ -87,6 +87,61 @@ describe('promptOrigin', () => {});});+ it('names the agent that started the session and the person it asked for', () => {+ const discussion = {+ surface: {+ type: 'channel' as const,+ id: 'c1',+ name: 'eng',+ channel_type: 'public' as const,+ },+ prompt_message_id: 'm2',+ sender: agent,+ agent_request: { on_behalf_of: julia, hops: 1 },+ reply_target: { kind: 'thread' as const, root_id: 'm1' },+ thread: {+ root_id: 'm1',+ messages: [+ {+ id: 'm2',+ author: agent,+ content: '@Cursor fix the flaky snapshot test',+ posted_at: '2026-10-15T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ };+ const destination = {+ kind: 'channel_message',+ channelId: 'c1',+ messageId: 'm2',+ threadId: 'm1',+ };+ expect(+ originOf({+ promptMarkdown: 'fix the flaky snapshot test',+ trigger: { kind: 'mentioned', ...discussion },+ })+ ).toEqual({+ lead: 'Started by Macro for Julia in',+ place: '#eng',+ tail: undefined,+ destination,+ });+ expect(+ originOf({+ promptMarkdown: 'one more change',+ trigger: { kind: 'follow_up', addressed_by: 'mention', discussion },+ })+ ).toEqual({+ lead: 'Asked by Macro for Julia in',+ place: '#eng',+ tail: undefined,+ destination,+ });+ });+it('names a direct message by its sender and points at the top-level message', () => {expect(originOf({diff --git a/apps/web/src/features/block-agent/state/prompt-origin.ts b/apps/web/src/features/block-agent/state/prompt-origin.tsindex d4c731e70b..94ca139318 100644--- a/apps/web/src/features/block-agent/state/prompt-origin.ts+++ b/apps/web/src/features/block-agent/state/prompt-origin.ts@@ -371,13 +371,28 @@ export function promptOrigin(contextText: string): PromptOrigin | undefined {};};+ // An agent that asked on a person's behalf names both, ahead of the place.+ const request = discussion && child(discussion, 'agent_request');+ const asker = discussion && attribute(child(discussion, 'sender'), 'name');+ const person = attribute(request && child(request, 'on_behalf_of'), 'name');+ const agentLead =+ request && asker && person+ ? (verb: string) => `${verb} by ${asker} for ${person} in`+ : undefined;+return match(attribute(trigger, 'kind'))- .with('mentioned', () => fromDiscussion('via @mention in'))+ .with('mentioned', () =>+ fromDiscussion(agentLead?.('Started') ?? 'via @mention in')+ ).with('follow_up', () =>- match(attribute(trigger, 'addressed_by'))- .with('explicit_reply', () => fromDiscussion('via reply in'))- .with('inferred', () => fromDiscussion('via message in', '(inferred)'))- .otherwise(() => fromDiscussion('via @mention in'))+ agentLead+ ? fromDiscussion(agentLead('Asked'))+ : match(attribute(trigger, 'addressed_by'))+ .with('explicit_reply', () => fromDiscussion('via reply in'))+ .with('inferred', () =>+ fromDiscussion('via message in', '(inferred)')+ )+ .otherwise(() => fromDiscussion('via @mention in'))).with('conversation', () => fromDiscussion('via message in')).with('task_assigned', () => {diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 834ef6da0e..fe321da710 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -35651,6 +35651,17 @@"$ref": "#/components/schemas/ChannelSender","description": "Actor that patched the message."},+ "completed_reply": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MessagePostedMetadata",+ "description": "Completed bot answer, evaluated for agent triggers like a new post.\nOrdinary edits and streaming updates omit this; older producers remain\ncompatible with the trigger consumer."+ }+ ]+ },"content": {"type": "string","description": "Macro Markdown body after the patch."diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 3e41aedaeb..6d35c909bd 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -123,6 +123,7 @@ fn open_command() -> OpenSession {/// Why the agent was called, as a trigger event carries it.fn trigger() -> TriggerContext {TriggerContext::Mentioned(DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: Uuid::from_u128(0xf0),name: Some("eng".to_owned()),diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rsindex 07816c8029..5a8166322e 100644--- a/crates/agent_harness/src/domain/trigger_router.rs+++ b/crates/agent_harness/src/domain/trigger_router.rs@@ -34,8 +34,8 @@ pub enum Skipped {/// The event is another deployment's to act on: an open for a bot whose/// runtime opens its own sessions, or managed traffic that is not ours.ForeignBot,- /// The sender is not a user, so there is nobody to own the session.- NotFromUser,+ /// Neither a user sender nor trusted bot attribution names a session owner.+ MissingInvokingUser,/// An event shape this harness does not recognise yet - the trigger's/// vocabulary is non-exhaustive on purpose, and unknown shapes are/// skipped rather than wedging the partition.@@ -71,7 +71,7 @@ pub fn route_agent_trigger(.sender.as_user().cloned()- .ok_or(Skipped::NotFromUser)?;+ .ok_or(Skipped::MissingInvokingUser)?;let mut context = event.context;links.link_context_attachments(context.as_mut());let attachments =@@ -132,10 +132,8 @@ pub fn route_agent_trigger(return Err(Skipped::ForeignBot);};let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;+ .invoking_user()+ .ok_or(Skipped::MissingInvokingUser)?;links.link_context_attachments(context.as_mut());let attachments = links.prompt_attachments_for(&message.attachments, context.as_ref());Ok(RoutedTrigger::Command(@@ -169,6 +167,7 @@ pub fn route_agent_trigger(else {return Err(Skipped::Unrecognized);};+ let sender = message.invoking_user();let origin = AnnounceOrigin {reply_placement: Default::default(),reuse_origin_message: false,@@ -189,17 +188,13 @@ pub fn route_agent_trigger(context,..DeliverAction::prompt(AgentAction::prompt_with_attachments(message.content, attachments),- message.sender.as_user().cloned(),+ sender.clone(),Some(origin),)}),));}- let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;+ let sender = sender.ok_or(Skipped::MissingInvokingUser)?;Ok(RoutedTrigger::Announce(session_id,AnnouncePrompt {diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 2a28660ba2..87a03c7b28 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -183,7 +183,7 @@ fn an_unresolved_existing_session_is_treated_as_external() {}#[test]-fn a_bot_authored_mention_is_skipped() {+fn an_unattributed_bot_mention_is_skipped() {assert_eq!(route_agent_trigger(mentioned(BotId::TEST_A, ChannelSender::new_from_bot(BotId::TEST_B)),@@ -191,7 +191,7 @@ fn a_bot_authored_mention_is_skipped() {&links(),).unwrap_err(),- Skipped::NotFromUser+ Skipped::MissingInvokingUser);}@@ -265,7 +265,7 @@ fn an_external_channel_message_announces_only() {}#[test]-fn a_bot_authored_external_channel_message_is_skipped() {+fn an_unattributed_bot_external_channel_message_is_skipped() {let event = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(ChannelEventMetadata {bot_id: BotId::TEST_A,@@ -277,7 +277,7 @@ fn a_bot_authored_external_channel_message_is_skipped() {));assert_eq!(route_agent_trigger(event, runtime(AgentKind::External), &links()).unwrap_err(),- Skipped::NotFromUser+ Skipped::MissingInvokingUser);}@@ -413,6 +413,7 @@ fn a_managed_follow_up_carries_its_context_to_delivery() {let context = TriggerContext::FollowUp(FollowUpContext {addressed_by: AddressedBy::Inferred,discussion: DiscussionContext {+ agent_request: None,surface: DiscussionSurface::DocumentComment {id: "doc".to_owned(),name: "Spec".to_owned(),@@ -601,6 +602,7 @@ fn image_attachment(entity_id: &str) -> ContextAttachment {/// A mention whose own message has no files, on a thread whose root does.fn thread_root_image_context(root_file: &str) -> TriggerContext {TriggerContext::Mentioned(DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: Uuid::from_u128(1),name: Some("eng".to_owned()),@@ -858,3 +860,52 @@ fn a_conversation_message_without_files_still_carries_the_thread_root_image() {]);}++#[test]+fn attributed_bot_mentions_keep_the_user_for_open_and_follow_up() {+ for (source, target, kind) in [+ (+ bot_id::MACRO_NEW_BOT_ID,+ bot_id::CURSOR_BOT_ID,+ AgentKind::Cursor,+ ),+ (+ bot_id::CURSOR_BOT_ID,+ bot_id::MACRO_NEW_BOT_ID,+ AgentKind::InMemory,+ ),+ ] {+ let mut posted = message(ChannelSender::new_from_bot(source));+ posted.triggered_by = Some(user().to_string());+ let open = AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(+ AgentBotMentionedEvent {+ bot_id: target,+ message: posted.clone(),+ context: None,+ },+ ));+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =+ route_agent_trigger(open, runtime(kind), &links()).unwrap()+ else {+ panic!("expected an open");+ };+ assert_eq!(open.bot_id, target);+ assert_eq!(mention_origin(&open).sender, user());+ let follow_up = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(+ ChannelEventMetadata {+ bot_id: target,+ session_id: AgentSessionId::TEST_A,+ kind: ThreadMessageKind::MentionThread,+ message: posted,+ context: None,+ },+ ));+ let RoutedTrigger::Command(id, HarnessCommand::Deliver(deliver)) =+ route_agent_trigger(follow_up, runtime(kind), &links()).unwrap()+ else {+ panic!("expected a follow-up");+ };+ assert_eq!(id, AgentSessionId::TEST_A);+ assert_eq!(deliver.actor, Some(user()));+ }+}diff --git a/crates/agent_trigger/AGENTS.md b/crates/agent_trigger/AGENTS.mdindex 8d7bdb1a6b..112cdb03cc 100644--- a/crates/agent_trigger/AGENTS.md+++ b/crates/agent_trigger/AGENTS.md@@ -51,6 +51,11 @@ session that results.- A new trigger variant must also be taught to `crates/webhook` ingestionand the SSE fan-out, or it will be silently dropped end to end.+- Attributed bot messages (`MessagePostedMetadata::invoking_user`) trigger+ exactly like human ones: explicit, reply-target and inferred. The agent hop+ limit (`messages::domain::agent_hops`) is the loop guard and runs before any+ routing or judge call; a bot's message never targets its own bot's session.+ Unattributed bot posts trigger nothing.## Relateddiff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rsindex 1fcbc08283..53f3d96675 100644--- a/crates/agent_trigger/src/domain/broker_events/test.rs+++ b/crates/agent_trigger/src/domain/broker_events/test.rs@@ -378,6 +378,7 @@ fn a_conversation_turn_carries_its_trigger_without_the_channel() {email: None,};let discussion = trigger_context::DiscussionContext {+ agent_request: None,surface: trigger_context::DiscussionSurface::Channel {id: Uuid::from_u128(1),name: None,diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rsindex 0ed1794169..bcfc0af099 100644--- a/crates/agent_trigger/src/domain/service.rs+++ b/crates/agent_trigger/src/domain/service.rs@@ -21,15 +21,15 @@ use messages::domain::service::MessageWrite;use messages::domain::{events::MessagePostedMetadata, models::MessageParent};use channel_sender::ChannelSender;-use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use crate::domain::broker_events::{ThreadMessageKind, TriggerDecision};use crate::domain::thread_window::{ThreadMessage, render_transcript, thread_window};use crate::domain::yield_event::{- AgentSessionEventDecision, NoEventReason, PotentialTriggerEvent, yield_event,+ AgentSessionEventDecision, NoEventReason, PotentialTriggerEvent, is_own_message, yield_event,};+use messages::domain::agent_hops::{MAX_AGENT_HOPS, agent_hops};/// Messages kept either side of a point where the agent spoke or was spoken to./// Wide enough to carry the exchange around it, narrow enough that a long@@ -241,7 +241,7 @@ whereposted: &MessagePostedMetadata,bot_id: BotId,) -> Result<bool> {- let Some(caller) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {+ let Some(caller) = posted.invoking_user() else {return Ok(false);};@@ -353,14 +353,14 @@ where}}- /// The poster's current capability on the message's conversation, for- /// reading it as context. `None` when the poster is no user or may no+ /// The invoking user's current capability on the message's conversation,+ /// for reading it as context. `None` when nobody invoked it or they may no/// longer write there.pub async fn invocation(&self,posted: &MessagePostedMetadata,) -> Result<Option<AuthorizedInvocation>> {- let Some(user) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {+ let Some(user) = posted.invoking_user() else {return Ok(None);};self.history@@ -368,6 +368,40 @@ where.await}+ /// Whether a bot's message stays within [`MAX_AGENT_HOPS`] of the last+ /// person in its thread. Checked before any routing or judging, explicit+ /// or implicit. An unreadable thread counts as over the limit: an agent+ /// loop is worse than one missed handoff.+ async fn within_hop_limit(+ &self,+ posted: &MessagePostedMetadata,+ invocation: &AuthorizedInvocation,+ ) -> bool {+ let messages = match self.history.thread_messages(invocation).await {+ Ok(messages) => messages,+ Err(error) => {+ tracing::warn!(error = ?error, "thread read failed; not counting agent hops");+ return false;+ }+ };+ let senders: Vec<&ChannelSender<'static>> = messages+ .iter()+ .take_while(|message| message.id != posted.message_id)+ .map(|message| &message.sender)+ .chain(std::iter::once(&posted.sender))+ .collect();+ let hops = agent_hops(senders.into_iter());+ if hops > MAX_AGENT_HOPS {+ tracing::info!(+ message_id = %posted.message_id,+ hops,+ "agent message exceeds the hop limit; not triggering another agent"+ );+ return false;+ }+ true+ }+/// Evaluates a posted message for every mentioned bot.#[tracing::instrument(err, skip(self, posted), fields(parent = ?posted.parent,@@ -377,7 +411,7 @@ whereagent.mention.bot_count = tracing::field::Empty,))]pub async fn evaluate(&self, posted: &MessagePostedMetadata) -> Result<Vec<TriggerDecision>> {- let Some(user) = posted.sender.as_user().cloned().map(CowLike::into_owned) else {+ let Some(user) = posted.invoking_user() else {return Ok(Vec::new());};let Some(invocation) = self@@ -387,6 +421,9 @@ whereelse {return Ok(Vec::new());};+ if posted.sender.as_bot().is_some() && !self.within_hop_limit(posted, &invocation).await {+ return Ok(Vec::new());+ }if let Some(router) = &self.conversations {match router.evaluate(posted).await? {ConversationDecision::NotConversation => {}@@ -411,7 +448,7 @@ whereif mentioned.is_empty() {if let Some(event) = self.evaluate_bot(posted, None, &mut seen_sessions).await? {events.push(event);- } else if let Some(event) = self.evaluate_implicit(posted, &invocation).await? {+ } else if let Some(event) = self.evaluate_implicit(posted, &user, &invocation).await? {events.push(event);}return Ok(events);@@ -507,23 +544,23 @@ where/// Extractor and judge failures are treated as "no" rather than propagated:/// implicit triggering is best-effort, and an outage must not wedge the/// message stream or fabricate forwards.+ ///+ /// A bot's message is judged like anyone's, but never against the bot's+ /// own session; the hop limit has already bounded agent chains.async fn evaluate_implicit(&self,posted: &MessagePostedMetadata,+ _user: &MacroUserIdStr<'static>,invocation: &AuthorizedInvocation,) -> Result<Option<TriggerDecision>> {let Some(thread_id) = posted.thread_id else {return Ok(None);};- // Only a user implicitly addresses an agent; bot traffic must always- // mention explicitly, or bots would relay each other forever.- let Some(_user) = posted.sender.as_user() else {- return Ok(None);- };let mut candidates = Vec::new();for session in self.sessions.find_all_for_thread(thread_id).await? {if session.thread_parent.as_ref() == Some(&posted.parent)&& session.thread_id == Some(thread_id)+ && !is_own_message(session.bot_id, &posted.sender)&& self.agent_is_available(posted, session.bot_id).await?{candidates.push(session);diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 39f6a51c4a..4d8569f382 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -315,7 +315,7 @@ async fn a_private_global_agent_is_unavailable_to_another_user() {}#[tokio::test]-async fn a_bot_authored_mention_cannot_trigger_an_agent() {+async fn an_unattributed_bot_mention_cannot_trigger_an_agent() {let mut posted = message(vec![mention_of(BotId::TEST_A)]);posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);let (replies, judge) = no_implicit();@@ -1308,3 +1308,273 @@ async fn a_crm_discussion_cannot_invoke_another_users_private_agent() {assert!(!mention_yields_event(&posted, bots).await);}}++#[tokio::test]+async fn attributed_bot_mentions_open_or_resume_the_target_session() {+ for (source, target) in [+ (bot_id::MACRO_NEW_BOT_ID, bot_id::CURSOR_BOT_ID),+ (bot_id::CURSOR_BOT_ID, bot_id::MACRO_NEW_BOT_ID),+ (BotId::TEST_A, bot_id::MACRO_NEW_BOT_ID),+ ] {+ for existing in [false, true] {+ let mut posted = message(vec![mention_of(target)]);+ posted.sender = ChannelSender::new_from_bot(source);+ posted.triggered_by = Some(user().to_string());+ let mut sessions = MockAgentSessionRepo::new();+ let id = AgentSessionId::TEST_A;+ sessions+ .expect_find_for_thread()+ .once()+ .returning(move |thread, bot| {+ assert_eq!(thread, Some(Uuid::from_u128(3)));+ assert_eq!(bot, Some(target));+ Box::pin(async move {+ Ok(if existing {+ ThreadSession::CreatedFromThread(thread_session(id, target))+ } else {+ ThreadSession::None+ })+ })+ });+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .returning(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot()+ .returning(|bot| Box::pin(async move { Ok(Some(system_bot(bot))) }));+ let mut history = MockThreadHistory::new();+ history+ .expect_authorize_invocation()+ .once()+ .returning(|actor, parent, root| {+ assert_eq!(actor, &user());+ allow_invocation(actor, parent, root)+ });+ history+ .expect_thread_messages()+ .once()+ .returning(|_| Box::pin(async { Ok(vec![]) }));+ let (replies, judge) = no_implicit();+ let events = service_reading(sessions, bots, replies, judge, history)+ .evaluate(&posted)+ .await+ .unwrap();+ assert_eq!(+ events,+ vec![if existing {+ TriggerDecision::Existing {+ bot_id: target,+ session_id: id,+ kind: ThreadMessageKind::MentionThread,+ message: posted,+ }+ } else {+ TriggerDecision::Open {+ bot_id: target,+ message: posted,+ }+ }]+ );+ }+ }+}++#[tokio::test]+async fn attributed_bots_cannot_bypass_access_or_trigger_themselves() {+ let mut posted = message(vec![mention_of(BotId::TEST_A)]);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);+ posted.triggered_by = Some(user().to_string());+ let mut history = MockThreadHistory::new();+ history+ .expect_authorize_invocation()+ .once()+ .returning(|_, _, _| Box::pin(async { Ok(None) }));+ let (replies, judge) = no_implicit();+ assert!(+ service_reading(+ MockAgentSessionRepo::new(),+ MockAgentBotLookup::new(),+ replies,+ judge,+ history+ )+ .evaluate(&posted)+ .await+ .unwrap()+ .is_empty()+ );++ for (source, actor) in [+ (BotId::TEST_A, user().to_string()),+ (BotId::TEST_B, "macro|[email protected]".into()),+ ] {+ posted.sender = ChannelSender::new_from_bot(source);+ posted.triggered_by = Some(actor);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .returning(|bot| Box::pin(async move { Ok(Some(private_agent(bot))) }));+ assert!(!mention_yields_event(&posted, bots).await);+ }+}++#[tokio::test]+async fn unattributed_bot_messages_do_not_trigger() {+ for (attribution, mentions) in [+ (None, vec![mention_of(BotId::TEST_A)]),+ (None, vec![]),+ (Some("invalid".to_owned()), vec![mention_of(BotId::TEST_A)]),+ ] {+ let mut posted = message(mentions);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);+ posted.triggered_by = attribution;+ let (replies, judge) = no_implicit();+ assert!(+ service_reading(+ MockAgentSessionRepo::new(),+ MockAgentBotLookup::new(),+ replies,+ judge,+ MockThreadHistory::new()+ )+ .evaluate(&posted)+ .await+ .unwrap()+ .is_empty()+ );+ }+}++#[tokio::test]+async fn agents_mentioning_each_other_stop_at_the_hop_limit_without_a_person() {+ let macro_ai = ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);+ let cursor = ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ // The agent posting hop `n`, alternating from Macro's first handoff.+ let agent = |n: usize| {+ if n % 2 == 1 {+ (macro_ai.clone(), bot_id::CURSOR_BOT_ID)+ } else {+ (cursor.clone(), bot_id::MACRO_NEW_BOT_ID)+ }+ };+ let thread: Vec<ThreadMessage> = std::iter::once(thread_message(+ 100,+ ChannelSender::new_from_user(user()),+ "@macro go",+ ))+ .chain((1..=MAX_AGENT_HOPS).map(|n| thread_message(100 + n as u128, agent(n).0, "over to you")))+ .collect();+ for (hop, triggers) in [(MAX_AGENT_HOPS, true), (MAX_AGENT_HOPS + 1, false)] {+ let (sender, target) = agent(hop);+ let read = hop;+ let mut posted = message(vec![mention_of(target)]);+ posted.sender = sender;+ posted.triggered_by = Some(user().to_string());+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .returning(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot()+ .returning(|bot| Box::pin(async move { Ok(Some(system_bot(bot))) }));+ let (replies, judge) = no_implicit();+ let sessions = if triggers {+ sessions_without_existing()+ } else {+ MockAgentSessionRepo::new()+ };+ let events = service_reading(+ sessions,+ bots,+ replies,+ judge,+ thread_of(thread[..read].to_vec()),+ )+ .evaluate(&posted)+ .await+ .unwrap();+ assert_eq!(!events.is_empty(), triggers, "hop {hop}");+ }+}++#[tokio::test]+async fn an_agents_unmentioned_follow_up_reaches_another_agents_session() {+ for (replies, judge, kind) in [+ (+ extractor(Ok(None)),+ judge_saying(Ok(true)),+ ThreadMessageKind::Inferred,+ ),+ (+ extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),+ MockImplicitTriggerJudge::new(),+ ThreadMessageKind::ExplicitReply,+ ),+ ] {+ let mut posted = message(vec![]);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);+ posted.triggered_by = Some(user().to_string());+ let sessions = implicit_sessions(vec![+ thread_session(AgentSessionId::TEST_A, BotId::TEST_A),+ thread_session(AgentSessionId::TEST_B, BotId::TEST_B),+ ]);++ let events = service(sessions, agent_bots(), replies, judge)+ .evaluate(&posted)+ .await+ .unwrap();++ let metadata = existing_channel_metadata(&events);+ assert_eq!(metadata.bot_id, BotId::TEST_A);+ assert_eq!(metadata.session_id, AgentSessionId::TEST_A);+ assert_eq!(metadata.kind, kind);+ }+}++#[tokio::test]+async fn an_agent_never_infers_into_its_own_session() {+ let mut posted = message(vec![]);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_A);+ posted.triggered_by = Some(user().to_string());+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let (replies, judge) = no_implicit();++ let events = service(sessions, agent_bots(), replies, judge)+ .evaluate(&posted)+ .await+ .unwrap();++ assert!(events.is_empty());+}++#[tokio::test]+async fn an_inferred_agent_chain_stops_at_the_hop_limit_before_judging() {+ let agent = |n: usize| {+ ChannelSender::new_from_bot(if n % 2 == 1 {+ BotId::TEST_A+ } else {+ BotId::TEST_B+ })+ };+ let thread: Vec<ThreadMessage> = std::iter::once(thread_message(+ 100,+ ChannelSender::new_from_user(user()),+ "work it out between you",+ ))+ .chain((1..=MAX_AGENT_HOPS).map(|n| thread_message(100 + n as u128, agent(n), "your turn")))+ .collect();+ let mut posted = message(vec![]);+ posted.sender = agent(MAX_AGENT_HOPS + 1);+ posted.triggered_by = Some(user().to_string());+ let (replies, judge) = no_implicit();++ let events = service_reading(+ MockAgentSessionRepo::new(),+ MockAgentBotLookup::new(),+ replies,+ judge,+ thread_of(thread),+ )+ .evaluate(&posted)+ .await+ .unwrap();++ assert!(events.is_empty());+}diff --git a/crates/agent_trigger/src/domain/sources.rs b/crates/agent_trigger/src/domain/sources.rsindex dff75cfd84..6bdf7fd609 100644--- a/crates/agent_trigger/src/domain/sources.rs+++ b/crates/agent_trigger/src/domain/sources.rs@@ -3,7 +3,8 @@//!//! `message.posted` on `macro.messages` is the source of record: it carries the//! persisted parent, so a mention in a document discussion routes like one in a-//! channel. The consumer also reads property changes for task assignments,+//! channel. Finalized bot replies carry the same candidate on their edit event.+//! The consumer also reads property changes for task assignments,//! including a task joining a project through its Project property.#[cfg(test)]@@ -56,7 +57,13 @@ impl TriggerEvents for MessageTriggerEvents {channel_type: None,}),),- MessageTopicEvent::Patched(_) => ("message.patched", None),+ MessageTopicEvent::Patched(patched) => (+ "message.patched",+ patched.completed_reply.clone().map(|posted| TriggerInput {+ posted,+ channel_type: None,+ }),+ ),MessageTopicEvent::Deleted(_) => ("message.deleted", None),MessageTopicEvent::Mentioned(_) => ("message.mentioned", None),MessageTopicEvent::AttachmentCreated(_) => ("message.attachment_created", None),diff --git a/crates/agent_trigger/src/domain/sources/test.rs b/crates/agent_trigger/src/domain/sources/test.rsindex 20a78af829..6351094de1 100644--- a/crates/agent_trigger/src/domain/sources/test.rs+++ b/crates/agent_trigger/src/domain/sources/test.rs@@ -67,6 +67,7 @@ fn the_message_source_carries_the_persisted_parent_through() {);let patched = MessageMacroEvent::patched(messages::domain::events::MessagePatchedMetadata {+ completed_reply: None,parent: MessageParent::parse("document", "doc-1").unwrap(),message_id: Uuid::from_u128(2),thread_id: None,@@ -129,3 +130,48 @@ fn a_task_joining_a_project_decodes_as_a_project_addition() {assert!(decoded.assignment.is_none());assert!(decoded.posted.is_none());}++#[test]+fn completed_bot_reply_mentions_reach_the_existing_trigger_path() {+ let posted = MessagePostedMetadata {+ parent: MessageParent::Channel(Uuid::from_u128(1)),+ message_id: Uuid::from_u128(2),+ thread_id: Some(Uuid::from_u128(3)),+ root_id: Uuid::from_u128(3),+ sender: ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID),+ triggered_by: Some(sender().as_ref().to_owned()),+ content: "handoff".into(),+ mentions: vec![messages::domain::models::SimpleMention {+ entity_type: "bot".into(),+ entity_id: bot_id::CURSOR_BOT_ID.into_storage_id().to_string(),+ }],+ attachments: vec![],+ created_at: Utc::now(),+ };+ let patched = MessageMacroEvent::patched(messages::domain::events::MessagePatchedMetadata {+ completed_reply: Some(posted.clone()),+ parent: posted.parent.clone(),+ message_id: posted.message_id,+ thread_id: posted.thread_id,+ root_id: posted.root_id,+ actor: posted.sender.clone(),+ content: posted.content.clone(),+ edited_at: None,+ updated_at: Utc::now(),+ });+ let trigger = MessageTriggerEvents::decode(&record(&patched))+ .unwrap()+ .into_trigger();+ assert_eq!(trigger.posted.unwrap().posted, posted);++ let mut old_payload = serde_json::to_value(&patched.event().event).unwrap();+ old_payload["metadata"]+ .as_object_mut()+ .unwrap()+ .remove("completed_reply");+ let older: messages::outbound::broker::MessageTopicEvent =+ serde_json::from_value(old_payload).unwrap();+ assert!(+ matches!(older, messages::outbound::broker::MessageTopicEvent::Patched(p) if p.completed_reply.is_none())+ );+}diff --git a/crates/agent_trigger/src/outbound/discussion_context.rs b/crates/agent_trigger/src/outbound/discussion_context.rsindex 0ee0bcee29..b8eecb9657 100644--- a/crates/agent_trigger/src/outbound/discussion_context.rs+++ b/crates/agent_trigger/src/outbound/discussion_context.rs@@ -16,6 +16,7 @@ use initiative::domain::{lookup::InitiativeReader, models::InitiativeId};use lexical_client::LexicalClient;use lexical_client::parse_markdown::ExtractedExplicitReply;use macro_uuid::Uuid;+use messages::domain::agent_hops::agent_hops;use messages::domain::{api::MessageReader,events::MessagePostedMetadata,@@ -24,8 +25,8 @@ use messages::domain::{service::MessageView,};use trigger_context::{- ChannelType, CommentAnchor, ContextAttachment, ContextMessage, ContextPerson, ContextThread,- DiscussionContext, DiscussionSurface, MarkedPassage, ReplyTarget,+ AgentRequest, ChannelType, CommentAnchor, ContextAttachment, ContextMessage, ContextPerson,+ ContextThread, DiscussionContext, DiscussionSurface, MarkedPassage, ReplyTarget,};use crate::domain::{@@ -321,6 +322,20 @@ where}let quoted = quote.as_ref().and_then(|quote| quote.message.as_ref());+ let on_behalf_of = prompt.sender_id.as_bot().and(prompt.triggered_by.clone());+ let hops = match &discussion {+ Some(discussion) => agent_hops(+ std::iter::once(&discussion.root)+ .chain(&discussion.replies)+ .take_while(|message| message.id != prompt.id)+ .chain(std::iter::once(&prompt))+ .map(|message| &message.sender_id)+ .collect::<Vec<_>>()+ .into_iter(),+ ),+ None => agent_hops(std::iter::once(&prompt.sender_id)),+ };+let authors: Vec<&Message> = std::iter::once(&prompt).chain(thread@@ -334,7 +349,9 @@ where).chain(quoted).collect();- let people = self.people_of(&authors).await?;+ let people = self+ .people_of(&authors, on_behalf_of.iter().cloned())+ .await?;let reply_target = match quote {Some(quote) => ReplyTarget::Quote {@@ -353,6 +370,10 @@ wheresurface: surface(parent, name, anchor)?,prompt_message_id: prompt.id,sender: people.author(&prompt),+ agent_request: on_behalf_of.map(|id| AgentRequest {+ on_behalf_of: people.person(id),+ hops,+ }),reply_target,thread: thread.map(|thread| people.thread(thread)),channel: channel@@ -365,12 +386,18 @@ whereimpl<People: PeopleDirectory, Names, Lexical> MessageDiscussionReader<People, Names, Lexical> {/// Everyone who wrote one of `messages`, named once each.- async fn people_of(&self, messages: &[&Message]) -> Result<Authors> {+ async fn people_of(+ &self,+ messages: &[&Message],+ others: impl Iterator<Item = String>,+ ) -> Result<Authors> {let mut ids: Vec<String> = Vec::new();- for message in messages {- if let Some(id) = directory_id(message)- && !ids.contains(&id)- {+ for id in messages+ .iter()+ .filter_map(|message| directory_id(message))+ .chain(others)+ {+ if !ids.contains(&id) {ids.push(id);}}@@ -651,7 +678,11 @@ impl Authors {email: None,};}- // Every author was named before any message is built.+ self.person(id)+ }++ /// A person by directory id. Everyone was named before any message is built.+ fn person(&self, id: String) -> ContextPerson {self.0.get(&id).cloned().unwrap_or(ContextPerson {name: id.clone(),id,diff --git a/crates/agent_trigger/src/outbound/discussion_context/test.rs b/crates/agent_trigger/src/outbound/discussion_context/test.rsindex c530d556a3..f140a03890 100644--- a/crates/agent_trigger/src/outbound/discussion_context/test.rs+++ b/crates/agent_trigger/src/outbound/discussion_context/test.rs@@ -260,6 +260,7 @@ async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {assert_eq!(context,DiscussionContext {+ agent_request: None,// An unanchored discussion names no place in the document.surface: DiscussionSurface::DocumentComment {id: "doc".to_owned(),@@ -441,6 +442,7 @@ async fn a_channel_thread_reply_is_about_its_thread_not_the_latest_message() {assert_eq!(context,DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: Uuid::from_u128(3),name: Some("eng".to_owned()),@@ -1181,3 +1183,43 @@ async fn design_discussions_reach_the_agent_unanchored() {);assert!(context.thread.is_some());}++#[tokio::test]+async fn an_agent_asking_for_a_person_names_them_and_counts_its_hop() {+ let parent = document();+ let root = posted(&parent, 1, None, "[email protected]", "@Macro fix this", 0);+ let by_bot = |id: u128, bot: bot_id::BotId, name: &str, content: &str, minute: i64| Message {+ sender_id: channel_sender::ChannelSender::new_from_bot(bot),+ triggered_by: Some(actor().as_ref().to_owned()),+ bot_profile: Some(BotSenderProfile {+ name: name.to_owned(),+ avatar_url: None,+ }),+ ..posted(&parent, id, Some(1), "[email protected]", content, minute)+ };+ let macro_reply = by_bot(2, bot_id::MACRO_NEW_BOT_ID, "Macro", "@Cursor fix it", 1);+ let prompt = by_bot(3, bot_id::CURSOR_BOT_ID, "Cursor", "@Macro done, check", 2);++ let mut source = MockMessageReader::new();+ let prompt_message = prompt.clone();+ source+ .expect_get()+ .returning(move |_, _| Ok(prompt_message.clone()));+ source.expect_preceding().never();+ let replies = vec![macro_reply, prompt.clone()];+ source+ .expect_get_thread()+ .once()+ .return_once(move |_, _| Ok(discussion(root, replies, None)));++ let context = context_from(source, document_names(), Lexical::none(), &prompt).await;++ assert_eq!(context.sender.name, "Cursor");+ assert_eq!(+ context.agent_request,+ Some(AgentRequest {+ on_behalf_of: person("[email protected]"),+ hops: 2,+ })+ );+}diff --git a/crates/agent_trigger/src/outbound/fast_model_judge.rs b/crates/agent_trigger/src/outbound/fast_model_judge.rsindex d258417f17..cf0e47f8db 100644--- a/crates/agent_trigger/src/outbound/fast_model_judge.rs+++ b/crates/agent_trigger/src/outbound/fast_model_judge.rs@@ -50,7 +50,7 @@ struct JudgeOutput {}/// Judges implicit triggers with [`PredefinedModel::Fast`], recording token-/// usage against the message's sender.+/// usage against the user the message invokes for.pub struct FastModelTriggerJudge {model: PredefinedModel,recorder: Arc<dyn UsageRecorder>,@@ -77,7 +77,7 @@ impl ImplicitTriggerJudge for FastModelTriggerJudge {posted: &MessagePostedMetadata,transcript: &str,) -> Result<bool> {- let Some(user) = posted.sender.as_user() else {+ let Some(user) = posted.invoking_user() else {return Ok(false);};let schema = DynamicSchema {@@ -101,7 +101,7 @@ impl ImplicitTriggerJudge for FastModelTriggerJudge {}}),};- let ctx = UsageContext::new(AiFeature::Automation, user.clone());+ let ctx = UsageContext::new(AiFeature::Automation, user);let blurbs =blurbs_for_attachments(self.images.as_ref(), &posted.attachments, ctx.clone()).await;diff --git a/crates/channel_bots/AGENTS.md b/crates/channel_bots/AGENTS.mdindex 80e3f8a8c1..57e79c9fb4 100644--- a/crates/channel_bots/AGENTS.md+++ b/crates/channel_bots/AGENTS.md@@ -46,6 +46,9 @@ decides whether to trigger, authorizes, and delivers a reply.- Implicit (non-mention) triggers go through the fast-model classifier, not themain agent model — keep that path cheap; it runs on every message.+- Attributed bot messages trigger like human ones (mention or inferred), never+ Macro AI's own; `messages::domain::agent_hops::MAX_AGENT_HOPS` is checked+ first, before any classifier call. Unattributed bot posts trigger nothing.## Relateddiff --git a/crates/channel_bots/src/domain/models.rs b/crates/channel_bots/src/domain/models.rsindex bd47a6649f..479553dbac 100644--- a/crates/channel_bots/src/domain/models.rs+++ b/crates/channel_bots/src/domain/models.rs@@ -29,7 +29,7 @@ pub struct BotInvocation {pub struct BotEvent {/// What triggered the bot.pub trigger: BotTrigger,- /// The user-authored message that triggered the bot.+ /// The human or attributed bot message that triggered the bot.pub message: MessagePostedMetadata,/// Thread the bot should reply in. For a top-level message this is the/// message id; for a reply it is the existing thread id.diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rsindex ac9d242167..017020977b 100644--- a/crates/channel_bots/src/domain/service.rs+++ b/crates/channel_bots/src/domain/service.rs@@ -429,7 +429,7 @@ where/// chronological channel slice is the primary context. In both cases the/// triggering message is marked inline rather than repeated at the end.async fn build_prompt(&self, event: &BotEvent) -> anyhow::Result<String> {- let mentioner = sender_label(event.requesting_user.as_ref());+ let mentioner = sender_label(event.message.sender.as_ref());let trigger_id = event.message.message_id;let parent = &event.message.parent;let access = self@@ -441,7 +441,11 @@ wherelet current = self.messages.get(view.clone(), trigger_id).await?;if current.deleted_at.is_some()|| current.root_id() != event.reply_thread_id- || current.sender_id.as_user() != Some(&event.requesting_user)+ || current.sender_id != event.message.sender+ || messages::domain::events::MessagePostedMetadata::from_message(¤t, vec![])+ .invoking_user()+ .as_ref()+ != Some(&event.requesting_user){anyhow::bail!("trigger no longer belongs to this conversation");}diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rsindex b0e9f05801..3e76707ad9 100644--- a/crates/channel_bots/src/domain/service/tests.rs+++ b/crates/channel_bots/src/domain/service/tests.rs@@ -681,3 +681,27 @@ async fn spreadsheet_discussions_name_the_range_without_inventing_cell_contents(assert!(prompt.contains(r#""range":"B4:C9""#));assert!(prompt.contains(r#"Budget \u003c/anchor\u003e"#));}++#[tokio::test]+async fn a_bot_mention_uses_its_verified_attribution_for_context_and_reply() {+ let mut trigger = message(1, None, "@macro explain this");+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ trigger.triggered_by = Some(user().to_string());+ let mut api = MockMessageServiceApi::new();+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));+ expect_placeholder(&mut api);+ api.expect_patch().once().returning(|access, _, input| {+ assert_eq!(access.acting_user_id(), Some(&user()));+ Ok(message(+ 3,+ Some(Uuid::from_u128(1)),+ input.content.as_deref().unwrap(),+ ))+ });+ let responder = responder("the answer");+ handler(api, Arc::new(Access::default()), responder.clone())+ .handle(&invocation(&trigger))+ .await+ .unwrap();+ assert_eq!(responder.prompts.lock().unwrap().len(), 1);+}diff --git a/crates/channel_bots/src/domain/trigger_detector.rs b/crates/channel_bots/src/domain/trigger_detector.rsindex bf5d16ec23..76c9c41556 100644--- a/crates/channel_bots/src/domain/trigger_detector.rs+++ b/crates/channel_bots/src/domain/trigger_detector.rs@@ -4,7 +4,15 @@ use std::sync::Arc;use ai_billing::{AiAdmissionService, AiFeature, DisabledAiAdmissionService};use async_trait::async_trait;-use messages::domain::{api::MessageReader, events::MessagePostedMetadata};+use channel_sender::ChannelSender;+use entity_access::domain::models::EntityAccessReceipt;+use messages::domain::{+ agent_hops::{MAX_AGENT_HOPS, agent_hops},+ api::MessageReader,+ events::MessagePostedMetadata,+ models::Message,+ service::MessageWrite,+};use uuid::Uuid;use super::models::{BotInvocation, BotTrigger, TranscriptMessage};@@ -21,8 +29,9 @@ use super::sender_label;/// * 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.+/// Attributed bot messages trigger like a person's, within the agent hop+/// limit and never their own bot; unattributed bot messages trigger nothing.+/// Classifier failures resolve to no trigger.pub struct MentionOrInferredDetector<I> {messages: Arc<dyn MessageReader>,access: Arc<dyn ConversationAccess>,@@ -63,12 +72,11 @@ whereparent_id: Uuid,) -> anyhow::Result<Vec<TranscriptMessage>> {let user = candidate- .sender- .as_user()- .ok_or_else(|| anyhow::anyhow!("only users invoke agents"))?;+ .invoking_user()+ .ok_or_else(|| anyhow::anyhow!("nobody invoked this message"))?;let access = self.access- .user_write(user, &candidate.parent)+ .user_write(&user, &candidate.parent).await.map_err(|e| anyhow::anyhow!(e.to_string()))?;let view = access.try_into_requirement()?;@@ -86,17 +94,57 @@ wherelet mut transcript = Vec::new();for message in std::iter::once(thread.root).chain(thread.replies) {if message.deleted_at.is_none() && !message.content.trim().is_empty() {- transcript.push(transcript_message(- message.sender_id.as_ref(),- &message.content,- ));+ transcript.push(transcript_message(&message));}}Ok(transcript)}+ /// Whether a bot's mention stays within [`MAX_AGENT_HOPS`] of the last+ /// person in its thread. An unreadable thread counts as over the limit.+ async fn within_hop_limit(+ &self,+ candidate: &MessagePostedMetadata,+ access: EntityAccessReceipt<MessageWrite>,+ ) -> bool {+ let thread: anyhow::Result<_> = async {+ let view = access.try_into_requirement()?;+ Ok(self.messages.get_thread(view, candidate.root_id).await?)+ }+ .await;+ let thread = match thread {+ Ok(thread) => thread,+ Err(error) => {+ tracing::warn!(error = ?error, "thread read failed; not counting agent hops");+ return false;+ }+ };+ let senders: Vec<&ChannelSender<'static>> = std::iter::once(&thread.root)+ .chain(&thread.replies)+ .take_while(|message| message.id != candidate.message_id)+ .map(|message| &message.sender_id)+ .chain(std::iter::once(&candidate.sender))+ .collect();+ let hops = agent_hops(senders.into_iter());+ if hops > MAX_AGENT_HOPS {+ tracing::info!(+ message_id = %candidate.message_id,+ hops,+ "bot mention exceeds the agent hop limit; not invoking"+ );+ return false;+ }+ true+ }++ /// Macro AI never infers a reply to its own message.async fn infer(&self, candidate: &MessagePostedMetadata) -> Option<BotInvocation> {- let requesting_user = candidate.sender.as_user()?;+ if candidate.sender.as_bot().map(|sender| sender.bot_id()) == Some(bot_id::MACRO_AI_BOT_ID)+ {+ return None;+ }+ let requesting_user = candidate.invoking_user()?;+ let requesting_user = &requesting_user;let parent_id = candidate.thread_id?;let transcript = self@@ -134,13 +182,18 @@ where}}-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);+/// Macro AI's messages are the agent's; other bots go by their public name.+fn transcript_message(message: &Message) -> TranscriptMessage {+ let from_agent =+ message.sender_id.as_bot().map(|bot| bot.bot_id()) == Some(bot_id::MACRO_AI_BOT_ID);+ let sender = match &message.bot_profile {+ Some(profile) if !from_agent => profile.name.clone(),+ _ => sender_label(message.sender_id.as_ref()),+ };TranscriptMessage {from_agent,- sender: sender_label(sender_id),- content: content.trim().to_string(),+ sender,+ content: message.content.trim().to_string(),}}@@ -150,24 +203,22 @@ whereI: InferredTriggerClassifier,{async fn detect(&self, candidate: &MessagePostedMetadata) -> Vec<BotInvocation> {- if candidate.sender.as_user().is_none() {+ let Some(user) = candidate.invoking_user() else {return Vec::new();- }- let Some(user) = candidate.sender.as_user() else {+ };+ let Ok(access) = self.access.user_write(&user, &candidate.parent).await else {return Vec::new();};- if self- .access- .user_write(user, &candidate.parent)- .await- .is_err()- {+ if candidate.sender.as_bot().is_some() && !self.within_hop_limit(candidate, access).await {return Vec::new();}let mentioned = messages::domain::mentions::bot_mention_ids(&candidate.mentions);if !mentioned.is_empty() {return mentioned.into_iter()+ .filter(|bot_id| {+ candidate.sender.as_bot().map(|sender| sender.bot_id()) != Some(*bot_id)+ }).map(|bot_id| BotInvocation {bot_id,trigger: BotTrigger::Mention,diff --git a/crates/channel_bots/src/domain/trigger_detector/tests.rs b/crates/channel_bots/src/domain/trigger_detector/tests.rsindex be37609fce..216473d255 100644--- a/crates/channel_bots/src/domain/trigger_detector/tests.rs+++ b/crates/channel_bots/src/domain/trigger_detector/tests.rs@@ -73,7 +73,7 @@ async fn document_mention_triggers_each_canonical_bot_once_without_classificatioassert_eq!(admission.calls.load(std::sync::atomic::Ordering::SeqCst), 0);}#[tokio::test]-async fn bot_authored_messages_never_trigger_another_response() {+async fn unattributed_bot_messages_never_trigger_another_response() {let mut trigger = message(1, None, "@macro help");trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);trigger.mentions = vec![SimpleMention {@@ -181,3 +181,205 @@ async fn unavailable_history_cannot_be_replaced_by_an_unverified_event_transcrip);assert!(classifier.calls.lock().unwrap().is_empty());}++#[tokio::test]+async fn attributed_bots_require_an_explicit_other_bot_mention_and_current_access() {+ for (source, mention, revoked, expected) in [+ (bot_id::CURSOR_BOT_ID, true, false, true),+ (bot_id::MACRO_AI_BOT_ID, true, false, false),+ (bot_id::CURSOR_BOT_ID, false, false, false),+ (bot_id::CURSOR_BOT_ID, true, true, false),+ ] {+ let mut trigger = message(2, Some(Uuid::from_u128(1)), "help");+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(source);+ trigger.triggered_by = Some(user().to_string());+ if mention {+ trigger.mentions = vec![SimpleMention {+ entity_type: "bot".into(),+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),+ }];+ }+ let access = Arc::new(Access::default());+ if revoked {+ access.revoke();+ }+ let classifier = classifier(Ok(true));+ let mut api = MockMessageServiceApi::new();+ configure_reads(+ &mut api,+ &trigger,+ thread(message(1, None, "@cursor look"), vec![trigger.clone()]),+ );+ let detector = MentionOrInferredDetector::new(Arc::new(api), access, classifier.clone());+ assert_eq!(+ !detector.detect(&event(&trigger)).await.is_empty(),+ expected+ );+ assert!(classifier.calls.lock().unwrap().is_empty());+ }+}++#[tokio::test]+async fn agents_handing_a_thread_back_and_forth_stop_at_the_hop_limit() {+ let by = |id: u128, bot: bot_id::BotId| {+ let mut reply = message(id, Some(Uuid::from_u128(1)), "over to you");+ reply.sender_id = channel_sender::ChannelSender::new_from_bot(bot);+ reply.triggered_by = Some(user().to_string());+ reply.mentions = vec![SimpleMention {+ entity_type: "bot".into(),+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),+ }];+ reply+ };+ for (hop, expected) in [+ (messages::domain::agent_hops::MAX_AGENT_HOPS, true),+ (messages::domain::agent_hops::MAX_AGENT_HOPS + 1, false),+ ] {+ // Cursor posts hop `hop`; Macro and Cursor alternate before it.+ let mut replies: Vec<_> = (1..hop)+ .map(|n| {+ let bot = if (hop - n) % 2 == 0 {+ bot_id::CURSOR_BOT_ID+ } else {+ bot_id::MACRO_AI_BOT_ID+ };+ by(1 + n as u128, bot)+ })+ .collect();+ let trigger = by(10_000, bot_id::CURSOR_BOT_ID);+ replies.push(trigger.clone());+ let mut api = MockMessageServiceApi::new();+ configure_reads(+ &mut api,+ &trigger,+ thread(message(1, None, "@macro ask cursor"), replies),+ );+ let detector = MentionOrInferredDetector::new(+ Arc::new(api),+ Arc::new(Access::default()),+ classifier(Ok(true)),+ );+ assert_eq!(+ !detector.detect(&event(&trigger)).await.is_empty(),+ expected,+ "hop {hop}"+ );+ }+}++#[tokio::test]+async fn an_agents_follow_up_is_inferred_for_macro_and_labelled_by_its_name() {+ let root = message(1, None, "question");+ let mut answer = message(2, Some(root.id), "previous answer");+ answer.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);+ let mut trigger = message(3, Some(root.id), "Macro, can you double-check this?");+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ trigger.triggered_by = Some(user().to_string());+ trigger.bot_profile = Some(messages::domain::models::BotSenderProfile {+ name: "Cursor".to_owned(),+ avatar_url: None,+ });+ let mut api = MockMessageServiceApi::new();+ configure_reads(+ &mut api,+ &trigger,+ thread(root, vec![answer, trigger.clone()]),+ );+ let classifier = classifier(Ok(true));+ let detector = MentionOrInferredDetector::new(+ Arc::new(api),+ Arc::new(Access::default()),+ classifier.clone(),+ );++ assert_eq!(+ detector.detect(&event(&trigger)).await,+ vec![BotInvocation {+ bot_id: bot_id::MACRO_AI_BOT_ID,+ trigger: BotTrigger::Inferred,+ }]+ );+ let calls = classifier.calls.lock().unwrap();+ let judged = calls[0].last().unwrap();+ assert_eq!(judged.sender, "Cursor");+ assert!(!judged.from_agent);+}++#[tokio::test]+async fn macro_never_infers_a_reply_to_its_own_message() {+ let root = message(1, None, "question");+ let mut answer = message(2, Some(root.id), "previous answer");+ answer.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);+ let mut trigger = message(3, Some(root.id), "anything else?");+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);+ trigger.triggered_by = Some(user().to_string());+ let mut api = MockMessageServiceApi::new();+ configure_reads(+ &mut api,+ &trigger,+ thread(root, vec![answer, trigger.clone()]),+ );+ let classifier = classifier(Ok(true));+ let detector = MentionOrInferredDetector::new(+ Arc::new(api),+ Arc::new(Access::default()),+ classifier.clone(),+ );++ assert!(detector.detect(&event(&trigger)).await.is_empty());+ assert!(classifier.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn an_unattributed_agent_follow_up_infers_nothing() {+ let mut trigger = message(3, Some(Uuid::from_u128(1)), "Macro, thoughts?");+ trigger.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ let classifier = classifier(Ok(true));+ let detector = MentionOrInferredDetector::new(+ Arc::new(MockMessageServiceApi::new()),+ Arc::new(Access::default()),+ classifier.clone(),+ );++ assert!(detector.detect(&event(&trigger)).await.is_empty());+ assert!(classifier.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn an_inferred_agent_chain_stops_at_the_hop_limit_before_classifying() {+ let hop = messages::domain::agent_hops::MAX_AGENT_HOPS + 1;+ let by = |id: u128, bot: bot_id::BotId| {+ let mut reply = message(id, Some(Uuid::from_u128(1)), "your turn");+ reply.sender_id = channel_sender::ChannelSender::new_from_bot(bot);+ reply.triggered_by = Some(user().to_string());+ reply+ };+ // Cursor posts the hop past the limit; Macro and Cursor alternate before it.+ let mut replies: Vec<_> = (1..hop)+ .map(|n| {+ let bot = if (hop - n) % 2 == 0 {+ bot_id::CURSOR_BOT_ID+ } else {+ bot_id::MACRO_AI_BOT_ID+ };+ by(1 + n as u128, bot)+ })+ .collect();+ let trigger = by(10_000, bot_id::CURSOR_BOT_ID);+ replies.push(trigger.clone());+ let mut api = MockMessageServiceApi::new();+ configure_reads(+ &mut api,+ &trigger,+ thread(message(1, None, "work it out between you"), replies),+ );+ let classifier = classifier(Ok(true));+ let detector = MentionOrInferredDetector::new(+ Arc::new(api),+ Arc::new(Access::default()),+ classifier.clone(),+ );++ assert!(detector.detect(&event(&trigger)).await.is_empty());+ assert!(classifier.calls.lock().unwrap().is_empty());+}diff --git a/crates/channel_bots/src/inbound/bot_trigger_router.rs b/crates/channel_bots/src/inbound/bot_trigger_router.rsindex e86ba3d394..c38a60cbc6 100644--- a/crates/channel_bots/src/inbound/bot_trigger_router.rs+++ b/crates/channel_bots/src/inbound/bot_trigger_router.rs@@ -106,8 +106,8 @@ where}async fn run(&self, candidate: MessagePostedMetadata) {- // Guarded upstream, but double-check: only user messages trigger bots.- let Some(requesting_user) = candidate.sender.as_user().cloned() else {+ // Attribution names the user whose access and billing apply.+ let Some(requesting_user) = candidate.invoking_user() else {return;};let reply_thread_id = candidate.root_id();diff --git a/crates/channel_bots/src/outbound/conversation.rs b/crates/channel_bots/src/outbound/conversation.rsindex ceb98ecbc5..94bf265213 100644--- a/crates/channel_bots/src/outbound/conversation.rs+++ b/crates/channel_bots/src/outbound/conversation.rs@@ -9,7 +9,7 @@ use macro_user_id::user_id::MacroUserIdStr;use messages::domain::{events::MessagePostedMetadata,models::MessageParent,- ports::{MessageChange, MessageEvent, MessageEventPublisher},+ ports::{MessageEvent, MessageEventPublisher},service::MessageWrite,};use std::sync::Arc;@@ -55,9 +55,8 @@ impl<A: EntityAccessService> ConversationAccess for EntityAccessConversation<A>/// Feeds the built-in responder from the same committed message stream hosted/// and external agents consume, for channel and document posts alike.///-/// Only human posts enter the queue: a bot's own reply, including Macro AI's,-/// never triggers another bot, which is what keeps bots from relaying each-/// other forever.+/// Attributed bot posts and completed replies enter the same trigger path as+/// human posts; the detector bounds agent chains with the hop limit.#[derive(Clone)]pub struct LocalBotPublisher {triggers: tokio::sync::mpsc::UnboundedSender<MessagePostedMetadata>,@@ -72,16 +71,11 @@ impl LocalBotPublisher {impl MessageEventPublisher for LocalBotPublisher {async fn publish(&self, event: MessageEvent) -> Result<(), rootcause::Report> {- if let MessageChange::Posted {- message, mentions, ..- } = &event.change- && message.sender_id.as_user().is_some()+ if let Some(candidate) = event.agent_trigger()+ && candidate.invoking_user().is_some(){self.triggers- .send(MessagePostedMetadata::from_message(- message,- mentions.clone(),- ))+ .send(candidate).map_err(|error| rootcause::report!(error).into())} else {Ok(())diff --git a/crates/channel_bots/src/outbound/conversation/test.rs b/crates/channel_bots/src/outbound/conversation/test.rsindex 1b11b824dc..3647928ba3 100644--- a/crates/channel_bots/src/outbound/conversation/test.rs+++ b/crates/channel_bots/src/outbound/conversation/test.rs@@ -1,5 +1,6 @@use super::*;use crate::domain::test::message;+use messages::domain::ports::MessageChange;use std::sync::Mutex;#[derive(Clone, Default)]@@ -28,7 +29,7 @@ fn posted(parent: MessageParent, bot: bool) -> MessageEvent {}}#[tokio::test]-async fn user_posts_dispatch_once_and_bot_responses_never_reenter() {+async fn user_posts_dispatch_once_and_unattributed_bot_responses_never_reenter() {let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();let delivery = Delivery::default();let publisher = messages::domain::effects::MessageEffects::new(@@ -73,3 +74,42 @@ async fn closed_agent_receiver_does_not_suppress_realtime_and_notification_deliv);assert_eq!(delivery.0.lock().unwrap().len(), 1);}++#[tokio::test]+async fn attributed_posts_and_completed_replies_reach_the_local_detector() {+ use messages::domain::models::{PatchMessageNotificationPolicy, SimpleMention};+ let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();+ let publisher = LocalBotPublisher::new(sender);+ let mut message = message(2, Some(uuid::Uuid::from_u128(1)), "@macro help");+ message.triggered_by = Some(message.sender_id.as_ref().to_owned());+ message.sender_id = channel_sender::ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ let mentions = vec![SimpleMention {+ entity_type: "bot".into(),+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),+ }];+ for change in [+ MessageChange::Posted {+ message: message.clone(),+ mentions: mentions.clone(),+ notification_policy: Default::default(),+ },+ MessageChange::Edited {+ message: message.clone(),+ mentions,+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,+ previous_attachments: vec![],+ },+ ] {+ publisher+ .publish(MessageEvent {+ parent: message.parent.clone(),+ actor: message.sender_id.as_ref().to_owned(),+ nonce: None,+ change,+ })+ .await+ .unwrap();+ assert_eq!(receiver.try_recv().unwrap().sender, message.sender_id);+ assert!(receiver.try_recv().is_err());+ }+}diff --git a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs b/crates/coding_agent_worker/src/herdr/acp_agent/test.rsindex ecda1b3294..9be1fcef9e 100644--- a/crates/coding_agent_worker/src/herdr/acp_agent/test.rs+++ b/crates/coding_agent_worker/src/herdr/acp_agent/test.rs@@ -405,6 +405,7 @@ async fn a_cancelled_turn_presses_esc_until_the_native_agent_stops() {&session,guard.as_mut().unwrap(),&cancel,+ false,).await.unwrap();diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rsindex c08f62ac2c..d527163332 100644--- a/crates/coding_agent_worker/src/trigger.rs+++ b/crates/coding_agent_worker/src/trigger.rs@@ -84,7 +84,7 @@ pub enum TriggerWork {/// errors, and the stream is left open either way.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Skipped {- /// The sender is not a user, so there is nobody to act for.+ /// No valid user sender, bot attribution, or requested owner to act for.NotFromUser,/// An event shape this daemon does not recognise yet - the trigger's/// vocabulary is non-exhaustive on purpose.@@ -138,11 +138,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skielse {return Err(Skipped::Unrecognized);};- let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;+ let sender = message.invoking_user().ok_or(Skipped::NotFromUser)?;Ok(TriggerWork::OpenAndPrompt {reuse_origin_message: false,bot: bot_id,@@ -166,11 +162,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skielse {return Err(Skipped::Unrecognized);};- let sender = message- .sender- .as_user()- .cloned()- .ok_or(Skipped::NotFromUser)?;+ let sender = message.invoking_user().ok_or(Skipped::NotFromUser)?;Ok(TriggerWork::PromptExisting {message_id: message.message_id,session: session_id,diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rsindex b983ecae7e..145954983c 100644--- a/crates/coding_agent_worker/src/trigger/test.rs+++ b/crates/coding_agent_worker/src/trigger/test.rs@@ -194,7 +194,7 @@ fn a_follow_up_becomes_prompt_existing() {}#[test]-fn a_bots_own_message_is_skipped() {+fn an_unattributed_bot_message_is_skipped() {let mut event = mention("self talk");if let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) =&mut event@@ -285,3 +285,25 @@ async fn failed_work_is_returned() {.is_err());}++#[test]+fn attributed_bot_mentions_open_and_prompt_with_the_invoking_user() {+ let mut open = mention("fix the test");+ if let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(event)) = &mut open {+ event.message.sender = ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);+ event.message.triggered_by = Some(sender().to_string());+ }+ assert!(+ matches!(trigger_to_work(open).unwrap(), TriggerWork::OpenAndPrompt { sender: actor, .. } if actor == sender())+ );+ let mut follow_up = follow_up("continue");+ if let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(event)) =+ &mut follow_up+ {+ event.message.sender = ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);+ event.message.triggered_by = Some(sender().to_string());+ }+ assert!(+ matches!(trigger_to_work(follow_up).unwrap(), TriggerWork::PromptExisting { sender: actor, .. } if actor == sender())+ );+}diff --git a/crates/messages/AGENTS.md b/crates/messages/AGENTS.mdindex 3508aa7473..21de2b74bd 100644--- a/crates/messages/AGENTS.md+++ b/crates/messages/AGENTS.md@@ -59,6 +59,10 @@ they need.- `cargo test -p messages --all-features` (`SQLX_OFFLINE` unset).+A finalized bot reply (`NotifyAsPostedMessage` edit by the bot itself) carries+`completed_reply` on its patch event so agent triggers evaluate it like a new+post; streaming updates and ordinary edits never do.+A bot post made for a user through a named client (an MCP client on the publicMCP) uses `MessageAttribution::ActingUserVia`; the client's self-reported name isstored in `comms_messages.triggered_via` beside `triggered_by` and shown "viadiff --git a/crates/messages/src/domain/agent_hops.rs b/crates/messages/src/domain/agent_hops.rsnew file mode 100644index 0000000000..67c4b3bf3c--- /dev/null+++ b/crates/messages/src/domain/agent_hops.rs@@ -0,0 +1,33 @@+//! How many agents in a row handed a conversation to one another.++use channel_sender::ChannelSender;++#[cfg(test)]+mod test;++/// Most agent-to-agent hops one person's message can set off: 64 round+/// trips between two agents. The limit exists to stop runaway loops between+/// agents with nobody stepping in; every hop bills the attributed user.+pub const MAX_AGENT_HOPS: usize = 128;++/// Agent hops leading to the last of `senders`, a thread read oldest first+/// through the prompt: each change of bot author since the last message by+/// anyone else counts one. A human post starts the count over.+///+/// Messages by one bot in a row (its session announcement and its reply)+/// are a single hop.+#[must_use]+pub fn agent_hops<'a>(senders: impl DoubleEndedIterator<Item = &'a ChannelSender<'a>>) -> usize {+ let mut hops = 0;+ let mut previous = None;+ for sender in senders.rev() {+ let Some(bot) = sender.as_bot() else {+ break;+ };+ if previous != Some(bot) {+ hops += 1;+ previous = Some(bot);+ }+ }+ hops+}diff --git a/crates/messages/src/domain/agent_hops/test.rs b/crates/messages/src/domain/agent_hops/test.rsnew file mode 100644index 0000000000..762d243361--- /dev/null+++ b/crates/messages/src/domain/agent_hops/test.rs@@ -0,0 +1,30 @@+use super::*;++use macro_user_id::cowlike::CowLike as _;+use macro_user_id::user_id::MacroUserIdStr;++#[test]+fn bots_answering_each_other_count_one_hop_per_turn_since_the_last_person() {+ let person = ChannelSender::new_from_user(+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .expect("a valid user id")+ .into_owned(),+ );+ let macro_ai = ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);+ let cursor = ChannelSender::new_from_bot(bot_id::CURSOR_BOT_ID);+ let thread = [+ cursor.clone(),+ person.clone(),+ macro_ai.clone(),+ macro_ai.clone(),+ cursor.clone(),+ macro_ai.clone(),+ cursor.clone(),+ ];+ assert_eq!(agent_hops(thread[..2].iter()), 0);+ assert_eq!(agent_hops(thread[..4].iter()), 1);+ assert_eq!(agent_hops(thread[..5].iter()), 2);+ assert_eq!(agent_hops(thread[..6].iter()), 3);+ assert_eq!(agent_hops(thread.iter()), 4);+ assert_eq!(agent_hops([cursor].iter()), 1);+}diff --git a/crates/messages/src/domain/events.rs b/crates/messages/src/domain/events.rsindex 4684d12f30..b8efc9f0d9 100644--- a/crates/messages/src/domain/events.rs+++ b/crates/messages/src/domain/events.rs@@ -8,6 +8,7 @@use super::models::{Message, MessageParent, SimpleMention};use channel_sender::ChannelSender;use chrono::{DateTime, Utc};+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -63,6 +64,16 @@ pub struct MessagePostedMetadata {}impl MessagePostedMetadata {+ /// User authorizing this invocation, including a trusted bot's attribution.+ /// Autonomous bot posts have no invoking user and cannot start paid sessions.+ pub fn invoking_user(&self) -> Option<MacroUserIdStr<'static>> {+ self.sender.as_user().cloned().or_else(|| {+ MacroUserIdStr::parse_from_str(self.triggered_by.as_deref()?)+ .ok()+ .map(CowLike::into_owned)+ })+ }+/// Build the event from the persisted message, never from client parent claims.pub fn from_message(message: &Message, mentions: Vec<SimpleMention>) -> Self {Self {@@ -116,6 +127,11 @@ pub struct MessageMentionedMetadata {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]pub struct MessagePatchedMetadata {+ /// Completed bot answer, evaluated for agent triggers like a new post.+ /// Ordinary edits and streaming updates omit this; older producers remain+ /// compatible with the trigger consumer.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub completed_reply: Option<MessagePostedMetadata>,/// Entity that owns the message.pub parent: MessageParent,/// The id of the patched message.diff --git a/crates/messages/src/domain/mod.rs b/crates/messages/src/domain/mod.rsindex 3a1ab5bcdb..7879a8cbdf 100644--- a/crates/messages/src/domain/mod.rs+++ b/crates/messages/src/domain/mod.rs@@ -1,3 +1,5 @@+/// Agent-to-agent handoff counting for loop limits.+pub mod agent_hops;/// Existing PDF annotation use cases and authorization.#[cfg(feature = "annotations")]pub mod annotations;diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rsindex c0944ddb99..d7caecfe09 100644--- a/crates/messages/src/domain/ports.rs+++ b/crates/messages/src/domain/ports.rs@@ -328,6 +328,34 @@ pub enum AgentTypingPhase {Waiting,}+impl MessageEvent {+ /// A posted message or finalized bot reply to evaluate for agent triggers,+ /// explicit or implicit. Streaming and ordinary edits must never wake an+ /// agent.+ pub fn agent_trigger(&self) -> Option<super::events::MessagePostedMetadata> {+ let (message, mentions) = match &self.change {+ MessageChange::Posted {+ message, mentions, ..+ } => (message, mentions),+ MessageChange::Edited {+ message,+ mentions,+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,+ ..+ } if message.sender_id.as_bot().is_some()+ && self.actor == message.sender_id.as_ref() =>+ {+ (message, mentions)+ }+ _ => return None,+ };+ Some(super::events::MessagePostedMetadata::from_message(+ message,+ mentions.clone(),+ ))+ }+}+/// Persisted reaction state and whether this operation changed membership.pub struct ReactionResult {/// Current message, including its reactions.diff --git a/crates/messages/src/outbound/broker.rs b/crates/messages/src/outbound/broker.rsindex 3ca5408636..0b91df067f 100644--- a/crates/messages/src/outbound/broker.rs+++ b/crates/messages/src/outbound/broker.rs@@ -191,6 +191,7 @@ pub fn topic_events(event: &crate::domain::ports::MessageEvent) -> Vec<MessageMa..} => {let mut facts = vec![MessageMacroEvent::patched(MessagePatchedMetadata {+ completed_reply: event.agent_trigger(),parent: message.parent.clone(),message_id: message.id,thread_id: message.thread_id,diff --git a/crates/messages/src/outbound/broker/test.rs b/crates/messages/src/outbound/broker/test.rsindex ed4b1dc4aa..682fe2cc13 100644--- a/crates/messages/src/outbound/broker/test.rs+++ b/crates/messages/src/outbound/broker/test.rs@@ -228,3 +228,54 @@ async fn deletions_publish_and_reactions_typing_and_thread_state_stay_off_the_toassert!(publish(parent.clone(), change).await.is_empty());}}++#[test]+fn only_finalized_bot_replies_reach_agent_triggers_with_or_without_a_mention() {+ use crate::domain::models::PatchMessageNotificationPolicy::{Default, NotifyAsPostedMessage};+ // A bot's streaming updates are `Default` edits; so is a person's ordinary edit.+ for (bot, policy, has_mention, expected) in [+ (true, NotifyAsPostedMessage, true, true),+ (true, NotifyAsPostedMessage, false, true),+ (true, Default, true, false),+ (true, Default, false, false),+ (false, Default, false, false),+ (false, NotifyAsPostedMessage, true, false),+ ] {+ let parent = MessageParent::Channel(Uuid::from_u128(20));+ let mut message = reply(parent.clone(), vec![]);+ if bot {+ message.sender_id =+ channel_sender::ChannelSender::new_from_bot(bot_id::MACRO_NEW_BOT_ID);+ message.triggered_by = Some(SENDER.into());+ }+ let mentions = if has_mention {+ vec![mention(+ "bot",+ bot_id::CURSOR_BOT_ID.into_storage_id().as_ref(),+ )]+ } else {+ vec![]+ };+ let expected_post = MessagePostedMetadata::from_message(&message, mentions.clone());+ let mut event = event(+ parent,+ MessageChange::Edited {+ message,+ mentions,+ notification_policy: policy,+ previous_attachments: vec![],+ },+ );+ event.actor = expected_post.sender.as_ref().to_owned();+ let facts = topic_events(&event);+ assert_eq!(+ facts.len(),+ 1,+ "completion is still a patch, not a second post"+ );+ let MessageTopicEvent::Patched(patched) = &facts[0].event().event else {+ panic!("expected a patch");+ };+ assert_eq!(patched.completed_reply, expected.then_some(expected_post));+ }+}diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event.rs b/crates/scheduled_action/src/outbound/event_content/routine_event.rsindex 43bf8cef0a..7cb923d911 100644--- a/crates/scheduled_action/src/outbound/event_content/routine_event.rs+++ b/crates/scheduled_action/src/outbound/event_content/routine_event.rs@@ -345,6 +345,7 @@ fn discussion(let prompt_message_id = message.id;match message.thread_id.filter(|root| *root != message.id) {Some(root_id) => DiscussionContext {+ agent_request: None,surface,prompt_message_id,sender,@@ -353,6 +354,7 @@ fn discussion(channel: Vec::new(),},None => DiscussionContext {+ agent_request: None,surface,prompt_message_id,sender,diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rsindex 754a7904a5..a72be07a36 100644--- a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs+++ b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs@@ -557,6 +557,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {routine_event(&event, content).unwrap(),RoutineEvent::ChannelMessagePosted {discussion: DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: channel_id,name: Some("eng".into()),diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rsindex 7f48f09021..0db1b4939f 100644--- a/crates/trigger_context/src/lib.rs+++ b/crates/trigger_context/src/lib.rs@@ -113,6 +113,9 @@ pub struct DiscussionContext {pub prompt_message_id: Uuid,/// Who posted it.pub sender: ContextPerson,+ /// Set when `sender` is an agent handing the discussion on for a person.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub agent_request: Option<AgentRequest>,/// What the message answers.pub reply_target: ReplyTarget,/// The message's own discussion, from its root through the message.@@ -196,6 +199,16 @@ impl TriggerContext {}}+/// An agent's message asking another agent for something on a person's behalf.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AgentRequest {+ /// The person the asking agent acts for, who owns the work it starts.+ pub on_behalf_of: ContextPerson,+ /// Agent-to-agent handoffs since a person last wrote in the discussion,+ /// this one included.+ pub hops: usize,+}+/// Where a discussion lives. Each carries its name, so the agent is never/// handed a bare id.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]diff --git a/crates/trigger_context/src/test.rs b/crates/trigger_context/src/test.rsindex 9373a6ea2c..8a483c67f2 100644--- a/crates/trigger_context/src/test.rs+++ b/crates/trigger_context/src/test.rs@@ -8,6 +8,7 @@ fn a_channel_follow_up_has_a_stable_wire_shape() {let context = TriggerContext::FollowUp(FollowUpContext {addressed_by: AddressedBy::ExplicitReply,discussion: DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: Uuid::parse_str("00000000-0000-0000-0000-0000000000c1").unwrap(),name: Some("eng".to_owned()),@@ -313,6 +314,7 @@ fn prompt_thread_attachments_put_the_prompt_message_first() {let prompt = image("prompt-file");let later = image("later-file");let discussion = DiscussionContext {+ agent_request: None,surface: DiscussionSurface::Channel {id: Uuid::from_u128(0xc1),name: Some("eng".to_owned()),diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 8544236e37..3b38bd9c59 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -703,6 +703,7 @@ fn message_event_cases() -> Vec<EventCase> {EventCase::new(TestBrokerEvent::Message(Event::with_schema_version(MessageTopicEvent::Patched(MessagePatchedMetadata {+ completed_reply: None,parent: channel.clone(),message_id,thread_id: None,diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 5fe1ac6bde..28429245d9 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -471,6 +471,23 @@ reply without attaching anything, and confirm it describes the image.Macro Coding Agent (`@coder`) is unavailable in mention suggestions, includingwhen it appears among existing participants or bots. Check with the agentsrollout both enabled and disabled.++Agent-authored messages trigger other agents exactly like a person's: an explicit+mention starts or continues the mentioned agent's session, and an unmentioned reply+in a thread can reach another live agent there by quote-reply or inference. The+originating user's permissions, connected runtime, and usage allowance apply through+the bot message's server-recorded attribution. Autonomous webhook posts without that+attribution trigger nothing, and a bot never triggers its own session. Finalized bot+answers are evaluated like new posts, mentioned or not; streaming updates and+ordinary edits are not. Agents handing the thread back and forth stop after 128+agent turns (64 round trips) with no person writing in between; the next agent+message is logged and triggers nothing, before any classifier runs. The invoked session's+prompt reads "Started by <agent> for <person>" (or "Asked by" on a follow-up).+To verify, ask session-backed `@Macro` to post a mention of `@cursor`, then have+Cursor post a mention of session-backed Macro in the same thread. Check that the+first mention opens Cursor and the return mention continues Macro's existing+session. Repeat with revoked channel access and confirm no new work starts.+When the backend is configured with AI usage enforcement, a rejected classic`@Macro` request gets a thread reply explaining the allowance failure (for example,`ai_allowance_exhausted`) or temporary validation failure (`ai_billing_unavailable`),diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.tsindex 357faeb466..1a6de4b711 100644--- a/packages/lexical-core/tests/agent-trigger-context.test.ts+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts@@ -266,6 +266,51 @@ describe('composeAgentContextPrompt with a trigger', () => {);});+ it('tells an agent asked by another agent who that agent speaks for', () => {+ const markdown = composeAgentContextPrompt({+ promptMarkdown: 'please fix the failing test',+ trigger: {+ kind: 'mentioned',+ surface: {+ type: 'channel',+ id: 'c1',+ name: 'eng',+ channel_type: 'public',+ },+ prompt_message_id: 'm2',+ sender: { id: 'bot|macro', name: 'Macro' },+ agent_request: {+ on_behalf_of: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ hops: 1,+ },+ reply_target: { kind: 'thread', root_id: 'm1' },+ },+ });++ expect(hiddenContext(markdown)).toBe(+ [+ '<trigger kind="mentioned">',+ ' <note>Macro mentioned you, and that mention opened this session. Their message is the prompt. Macro is another agent asking on behalf of Julia; Julia did not write this message. Address your reply to Macro in the discussion, where Julia can read it too.</note>',+ ' <discussion>',+ ' <channel id="c1" name="eng" type="public"/>',+ ' <origin>This prompt was posted in a channel thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.</origin>',+ ' <sender name="Macro" id="bot|macro"/>',+ ' <agent_request hops="1">',+ ' <on_behalf_of name="Julia" email="[email protected]" id="macro|[email protected]"/>',+ ' </agent_request>',+ ' <reply_target kind="thread" thread="m1">',+ ' <note>The prompt was posted as a reply in the thread below. It is about that thread.</note>',+ ' </reply_target>',+ ' </discussion>',+ '</trigger>',+ ].join('\n')+ );+ });+it('renders an inferred follow-up after the session block and warns the inference can be wrong', () => {const markdown = composeAgentContextPrompt({promptMarkdown: 'and the popover one too',diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.tsindex 6c08ea8722..9887bcde6b 100644--- a/packages/lexical-core/utils/agent-context.ts+++ b/packages/lexical-core/utils/agent-context.ts@@ -68,6 +68,8 @@ export type DiscussionContext = {surface: DiscussionSurface;prompt_message_id: string;sender: ContextPerson;+ /** Present when the sender is an agent asking on a person's behalf. */+ agent_request?: AgentRequest;reply_target: ReplyTarget;/** Absent for a top-level channel message. */thread?: ContextThread;@@ -75,6 +77,13 @@ export type DiscussionContext = {channel?: ContextThread[];};+export type AgentRequest = {+ /** The person the asking agent acts for, who owns the work it starts. */+ on_behalf_of: ContextPerson;+ /** Agent-to-agent handoffs since a person last wrote, this one included. */+ hops: number;+};+export type ChannelType = 'public' | 'private' | 'direct_message' | 'team';/** Where a discussion lives. */@@ -1020,6 +1029,15 @@ function discussionNode(]: []),personNode('sender', discussion.sender),+ ...(discussion.agent_request+ ? [+ el(+ 'agent_request',+ [personNode('on_behalf_of', discussion.agent_request.on_behalf_of)],+ { hops: String(discussion.agent_request.hops) }+ ),+ ]+ : []),contextReplyTargetNode(discussion.reply_target, marker, reading.subject),...(discussionHasAttachments(discussion)? [@@ -1150,12 +1168,23 @@ function callNode(call: CallSnapshot): FxpNode {);}+/**+ * Who an agent's message speaks for, so the reply goes to the agent that+ * asked rather than to a person who never wrote it.+ */+function agentRequestNote(discussion: DiscussionContext): string {+ const request = discussion.agent_request;+ if (!request) return '';+ const person = request.on_behalf_of.name;+ return ` ${discussion.sender.name} is another agent asking on behalf of ${person}; ${person} did not write this message. Address your reply to ${discussion.sender.name} in the discussion, where ${person} can read it too.`;+}+function mentionedNode(discussion: DiscussionContext): FxpNode {return el('trigger',[note(- `${discussion.sender.name} mentioned you, and that mention opened this session. Their message is the prompt.`+ `${discussion.sender.name} mentioned you, and that mention opened this session. Their message is the prompt.${agentRequestNote(discussion)}`),discussionNode(discussion, {marker: 'mentioned_you',@@ -1188,7 +1217,7 @@ function followUpNode({ addressed_by, discussion }: FollowUpContext): FxpNode {'trigger',[note(- `This session was already running when ${discussion.sender.name} posted this message in its discussion. ${explanation} The message is the prompt.`+ `This session was already running when ${discussion.sender.name} posted this message in its discussion. ${explanation} The message is the prompt.${agentRequestNote(discussion)}`),discussionNode(discussion, {marker,diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MessagePatchedMetadata.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MessagePatchedMetadata.mdindex b0d9bb8374..2918ba80f1 100644--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MessagePatchedMetadata.md+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/MessagePatchedMetadata.md@@ -1,6 +1,6 @@# Type Alias: MessagePatchedMetadata-> **MessagePatchedMetadata** = \{ `actor`: [`ChannelSender`](ChannelSender.md); `content`: `string`; `edited_at?`: `string` \| `null`; `message_id`: `string`; `parent`: [`MessageParent`](MessageParent.md); `root_id`: `string`; `thread_id?`: `string` \| `null`; `updated_at`: `string`; \}+> **MessagePatchedMetadata** = \{ `actor`: [`ChannelSender`](ChannelSender.md); `completed_reply?`: `null` \| [`MessagePostedMetadata`](MessagePostedMetadata.md); `content`: `string`; `edited_at?`: `string` \| `null`; `message_id`: `string`; `parent`: [`MessageParent`](MessageParent.md); `root_id`: `string`; `thread_id?`: `string` \| `null`; `updated_at`: `string`; \}A committed content edit.@@ -9,6 +9,7 @@ A committed content edit.| Property | Type | Description || ------ | ------ | ------ || <a id="property-actor"></a> `actor` | [`ChannelSender`](ChannelSender.md) | Actor that patched the message. |+| <a id="property-completed_reply"></a> `completed_reply?` | `null` \| [`MessagePostedMetadata`](MessagePostedMetadata.md) | - || <a id="property-content"></a> `content` | `string` | Macro Markdown body after the patch. || <a id="property-edited_at"></a> `edited_at?` | `string` \| `null` | Edit timestamp, when the patch marked the message edited. || <a id="property-message_id"></a> `message_id` | `string` | The id of the patched message. |diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 1acafa6208..7b2578066d 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -10459,6 +10459,7 @@ export type MessagePatchedMetadata = {* Actor that patched the message.*/actor: ChannelSender;+ completed_reply?: null | MessagePostedMetadata;/*** Macro Markdown body after the patch.*/diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 834ef6da0e..fe321da710 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -35651,6 +35651,17 @@"$ref": "#/components/schemas/ChannelSender","description": "Actor that patched the message."},+ "completed_reply": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/MessagePostedMetadata",+ "description": "Completed bot answer, evaluated for agent triggers like a new post.\nOrdinary edits and streaming updates omit this; older producers remain\ncompatible with the trigger consumer."+ }+ ]+ },"content": {"type": "string","description": "Macro Markdown body after the patch."diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.tsindex 7c332ceade..3933d7aa10 100644--- a/services/lexical-service/src/endpoints/agent-context.ts+++ b/services/lexical-service/src/endpoints/agent-context.ts@@ -184,6 +184,12 @@ const discussionContext = z.object({surface: discussionSurface,prompt_message_id: z.string().min(1),sender: triggerPerson,+ agent_request: z+ .object({+ on_behalf_of: triggerPerson,+ hops: z.number().int().nonnegative(),+ })+ .optional(),reply_target: triggerReplyTarget,thread: triggerThread.optional(),channel: z.array(triggerThread).optional(),diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex 7d8443c111..878e5caa70 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -801,6 +801,7 @@ fn message_event_cases() -> Vec<(MessageTopicEvent, MessageEventDescription)> {),(MessageTopicEvent::Patched(MessagePatchedMetadata {+ completed_reply: None,parent: channel.clone(),message_id: MESSAGE_ID,thread_id: None,