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: implicit agent triggers (quote-reply and fast-model judge) (#5699)
Wolf Mermelstein6780807db9d6
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex e5c9e37cc9..096fa9d436 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -457,19 +457,26 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/authentication_service_client","crates/bot_id","crates/bot_token","crates/bots","crates/broadcast",+ "crates/call","crates/channel_sender","crates/channels",+ "crates/connection","crates/connection_gateway_client","crates/connection_gateway_models","crates/contacts","crates/cowlike",+ "crates/crm","crates/document_sub_type",+ "crates/email",+ "crates/email_utils","crates/entity_access","crates/entity_access_db_utils",+ "crates/entity_access_management","crates/entity_mutation","crates/filter_ast","crates/frecency",@@ -477,8 +484,10 @@"crates/item_filters","crates/kafka_util","crates/last_online_tracker",+ "crates/lexical_client","crates/macro_auth","crates/macro_authorization",+ "crates/macro_aws_config","crates/macro_env","crates/macro_env_var","crates/macro_event_broker",@@ -496,15 +505,26 @@"crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",+ "crates/models_opensearch","crates/models_pagination","crates/models_permissions",+ "crates/models_properties",+ "crates/models_search",+ "crates/models_search_cursor",+ "crates/models_soup","crates/non_empty","crates/notification",+ "crates/opensearch_client",+ "crates/opensearch_query_builder","crates/prompt",+ "crates/properties","crates/rate_limit",+ "crates/reminders","crates/remote_env_var","crates/share_permission_db_utils","crates/sqs_worker",+ "crates/system_properties",+ "crates/unfurl","crates/workspace-hack"],"agent_trigger_service": [@@ -517,20 +537,27 @@"crates/ai_toolset","crates/ai_usage","crates/attachment",+ "crates/authentication_service_client","crates/bot_id","crates/bot_token","crates/bots","crates/broadcast",+ "crates/call","crates/channel_sender","crates/channels",+ "crates/connection","crates/connection_gateway_client","crates/connection_gateway_models","crates/contacts","crates/cowlike",+ "crates/crm","crates/database_env_vars","crates/document_sub_type",+ "crates/email",+ "crates/email_utils","crates/entity_access","crates/entity_access_db_utils",+ "crates/entity_access_management","crates/entity_mutation","crates/filter_ast","crates/frecency",@@ -538,8 +565,10 @@"crates/item_filters","crates/kafka_util","crates/last_online_tracker",+ "crates/lexical_client","crates/macro_auth","crates/macro_authorization",+ "crates/macro_aws_config","crates/macro_config","crates/macro_config_derive","crates/macro_entrypoint",@@ -560,15 +589,26 @@"crates/model_user","crates/models_bulk_upload","crates/models_entity_access_management",+ "crates/models_opensearch","crates/models_pagination","crates/models_permissions",+ "crates/models_properties",+ "crates/models_search",+ "crates/models_search_cursor",+ "crates/models_soup","crates/non_empty","crates/notification",+ "crates/opensearch_client",+ "crates/opensearch_query_builder","crates/prompt",+ "crates/properties","crates/rate_limit",+ "crates/reminders","crates/remote_env_var","crates/share_permission_db_utils","crates/sqs_worker",+ "crates/system_properties",+ "crates/unfurl","crates/workspace-hack","services/agent_trigger_service"],diff --git a/.sqlx/query-1b9d5291cf17cb33b9ba0843863f59ff3cf2e1473c89880a5a21d32f881ebc54.json b/.sqlx/query-1b9d5291cf17cb33b9ba0843863f59ff3cf2e1473c89880a5a21d32f881ebc54.jsonnew file mode 100644index 0000000000..3a1bc98dc3--- /dev/null+++ b/.sqlx/query-1b9d5291cf17cb33b9ba0843863f59ff3cf2e1473c89880a5a21d32f881ebc54.json@@ -0,0 +1,118 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1\n ORDER BY created_at DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "originating_message_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 5,+ "name": "bot_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 6,+ "name": "model",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "harness",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "repo_url",+ "type_info": "Text"+ },+ {+ "ordinal": 9,+ "name": "workspace",+ "type_info": "Text"+ },+ {+ "ordinal": 10,+ "name": "sandbox_size",+ "type_info": "Text"+ },+ {+ "ordinal": 11,+ "name": "acp_session_id",+ "type_info": "Text"+ },+ {+ "ordinal": 12,+ "name": "status",+ "type_info": "Text"+ },+ {+ "ordinal": 13,+ "name": "status_event_name",+ "type_info": "Text"+ },+ {+ "ordinal": 14,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 15,+ "name": "modified_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "thread_channel_id?",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ false,+ false,+ false,+ true,+ false,+ false,+ true,+ false,+ true,+ false,+ false,+ null+ ]+ },+ "hash": "1b9d5291cf17cb33b9ba0843863f59ff3cf2e1473c89880a5a21d32f881ebc54"+}diff --git a/Cargo.lock b/Cargo.lockindex 568ff8ace9..b2c0eea362 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -389,11 +389,15 @@ dependencies = [name = "agent_trigger"version = "0.1.0"dependencies = [+ "agent","agent_session",+ "ai_usage",+ "anyhow","bot_id","channel_sender","channels","chrono",+ "lexical_client","macro_event_broker","macro_event_topics","macro_user_id",@@ -414,15 +418,18 @@ version = "0.1.0"dependencies = ["agent_session","agent_trigger",+ "ai_usage","anyhow","bots","channels","database_env_vars","kafka_util",+ "lexical_client","macro_config","macro_entrypoint","macro_env_var","macro_event_broker",+ "macro_service_urls","rdkafka","serde_json","sqlx",diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rsindex df6b038ad5..c1045e9489 100644--- a/crates/agent_harness/src/domain/service.rs+++ b/crates/agent_harness/src/domain/service.rs@@ -586,7 +586,8 @@ where////// Three steps, in this order: persist whatever the action changes about/// the session, work out whether anyone needs telling, then deliver it.- /// Announcing last means nothing is announced that was never sent.+ /// Announcing before delivery means the chip exists to anchor the turn+ /// the agent streams into.#[tracing::instrument(err, skip(self, command), fields(agent.session.id = %session_id))]async fn deliver(&self, session_id: AgentSessionId, command: DeliverAction) -> Result<()> {let DeliverAction {@@ -600,6 +601,13 @@ where.announcement(session_id, &action, actor.as_ref(), announce).await?;+ // Announced before the prompt is delivered, as `open` does: the chip+ // anchors the turn the agent is about to stream into, so it has to+ // exist before the response can arrive.+ if let Some(announcement) = announcement {+ self.announcer.announce(announcement).await?;+ }+match self.sessions.send_action(session_id, actor.clone(), action.clone(), id.clone())@@ -639,10 +647,6 @@ where}Err(error) => return Err(error.into()),}-- if let Some(announcement) = announcement {- self.announcer.announce(announcement).await?;- }Ok(())}diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex a03564348d..244a3f1ac8 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -369,6 +369,46 @@ async fn forward_to_a_live_session_reuses_the_transport() {assert_eq!(announced[1].origin_thread_id, Uuid::from_u128(0xf1));}+#[tokio::test]+async fn forward_announces_before_delivering_the_prompt() {+ let (service, _repo, containers, announcer, _runtimes) = harness();+ let id = AgentSessionId::new();+ let open = service.execute(id, HarnessCommand::Open(open_command()));+ let drive = async {+ loop {+ if containers.spawned() == 1 {+ break;+ }+ tokio::task::yield_now().await;+ }+ let container = containers+ .container(session_of(&containers))+ .expect("the spawned container is findable");+ complete_handshake(&container).await;+ container+ };+ let (opened, container) = tokio::join!(open, drive);+ opened.expect("open should succeed");+ assert_eq!(prompts(&container.agent()).len(), 1);++ // A chip that cannot be posted has nothing to anchor the response, so the+ // prompt must not reach the agent at all.+ announcer.fails("the chip could not be posted");+ let result = service+ .execute(+ id,+ HarnessCommand::Deliver(forward_message("and add a regression test")),+ )+ .await;++ assert!(matches!(result, Err(HarnessError::Announce(_))));+ assert_eq!(+ prompts(&container.agent()).len(),+ 1,+ "the chip is announced before the prompt is delivered"+ );+}+#[tokio::test]async fn a_delivery_failure_is_not_automatically_resumed() {let (service, _repo, containers, _announcer, _runtimes) = harness();diff --git a/crates/agent_harness/src/inbound/kafka.rs b/crates/agent_harness/src/inbound/kafka.rsindex 65bb5ec2c0..fb2a2e3977 100644--- a/crates/agent_harness/src/inbound/kafka.rs+++ b/crates/agent_harness/src/inbound/kafka.rs@@ -104,6 +104,7 @@ pub fn route_agent_trigger(ChannelEventMetadata {bot_id,session_id,+ kind: _,message,},)) => {diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex 1705d6855d..74d48df9bb 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -1,7 +1,7 @@use agent_runtime_protocol::domain::action::AgentAction;use agent_session::domain::model::AgentSessionId;use agent_trigger::domain::broker_events::{- AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata,+ AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata, ChannelKind,ExistingAgentSessionEvent, NewAgentSessionEvent,};use bot_id::MACRO_CODER_BOT_ID;@@ -47,6 +47,7 @@ fn channel_message(bot: BotId) -> AgentTriggerTopicEvent {AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(ChannelEventMetadata {bot_id: bot,session_id: AgentSessionId::TEST_A,+ kind: ChannelKind::MentionThread,message: message(ChannelSender::new_from_user(user())),}))}@@ -182,6 +183,7 @@ fn a_bot_authored_external_channel_message_is_skipped() {ChannelEventMetadata {bot_id: BotId::TEST_A,session_id: AgentSessionId::TEST_A,+ kind: ChannelKind::MentionThread,message: message(ChannelSender::new_from_bot(BotId::TEST_B)),},));diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex c404434585..aab9e97047 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -155,6 +155,16 @@ pub trait AgentSessionRepo: Send + Sync + 'static {bot_id: Option<BotId>,) -> impl Future<Output = Result<ChannelSession>> + Send;+ /// Every session rooted at this thread, newest first, regardless of bot.+ ///+ /// [`find_for_channel`](Self::find_for_channel) answers for one known bot;+ /// this answers when no bot was named - a message in the thread may still+ /// be meant for whichever agent lives there.+ fn find_all_for_thread(+ &self,+ thread_id: Uuid,+ ) -> impl Future<Output = Result<Vec<AgentSession>>> + Send;+/// The agent behind a session, for rendering the messages it sent.////// A bot that has been deleted still has messages in the channel, so thisdiff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex 58e623887e..d7822225e9 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -857,6 +857,10 @@ whereself.repo.find_for_channel(thread_id, bot_id).await}+ async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {+ self.repo.find_all_for_thread(thread_id).await+ }+async fn set_acp_session_id(&self,id: AgentSessionId,diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex 8443c8b275..e8327828f9 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -344,6 +344,10 @@ impl AgentSessionRepo for BlockingPromptLogs {self.repo.find_for_channel(thread_id, bot_id).await}+ async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {+ self.repo.find_all_for_thread(thread_id).await+ }+async fn set_acp_session_id(&self,id: AgentSessionId,diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex 8cd39f29f4..3bb922e086 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -338,6 +338,32 @@ impl AgentSessionRepo for PgAgentSessionRepo {})}+ async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {+ let rows = sqlx::query_as!(+ AgentSessionRow,+ r#"+ SELECT+ id, name, owner_id, thread_id, originating_message_id, bot_id,+ model, harness, repo_url, workspace, sandbox_size, acp_session_id, status,+ status_event_name, created_at, modified_at,+ (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)+ AS "thread_channel_id?"+ FROM agent_session+ WHERE thread_id = $1+ ORDER BY created_at DESC+ "#,+ thread_id,+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to find agent sessions for thread")?;++ Ok(rows+ .into_iter()+ .map(AgentSession::try_from)+ .collect::<anyhow::Result<Vec<_>>>()?)+ }+async fn session_bot(&self, id: BotId) -> Result<SessionBot> {// Delegated to the bots hex rather than a bespoke query: this is// exactly bot id -> bot, and `get_bot` already excludes deleted bots -diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex 13eede537c..9f27996f54 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -137,6 +137,19 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {})}+ async fn find_all_for_thread(&self, thread_id: Uuid) -> Result<Vec<AgentSession>> {+ let mut found: Vec<AgentSession> = self+ .sessions+ .lock()+ .expect("in-memory session store is not poisoned")+ .values()+ .filter(|session| session.thread_id == Some(thread_id))+ .cloned()+ .collect();+ found.sort_by(|a, b| b.created_at.cmp(&a.created_at));+ Ok(found)+ }+async fn find_for_channel(&self,thread_id: Option<Uuid>,diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.tomlindex e050c19947..86e1d1437a 100644--- a/crates/agent_trigger/Cargo.toml+++ b/crates/agent_trigger/Cargo.toml@@ -5,8 +5,12 @@ publish = falseversion = "0.1.0"[dependencies]+agent = { path = "../agent" }agent_session = { path = "../agent_session" }+ai_usage = { path = "../ai_usage" }+anyhow = { workspace = true }bot_id = { path = "../bot_id" }+lexical_client = { path = "../lexical_client" }channels = { path = "../channels", features = ["ports"] }chrono = { workspace = true }# Only the domain vocabulary (`Event`, `MacroEvent`, `TopicEvent`). Asking fordiff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rsindex bda3cb1125..c7fab61dae 100644--- a/crates/agent_trigger/src/domain/broker_events.rs+++ b/crates/agent_trigger/src/domain/broker_events.rs@@ -10,6 +10,20 @@ use serde::{Deserialize, Serialize};#[cfg(test)]mod test;+/// How a message was attributed to the session it feeds.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ChannelKind {+ /// The thread the session was created from, where the bot was pinged.+ MentionThread,+ /// The session's thread, where the message quote-replied without a+ /// mention.+ QuoteReply,+ /// The session's thread, where a model inferred the message was addressed+ /// to the agent.+ Inferred,+}+/// A session opened by a mention in a channel.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct AgentBotMentionedEvent {@@ -35,6 +49,8 @@ pub struct ChannelEventMetadata {pub bot_id: BotId,/// The session to feed.pub session_id: AgentSessionId,+ /// How the message was attributed to the session.+ pub kind: ChannelKind,/// The message, verbatim.pub message: ChannelMessagePostedMetadata,}diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rsindex c9e45bda48..2a319e827d 100644--- a/crates/agent_trigger/src/domain/broker_events/test.rs+++ b/crates/agent_trigger/src/domain/broker_events/test.rs@@ -49,6 +49,7 @@ fn serializes_an_existing_channel_event() {ChannelEventMetadata {bot_id: BotId::TEST_A,session_id: AgentSessionId::TEST_A,+ kind: ChannelKind::MentionThread,message: message(),},));@@ -80,6 +81,7 @@ fn event_names_match_the_wire() {ChannelEventMetadata {bot_id: BotId::TEST_A,session_id: AgentSessionId::TEST_A,+ kind: ChannelKind::MentionThread,message: message(),},)),@@ -93,3 +95,17 @@ fn event_names_match_the_wire() {assert_eq!(names, wire_names);}++#[test]+fn channel_kinds_round_trip_in_snake_case() {+ for (kind, wire) in [+ (ChannelKind::MentionThread, "mention_thread"),+ (ChannelKind::QuoteReply, "quote_reply"),+ (ChannelKind::Inferred, "inferred"),+ ] {+ let value = serde_json::to_value(kind).expect("serialize kind");+ assert_eq!(value, json!(wire));+ let parsed: ChannelKind = serde_json::from_value(value).expect("deserialize kind");+ assert_eq!(parsed, kind);+ }+}diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rsindex 987a7eaf1e..6c98e84cd0 100644--- a/crates/agent_trigger/src/domain/mod.rs+++ b/crates/agent_trigger/src/domain/mod.rs@@ -1,4 +1,5 @@pub mod broker_events;pub mod processing;pub mod service;+pub mod thread_window;pub mod yield_event;diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rsindex 119ce6a581..8a7da20e44 100644--- a/crates/agent_trigger/src/domain/processing.rs+++ b/crates/agent_trigger/src/domain/processing.rs@@ -6,7 +6,9 @@ use channels::domain::broker_events::{ChannelMacroEvent, ChannelTopicEvent};use macro_event_broker::{EventBrokerError, MacroEvent as _, MacroEventBroker};use super::broker_events::AgentTriggerEventName;-use super::service::{AgentBotLookup, AgentTriggerService};+use super::service::{+ AgentBotLookup, AgentTriggerService, ImplicitTriggerJudge, ReplyDetector, ThreadHistory,+};/// Failure while evaluating or publishing one channel event.#[derive(Debug, thiserror::Error)]@@ -26,14 +28,17 @@ pub enum ProcessChannelEventError {////// Transport adapters retain ownership of decode and offset commit so their/// `kafka.process` span can cover the complete record lifecycle.-pub async fn process_channel_event<Repo, Bots, Broker>(- trigger: &AgentTriggerService<Repo, Bots>,+pub async fn process_channel_event<Repo, Bots, Replies, Judge, History, Broker>(+ trigger: &AgentTriggerService<Repo, Bots, Replies, Judge, History>,publisher: &Broker,event: &ChannelMacroEvent,) -> Result<(), ProcessChannelEventError>whereRepo: AgentSessionRepo,Bots: AgentBotLookup,+ Replies: ReplyDetector,+ Judge: ImplicitTriggerJudge,+ History: ThreadHistory,Broker: MacroEventBroker,{let ChannelTopicEvent::MessagePosted(posted) = &event.event().event else {diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rsindex bb67a01cb0..e7ce65aafc 100644--- a/crates/agent_trigger/src/domain/service.rs+++ b/crates/agent_trigger/src/domain/service.rs@@ -6,17 +6,30 @@ use std::collections::HashSet;mod test;use agent_session::domain::error::Result;-use agent_session::domain::model::{AgentSessionId, ChannelSession};+use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession};use agent_session::domain::ports::AgentSessionRepo;use bot_id::BotId;use channels::domain::broker_events::ChannelMessagePostedMetadata;use channels::domain::side_effects::bot_mention_ids;-use crate::domain::broker_events::AgentSessionMacroEvent;+use macro_uuid::Uuid;++use crate::domain::broker_events::{AgentSessionMacroEvent, ChannelEventMetadata, ChannelKind};+use crate::domain::thread_window::{ThreadMessage, render_transcript, thread_window};use crate::domain::yield_event::{AgentSessionEventDecision, NoEventReason, PotentialTriggerEvent, yield_event,};+/// 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+/// thread does not become mostly unrelated chatter.+const WINDOW_RADIUS: usize = 4;++/// Ceiling on transcript length, keeping the most recent messages. A judgement+/// about the newest message rarely turns on what happened dozens of messages+/// ago, and the fast model reads a bounded prompt.+const TRANSCRIPT_CAP: usize = 40;+/// Bot facts required to decide whether a mention may start an agent session.#[cfg_attr(test, mockall::automock)]pub trait AgentBotLookup: Send + Sync + 'static {@@ -24,20 +37,73 @@ pub trait AgentBotLookup: Send + Sync + 'static {fn has_agent(&self, bot_id: BotId) -> impl Future<Output = Result<bool>> + Send;}+/// Detects whether a message is composed as a quote-reply - a leading+/// blockquote followed by the reply itself, the shape the editor produces+/// when replying to a message.+#[cfg_attr(test, mockall::automock)]+pub trait ReplyDetector: Send + Sync + 'static {+ /// Whether this markdown is a quote-reply.+ fn is_quote_reply(&self, markdown: &str) -> impl Future<Output = Result<bool>> + Send;+}++/// Reads whole threads, so an unmentioned message can be judged against the+/// conversation it landed in.+#[cfg_attr(test, mockall::automock)]+pub trait ThreadHistory: Send + Sync + 'static {+ /// Every message of the thread rooted at `thread_id`, oldest first.+ fn thread_messages(+ &self,+ channel_id: Uuid,+ thread_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ThreadMessage>>> + Send;+}++/// Judges whether an unmentioned message in a session's thread is addressed+/// to the agent.+#[cfg_attr(test, mockall::automock)]+pub trait ImplicitTriggerJudge: Send + Sync + 'static {+ /// Whether the message reads as directed at the session's agent, read+ /// against `transcript` - the thread around the agent's participation in+ /// it, empty when the thread could not be read.+ fn is_addressed_to_agent(+ &self,+ posted: &ChannelMessagePostedMetadata,+ transcript: &str,+ ) -> impl Future<Output = Result<bool>> + Send;+}+/// Looks up the session context for a channel message and evaluates its trigger rule.-pub struct AgentTriggerService<Repo, Bots> {+pub struct AgentTriggerService<Repo, Bots, Replies, Judge, History> {sessions: Repo,bots: Bots,+ replies: Replies,+ judge: Judge,+ history: History,}-impl<Repo, Bots> AgentTriggerService<Repo, Bots>+impl<Repo, Bots, Replies, Judge, History> AgentTriggerService<Repo, Bots, Replies, Judge, History>whereRepo: AgentSessionRepo,Bots: AgentBotLookup,+ Replies: ReplyDetector,+ Judge: ImplicitTriggerJudge,+ History: ThreadHistory,{/// Creates a trigger service backed by session and bot lookups.- pub const fn new(sessions: Repo, bots: Bots) -> Self {- Self { sessions, bots }+ pub const fn new(+ sessions: Repo,+ bots: Bots,+ replies: Replies,+ judge: Judge,+ history: History,+ ) -> Self {+ Self {+ sessions,+ bots,+ replies,+ judge,+ history,+ }}/// Evaluates one channel message for every mentioned bot.@@ -69,6 +135,8 @@ 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).await? {+ events.push(event);}return Ok(events);}@@ -143,6 +211,146 @@ where}}}++ /// Evaluates an unmentioned message against the sessions rooted at its+ /// thread: a quote-reply is forwarded outright, anything else only when+ /// the judge reads it as addressed to the agent.+ ///+ /// Only fires when exactly one agent is live in the thread; picking among+ /// several by recency would route on nothing the author meant.+ ///+ /// Detector and judge failures are treated as "no" rather than propagated:+ /// implicit triggering is best-effort, and an outage must not wedge the+ /// channel firehose or fabricate forwards.+ async fn evaluate_implicit(+ &self,+ posted: &ChannelMessagePostedMetadata,+ ) -> Result<Option<AgentSessionMacroEvent>> {+ 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.+ if posted.sender.as_user().is_none() {+ return Ok(None);+ }+ let mut candidates = Vec::new();+ for session in self.sessions.find_all_for_thread(thread_id).await? {+ if self.bots.has_agent(session.bot_id).await? {+ candidates.push(session);+ }+ }+ let session = match candidates.as_slice() {+ [] => return Ok(None),+ [session] => session.clone(),+ sessions => {+ log_no_event(+ posted,+ None,+ NoEventReason::AmbiguousAgentSessions {+ candidates: sessions.len(),+ },+ );+ return Ok(None);+ }+ };++ let kind = if self.is_quote_reply(posted).await {+ // A quote-reply says who it answers on its face, so it needs no+ // thread read at all.+ ChannelKind::QuoteReply+ } else if self+ .is_addressed_to_agent(posted, &self.transcript(posted, thread_id, &session).await)+ .await+ {+ ChannelKind::Inferred+ } else {+ log_no_event(+ posted,+ None,+ NoEventReason::NotAddressedToAgent {+ session_id: session.id,+ },+ );+ return Ok(None);+ };++ Ok(Some(AgentSessionMacroEvent::channel_event(+ ChannelEventMetadata {+ bot_id: session.bot_id,+ session_id: session.id,+ kind,+ message: posted.clone(),+ },+ )))+ }++ async fn is_quote_reply(&self, posted: &ChannelMessagePostedMetadata) -> bool {+ self.replies+ .is_quote_reply(&posted.content)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "quote-reply detection failed; treating as not a reply");+ })+ .unwrap_or(false)+ }++ /// The thread around the points where the agent took part: its own+ /// messages, and the message being judged, each with [`WINDOW_RADIUS`]+ /// messages of surrounding conversation.+ ///+ /// An unreadable thread yields an empty transcript rather than an error, so+ /// the judge still rules on the message itself instead of the whole path+ /// wedging on a thread read.+ async fn transcript(+ &self,+ posted: &ChannelMessagePostedMetadata,+ thread_id: Uuid,+ session: &AgentSession,+ ) -> String {+ let messages = match self+ .history+ .thread_messages(posted.channel_id, thread_id)+ .await+ {+ Ok(messages) => messages,+ Err(error) => {+ tracing::warn!(error = ?error, "thread read failed; judging without thread context");+ return String::new();+ }+ };+ let agent = session.bot_id.into_storage_id();+ let anchors: Vec<Uuid> = messages+ .iter()+ .filter(|message| {+ message.id == posted.message_id+ || message+ .sender+ .as_bot()+ .is_some_and(|bot| bot.as_ref() == agent.as_ref())+ })+ .map(|message| message.id)+ .collect();++ render_transcript(+ &thread_window(&messages, &anchors, WINDOW_RADIUS, TRANSCRIPT_CAP),+ session.bot_id,+ )+ }++ async fn is_addressed_to_agent(+ &self,+ posted: &ChannelMessagePostedMetadata,+ transcript: &str,+ ) -> bool {+ self.judge+ .is_addressed_to_agent(posted, transcript)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "implicit trigger judge failed; treating as not addressed");+ })+ .unwrap_or(false)+ }}fn log_no_event(diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 164ede62c5..2d75b72402 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -1,5 +1,6 @@use super::*;+use agent_session::domain::error::AgentSessionError;use agent_session::domain::model::{AgentSession, AgentSessionId, ChannelSession, SessionStatus};use agent_session::domain::ports::MockAgentSessionRepo;use channel_sender::ChannelSender;@@ -64,6 +65,72 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {}}+/// A session rooted at the test message's thread.+fn thread_session(id: AgentSessionId, bot_id: BotId) -> AgentSession {+ AgentSession {+ thread_id: Some(Uuid::from_u128(3)),+ originating_message_id: Some(Uuid::from_u128(3)),+ ..session(id, bot_id)+ }+}++type TestService = AgentTriggerService<+ MockAgentSessionRepo,+ MockAgentBotLookup,+ MockReplyDetector,+ MockImplicitTriggerJudge,+ MockThreadHistory,+>;++/// A service over a thread that reads as empty; tests that care about thread+/// context pass their own history with [`service_reading`].+fn service(+ sessions: MockAgentSessionRepo,+ bots: MockAgentBotLookup,+ replies: MockReplyDetector,+ judge: MockImplicitTriggerJudge,+) -> TestService {+ AgentTriggerService::new(sessions, bots, replies, judge, thread_of(vec![]))+}++fn service_reading(+ sessions: MockAgentSessionRepo,+ bots: MockAgentBotLookup,+ replies: MockReplyDetector,+ judge: MockImplicitTriggerJudge,+ history: MockThreadHistory,+) -> TestService {+ AgentTriggerService::new(sessions, bots, replies, judge, history)+}++/// A history that reads the given messages for any thread.+fn thread_of(messages: Vec<ThreadMessage>) -> MockThreadHistory {+ let mut history = MockThreadHistory::new();+ history.expect_thread_messages().returning(move |_, _| {+ let messages = messages.clone();+ Box::pin(async move { Ok(messages) })+ });+ history+}++/// Mocks for tests whose message never reaches the implicit path; any call is+/// a test failure.+fn no_implicit() -> (MockReplyDetector, MockImplicitTriggerJudge) {+ (MockReplyDetector::new(), MockImplicitTriggerJudge::new())+}++fn existing_channel_metadata(+ events: &[AgentSessionMacroEvent],+) -> &crate::domain::broker_events::ChannelEventMetadata {+ assert_eq!(events.len(), 1);+ let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =+ &events[0].event().event+ else {+ panic!("expected a channel event");+ };+ metadata+}+#[tokio::test]async fn forwards_a_mentioned_thread_reply_to_its_session() {let posted = message(vec![mention_of(BotId::TEST_A)]);@@ -88,15 +155,11 @@ async fn forwards_a_mentioned_thread_reply_to_its_session() {.with(mockall::predicate::eq(BotId::TEST_A)).once().return_once(|_| Box::pin(async { Ok(true) }));- let service = AgentTriggerService::new(sessions, bots);+ let (replies, judge) = no_implicit();+ let service = service(sessions, bots, replies, judge);let events = service.evaluate(&posted).await.expect("evaluate message");- assert_eq!(events.len(), 1);- let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =- &events[0].event().event- else {- panic!("expected a channel event");- };+ let metadata = existing_channel_metadata(&events);assert_eq!(metadata.bot_id, BotId::TEST_A);assert_eq!(metadata.session_id, AgentSessionId::TEST_A);}@@ -106,13 +169,9 @@ async fn forwards_a_mentioned_thread_reply_to_its_session() {#[tokio::test]async fn a_thread_reply_without_a_mention_does_not_forward() {let posted = message(vec![]);- let mut sessions = MockAgentSessionRepo::new();- sessions- .expect_find_for_channel()- .once()- .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));- let bots = MockAgentBotLookup::new();- let service = AgentTriggerService::new(sessions, bots);+ let sessions = implicit_sessions(vec![]);+ let (replies, judge) = no_implicit();+ let service = service(sessions, MockAgentBotLookup::new(), replies, judge);assert!(service@@ -137,7 +196,8 @@ async fn evaluates_every_mentioned_agent_bot() {bots.expect_has_agent().times(2).returning(|_| Box::pin(async { Ok(true) }));- let service = AgentTriggerService::new(sessions, bots);+ let (replies, judge) = no_implicit();+ let service = service(sessions, bots, replies, judge);let events = service.evaluate(&posted).await.expect("evaluate message");assert_eq!(events.len(), 2);@@ -171,7 +231,8 @@ async fn evaluates_a_repeated_bot_mention_once() {.with(mockall::predicate::eq(BotId::TEST_A)).once().return_once(|_| Box::pin(async { Ok(true) }));- let service = AgentTriggerService::new(sessions, bots);+ let (replies, judge) = no_implicit();+ let service = service(sessions, bots, replies, judge);let events = service.evaluate(&posted).await.expect("evaluate message");assert_eq!(events.len(), 1);@@ -196,7 +257,8 @@ async fn ignores_a_mentioned_bot_without_an_agent() {.with(mockall::predicate::eq(BotId::TEST_A)).once().return_once(|_| Box::pin(async { Ok(false) }));- let service = AgentTriggerService::new(sessions, bots);+ let (replies, judge) = no_implicit();+ let service = service(sessions, bots, replies, judge);assert!(service@@ -227,14 +289,332 @@ async fn deduplicates_a_session_found_for_multiple_mentions() {.with(mockall::predicate::eq(BotId::TEST_A)).once().return_once(|_| Box::pin(async { Ok(true) }));- let service = AgentTriggerService::new(sessions, bots);+ let (replies, judge) = no_implicit();+ let service = service(sessions, bots, replies, judge);let events = service.evaluate(&posted).await.expect("evaluate message");- assert_eq!(events.len(), 1);- let AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) =- &events[0].event().event- else {- panic!("expected a channel event");- };+ let metadata = existing_channel_metadata(&events);assert_eq!(metadata.session_id, AgentSessionId::TEST_A);}++/// Session repo mocks for the implicit path: no session owns the message's+/// channel, and its thread carries the given sessions.+fn implicit_sessions(found: Vec<AgentSession>) -> MockAgentSessionRepo {+ let mut sessions = MockAgentSessionRepo::new();+ sessions+ .expect_find_for_channel()+ .once()+ .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));+ sessions+ .expect_find_all_for_thread()+ .with(mockall::predicate::eq(Uuid::from_u128(3)))+ .once()+ .return_once(move |_| Box::pin(async move { Ok(found) }));+ sessions+}++fn agent_bots() -> MockAgentBotLookup {+ let mut bots = MockAgentBotLookup::new();+ bots.expect_has_agent()+ .returning(|_| Box::pin(async { Ok(true) }));+ bots+}++fn detector(result: Result<bool>) -> MockReplyDetector {+ let mut replies = MockReplyDetector::new();+ replies+ .expect_is_quote_reply()+ .once()+ .return_once(move |_| Box::pin(async move { result }));+ replies+}++fn judge_saying(result: Result<bool>) -> MockImplicitTriggerJudge {+ let mut judge = MockImplicitTriggerJudge::new();+ judge+ .expect_is_addressed_to_agent()+ .once()+ .return_once(move |_, _| Box::pin(async move { result }));+ judge+}++/// A judge that asserts on the transcript it was handed, and says yes.+fn judge_expecting(transcript: &'static str) -> MockImplicitTriggerJudge {+ let mut judge = MockImplicitTriggerJudge::new();+ judge+ .expect_is_addressed_to_agent()+ .once()+ .return_once(move |_, given| {+ assert_eq!(given, transcript);+ Box::pin(async { Ok(true) })+ });+ judge+}++fn thread_message(id: u128, sender: ChannelSender<'static>, content: &str) -> ThreadMessage {+ ThreadMessage {+ id: Uuid::from_u128(id),+ sender,+ content: content.to_owned(),+ created_at: Utc::now(),+ }+}++#[tokio::test]+async fn a_quote_reply_in_a_session_thread_triggers_without_a_mention() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let service = service(+ sessions,+ agent_bots(),+ detector(Ok(true)),+ MockImplicitTriggerJudge::new(),+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ let metadata = existing_channel_metadata(&events);+ assert_eq!(metadata.session_id, AgentSessionId::TEST_A);+ assert_eq!(metadata.bot_id, BotId::TEST_A);+ assert_eq!(metadata.kind, ChannelKind::QuoteReply);+}++#[tokio::test]+async fn a_message_the_judge_reads_as_addressed_triggers_as_inferred() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let service = service(+ sessions,+ agent_bots(),+ detector(Ok(false)),+ judge_saying(Ok(true)),+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ let metadata = existing_channel_metadata(&events);+ assert_eq!(metadata.kind, ChannelKind::Inferred);+}++#[tokio::test]+async fn a_message_addressed_to_nobody_yields_nothing() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let service = service(+ sessions,+ agent_bots(),+ detector(Ok(false)),+ judge_saying(Ok(false)),+ );++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn a_thread_without_sessions_never_consults_the_judge() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![]);+ let (replies, judge) = no_implicit();+ let service = service(sessions, MockAgentBotLookup::new(), replies, judge);++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn a_bot_sender_never_triggers_implicitly() {+ let mut posted = message(vec![]);+ posted.sender = ChannelSender::new_from_bot(BotId::TEST_B);+ let mut sessions = MockAgentSessionRepo::new();+ sessions+ .expect_find_for_channel()+ .once()+ .return_once(|_, _| Box::pin(async { Ok(ChannelSession::None) }));+ let (replies, judge) = no_implicit();+ let service = service(sessions, MockAgentBotLookup::new(), replies, judge);++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn implicit_triggering_skips_sessions_of_agentless_bots() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![+ thread_session(AgentSessionId::TEST_A, BotId::TEST_A),+ thread_session(AgentSessionId::TEST_B, BotId::TEST_B),+ ]);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_has_agent()+ .with(mockall::predicate::eq(BotId::TEST_A))+ .once()+ .return_once(|_| Box::pin(async { Ok(false) }));+ bots.expect_has_agent()+ .with(mockall::predicate::eq(BotId::TEST_B))+ .once()+ .return_once(|_| Box::pin(async { Ok(true) }));+ let service = service(+ sessions,+ bots,+ detector(Ok(true)),+ MockImplicitTriggerJudge::new(),+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ let metadata = existing_channel_metadata(&events);+ assert_eq!(metadata.session_id, AgentSessionId::TEST_B);+ assert_eq!(metadata.bot_id, BotId::TEST_B);+}++#[tokio::test]+async fn two_live_agents_in_a_thread_yield_nothing() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![+ thread_session(AgentSessionId::TEST_A, BotId::TEST_A),+ thread_session(AgentSessionId::TEST_B, BotId::TEST_B),+ ]);+ let (replies, judge) = no_implicit();+ let service = service(sessions, agent_bots(), replies, judge);++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn a_failing_detector_falls_through_to_the_judge() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let service = service(+ sessions,+ agent_bots(),+ detector(Err(AgentSessionError::Unknown(anyhow::anyhow!(+ "lexical service unavailable"+ )))),+ judge_saying(Ok(true)),+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ assert_eq!(+ existing_channel_metadata(&events).kind,+ ChannelKind::Inferred+ );+}++#[tokio::test]+async fn a_failing_judge_yields_nothing_instead_of_an_error() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let service = service(+ sessions,+ agent_bots(),+ detector(Ok(false)),+ judge_saying(Err(AgentSessionError::Unknown(anyhow::anyhow!(+ "model unavailable"+ )))),+ );++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn the_judge_reads_the_thread_around_the_agent() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ // Message 2 is the one being evaluated, so both it and the agent's own+ // message anchor a window; message 0 falls outside both.+ let history = thread_of(vec![+ thread_message(0, ChannelSender::new_from_user(user()), "unrelated chatter"),+ thread_message(1, ChannelSender::new_from_bot(BotId::TEST_A), "on it"),+ thread_message(2, ChannelSender::new_from_user(user()), "hello"),+ ]);+ let service = service_reading(+ sessions,+ agent_bots(),+ detector(Ok(false)),+ judge_expecting(+ "[user macro|[email protected]] unrelated chatter\n\+ [agent] on it\n\+ [user macro|[email protected]] hello\n",+ ),+ history,+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ assert_eq!(+ existing_channel_metadata(&events).kind,+ ChannelKind::Inferred+ );+}++#[tokio::test]+async fn a_quote_reply_never_reads_the_thread() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let mut history = MockThreadHistory::new();+ history.expect_thread_messages().never();+ let service = service_reading(+ sessions,+ agent_bots(),+ detector(Ok(true)),+ MockImplicitTriggerJudge::new(),+ history,+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ assert_eq!(+ existing_channel_metadata(&events).kind,+ ChannelKind::QuoteReply+ );+}++#[tokio::test]+async fn an_unreadable_thread_still_judges_the_message_alone() {+ let posted = message(vec![]);+ let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);+ let mut history = MockThreadHistory::new();+ history.expect_thread_messages().once().return_once(|_, _| {+ Box::pin(async {+ Err(AgentSessionError::Unknown(anyhow::anyhow!(+ "channels database unavailable"+ )))+ })+ });+ let service = service_reading(+ sessions,+ agent_bots(),+ detector(Ok(false)),+ judge_expecting(""),+ history,+ );++ let events = service.evaluate(&posted).await.expect("evaluate message");+ assert_eq!(+ existing_channel_metadata(&events).kind,+ ChannelKind::Inferred+ );+}diff --git a/crates/agent_trigger/src/domain/thread_window.rs b/crates/agent_trigger/src/domain/thread_window.rsnew file mode 100644index 0000000000..77a7dec0a5--- /dev/null+++ b/crates/agent_trigger/src/domain/thread_window.rs@@ -0,0 +1,120 @@+//! Thread context around the points where an agent was addressed.++use std::fmt::Write as _;++use bot_id::BotId;+use channel_sender::ChannelSender;+use chrono::{DateTime, Utc};+use macro_uuid::Uuid;++#[cfg(test)]+mod test;++/// One message of a thread.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ThreadMessage {+ /// Message id.+ pub id: Uuid,+ /// Who posted it.+ pub sender: ChannelSender<'static>,+ /// Message body.+ pub content: String,+ /// When it was posted.+ pub created_at: DateTime<Utc>,+}++/// A transcript entry: a kept message, or a note that some were dropped.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum TranscriptEntry<'a> {+ /// A message inside one of the windows.+ Message(&'a ThreadMessage),+ /// Messages between two windows, or before the first one.+ Elided {+ /// How many were dropped.+ count: usize,+ },+}++/// Messages within `radius` of any of `anchors`, oldest first, capped to the+/// `cap` most recent.+///+/// Overlapping windows merge, and every gap between kept messages becomes an+/// [`TranscriptEntry::Elided`] so a reader can tell the thread is not+/// contiguous. Anchors not present in `messages` are ignored; empty when none+/// of them are.+#[must_use]+pub fn thread_window<'a>(+ messages: &'a [ThreadMessage],+ anchors: &[Uuid],+ radius: usize,+ cap: usize,+) -> Vec<TranscriptEntry<'a>> {+ let anchored = messages+ .iter()+ .enumerate()+ .filter(|(_, message)| anchors.contains(&message.id));++ let mut kept: Vec<usize> = Vec::new();+ for (index, _) in anchored {+ let start = index.saturating_sub(radius);+ let end = (index + radius).min(messages.len().saturating_sub(1));+ kept.extend(start..=end);+ }+ kept.sort_unstable();+ kept.dedup();+ if kept.is_empty() {+ return Vec::new();+ }+ // Oldest first out, so the cap keeps the context nearest the message being+ // evaluated rather than the oldest mention in the thread.+ if kept.len() > cap {+ kept.drain(..kept.len() - cap);+ }++ let mut entries = Vec::with_capacity(kept.len() + 1);+ let mut previous: Option<usize> = None;+ for index in kept {+ let gap = match previous {+ Some(previous) => index - previous - 1,+ None => index,+ };+ if gap > 0 {+ entries.push(TranscriptEntry::Elided { count: gap });+ }+ entries.push(TranscriptEntry::Message(&messages[index]));+ previous = Some(index);+ }+ entries+}++/// Renders a transcript for a judge reading the thread, labelling `agent`'s own+/// messages so it can tell which participant it is deciding about.+///+/// Other bots keep their raw ids: a second bot in the thread is a participant+/// like any other, and mislabelling it as the agent would invite the judge to+/// answer about the wrong one.+#[must_use]+pub fn render_transcript(entries: &[TranscriptEntry<'_>], agent: BotId) -> String {+ let agent = agent.into_storage_id();+ let mut rendered = String::new();+ for entry in entries {+ match entry {+ TranscriptEntry::Elided { count } => {+ let plural = if *count == 1 { "" } else { "s" };+ let _ = writeln!(rendered, "({count} earlier message{plural} hidden)");+ }+ TranscriptEntry::Message(message) => {+ let speaker = match (message.sender.as_bot(), message.sender.as_user()) {+ (Some(bot), _) if bot.as_ref() == agent.as_ref() => "agent".to_owned(),+ (Some(bot), _) => format!("bot {bot}"),+ (None, Some(user)) => format!("user {user}"),+ // A sender is one or the other; a future third kind should+ // still appear in the transcript rather than vanish.+ (None, None) => "unknown".to_owned(),+ };+ let _ = writeln!(rendered, "[{speaker}] {}", message.content);+ }+ }+ }+ rendered+}diff --git a/crates/agent_trigger/src/domain/thread_window/test.rs b/crates/agent_trigger/src/domain/thread_window/test.rsnew file mode 100644index 0000000000..c359750b42--- /dev/null+++ b/crates/agent_trigger/src/domain/thread_window/test.rs@@ -0,0 +1,181 @@+use super::*;++use chrono::TimeZone as _;+use macro_user_id::cowlike::CowLike as _;+use macro_user_id::user_id::MacroUserIdStr;++fn thread(len: u128) -> Vec<ThreadMessage> {+ (0..len)+ .map(|index| ThreadMessage {+ id: Uuid::from_u128(index),+ sender: ChannelSender::new_from_user(+ MacroUserIdStr::parse_from_str("macro|[email protected]")+ .expect("a valid user id")+ .into_owned(),+ ),+ content: format!("message {index}"),+ created_at: Utc+ .timestamp_opt(1_700_000_000 + index as i64, 0)+ .single()+ .expect("a valid timestamp"),+ })+ .collect()+}++fn anchors(indices: &[u128]) -> Vec<Uuid> {+ indices+ .iter()+ .map(|index| Uuid::from_u128(*index))+ .collect()+}++fn ids(entries: &[TranscriptEntry<'_>]) -> Vec<u128> {+ entries+ .iter()+ .filter_map(|entry| match entry {+ TranscriptEntry::Message(message) => Some(message.id.as_u128()),+ TranscriptEntry::Elided { .. } => None,+ })+ .collect()+}++fn elisions(entries: &[TranscriptEntry<'_>]) -> Vec<usize> {+ entries+ .iter()+ .filter_map(|entry| match entry {+ TranscriptEntry::Elided { count } => Some(*count),+ TranscriptEntry::Message(_) => None,+ })+ .collect()+}++#[test]+fn a_thread_with_no_anchors_yields_nothing() {+ let messages = thread(10);++ assert!(thread_window(&messages, &[], 2, 60).is_empty());+}++#[test]+fn an_anchor_that_is_not_in_the_thread_is_ignored() {+ let messages = thread(5);++ let entries = thread_window(&messages, &anchors(&[99]), 2, 60);++ assert!(entries.is_empty());+}++#[test]+fn a_window_spans_the_radius_on_both_sides_of_the_anchor() {+ let messages = thread(11);++ let entries = thread_window(&messages, &anchors(&[5]), 2, 60);++ assert_eq!(ids(&entries), vec![3, 4, 5, 6, 7]);+}++#[test]+fn a_window_clamps_at_both_ends_of_the_thread() {+ let messages = thread(3);++ let entries = thread_window(&messages, &anchors(&[0, 2]), 10, 60);++ assert_eq!(ids(&entries), vec![0, 1, 2]);+ assert!(elisions(&entries).is_empty());+}++#[test]+fn overlapping_windows_merge_without_repeating_a_message() {+ let messages = thread(10);++ let entries = thread_window(&messages, &anchors(&[3, 5]), 2, 60);++ assert_eq!(ids(&entries), vec![1, 2, 3, 4, 5, 6, 7]);+}++#[test]+fn a_gap_between_windows_is_marked_elided() {+ let messages = thread(20);++ let entries = thread_window(&messages, &anchors(&[2, 15]), 1, 60);++ assert_eq!(ids(&entries), vec![1, 2, 3, 14, 15, 16]);+ // Message 0 before the first window, then 4..=13 between the two.+ assert_eq!(elisions(&entries), vec![1, 10]);+}++#[test]+fn the_cap_keeps_the_most_recent_messages() {+ let messages = thread(20);++ let entries = thread_window(&messages, &anchors(&[2, 15]), 1, 4);++ assert_eq!(ids(&entries), vec![3, 14, 15, 16]);+}++#[test]+fn a_capped_transcript_still_reports_what_it_dropped() {+ let messages = thread(20);++ let entries = thread_window(&messages, &anchors(&[2, 15]), 1, 4);++ // Everything before message 3, then 4..=13 between the two windows.+ assert_eq!(elisions(&entries), vec![3, 10]);+}++fn bot_thread() -> Vec<ThreadMessage> {+ let mut messages = thread(3);+ messages[1].sender = ChannelSender::new_from_bot(BotId::TEST_A);+ messages[2].sender = ChannelSender::new_from_bot(BotId::TEST_B);+ messages+}++#[test]+fn a_rendered_transcript_marks_the_agents_own_messages() {+ let messages = bot_thread();++ let rendered = render_transcript(+ &thread_window(&messages, &anchors(&[1]), 2, 60),+ BotId::TEST_A,+ );++ assert_eq!(+ rendered,+ format!(+ "[user macro|[email protected]] message 0\n\+ [agent] message 1\n\+ [bot {}] message 2\n",+ BotId::TEST_B.into_storage_id()+ )+ );+}++#[test]+fn a_rendered_transcript_says_where_messages_were_dropped() {+ let messages = thread(20);++ let rendered = render_transcript(+ &thread_window(&messages, &anchors(&[15]), 1, 60),+ BotId::TEST_A,+ );++ assert!(+ rendered.starts_with("(14 earlier messages hidden)\n"),+ "unexpected transcript: {rendered}"+ );+}++#[test]+fn a_single_dropped_message_reads_as_one() {+ let messages = thread(3);++ let rendered = render_transcript(+ &thread_window(&messages, &anchors(&[1]), 0, 60),+ BotId::TEST_A,+ );++ assert!(+ rendered.starts_with("(1 earlier message hidden)\n"),+ "unexpected transcript: {rendered}"+ );+}diff --git a/crates/agent_trigger/src/domain/yield_event.rs b/crates/agent_trigger/src/domain/yield_event.rsindex 649cd79b9e..c395a07368 100644--- a/crates/agent_trigger/src/domain/yield_event.rs+++ b/crates/agent_trigger/src/domain/yield_event.rs@@ -7,7 +7,8 @@ use channels::domain::broker_events::ChannelMessagePostedMetadata;use channels::domain::side_effects::bot_mention_ids;use crate::domain::broker_events::{- AgentBotMentionedEvent, AgentSessionMacroEvent, ChannelEventMetadata, NewAgentSessionEvent,+ AgentBotMentionedEvent, AgentSessionMacroEvent, ChannelEventMetadata, ChannelKind,+ NewAgentSessionEvent,};/// Why evaluating a message did not produce an agent-session event.@@ -38,6 +39,18 @@ pub enum NoEventReason {/// Session already evaluated for this message.session_id: AgentSessionId,},+ /// The message sat in a session's thread without a mention, and neither+ /// quote-reply detection nor the model judged it addressed to the agent.+ NotAddressedToAgent {+ /// Session whose thread carried the message.+ session_id: AgentSessionId,+ },+ /// Several agents are live in the thread and nothing said which one the+ /// message was for.+ AmbiguousAgentSessions {+ /// How many agent-backed sessions the thread carried.+ candidates: usize,+ },}/// Result of evaluating one message for one bot and session context.@@ -141,6 +154,7 @@ fn yield_channel_event(AgentSessionMacroEvent::channel_event(ChannelEventMetadata {bot_id: session_bot,session_id: session.id,+ kind: ChannelKind::MentionThread,message: posted.clone(),}),),diff --git a/crates/agent_trigger/src/lib.rs b/crates/agent_trigger/src/lib.rsindex d7abca180c..006b073cae 100644--- a/crates/agent_trigger/src/lib.rs+++ b/crates/agent_trigger/src/lib.rs@@ -1 +1,2 @@pub mod domain;+pub mod outbound;diff --git a/crates/agent_trigger/src/outbound/channel_thread_history.rs b/crates/agent_trigger/src/outbound/channel_thread_history.rsnew file mode 100644index 0000000000..32cf338c65--- /dev/null+++ b/crates/agent_trigger/src/outbound/channel_thread_history.rs@@ -0,0 +1,78 @@+//! Thread history assembled from the channels repository.++use agent_session::domain::error::{AgentSessionError, Result};+use channel_sender::ChannelSender;+use channels::domain::ports::ChannelRepo;+use macro_uuid::Uuid;++use crate::domain::service::ThreadHistory;+use crate::domain::thread_window::ThreadMessage;++/// Reads a thread as its root message followed by its replies.+pub struct ChannelThreadHistory<Repo> {+ repo: Repo,+}++impl<Repo> ChannelThreadHistory<Repo> {+ /// Creates a reader over the given channels repository.+ pub const fn new(repo: Repo) -> Self {+ Self { repo }+ }+}++/// A sender that will not parse drops its message rather than failing the+/// read: one unreadable row must not blind the judge to the whole thread.+fn thread_message(+ id: Uuid,+ sender_id: String,+ content: String,+ created_at: chrono::DateTime<chrono::Utc>,+) -> Option<ThreadMessage> {+ let sender = ChannelSender::try_from(sender_id)+ .inspect_err(|error| {+ tracing::warn!(error = ?error, message_id = %id, "skipping thread message with an unparseable sender");+ })+ .ok()?;+ Some(ThreadMessage {+ id,+ sender,+ content,+ created_at,+ })+}++impl<Repo> ThreadHistory for ChannelThreadHistory<Repo>+where+ Repo: ChannelRepo,+{+ async fn thread_messages(+ &self,+ channel_id: Uuid,+ thread_id: Uuid,+ ) -> Result<Vec<ThreadMessage>> {+ // The root is not one of its own replies, and it is where the mention+ // that opened the session lives.+ let root = self+ .repo+ .resolve_top_level_parent(channel_id, thread_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))?+ .filter(|root| root.deleted_at.is_none())+ .and_then(|root| {+ thread_message(root.id, root.sender_id, root.content, root.created_at)+ });++ let replies = self+ .repo+ .get_thread_replies(thread_id)+ .await+ .map_err(|error| AgentSessionError::Unknown(error.into()))?;++ Ok(root+ .into_iter()+ .chain(replies.into_iter().filter_map(|reply| {+ thread_message(reply.id, reply.sender_id, reply.content, reply.created_at)+ }))+ .collect())+ }+}diff --git a/crates/agent_trigger/src/outbound/fast_model_judge.rs b/crates/agent_trigger/src/outbound/fast_model_judge.rsnew file mode 100644index 0000000000..ee3b341e16--- /dev/null+++ b/crates/agent_trigger/src/outbound/fast_model_judge.rs@@ -0,0 +1,116 @@+//! Implicit-trigger judgement backed by the fast agent model.++use std::sync::Arc;++use agent::structured_output::{DynamicSchema, dynamic_structured_completion};+use agent::{Message, PredefinedModel};+use agent_session::domain::error::Result;+use ai_usage::{AiFeature, UsageContext, UsageRecorder};+use channels::domain::broker_events::ChannelMessagePostedMetadata;+use serde::Deserialize;+use serde_json::json;++use crate::domain::service::ImplicitTriggerJudge;++static SYSTEM_PROMPT: &str = "\+You decide whether a channel message is addressed to an AI coding agent.++The message was posted, without mentioning anyone, in a thread where an AI \+coding agent has an open session: the agent was asked to do work earlier in \+the thread and posts its progress there. Decide whether this new message is \+directed at that agent - a follow-up instruction, question, correction, or \+feedback the agent should act on - or is conversation between the people in \+the thread.++Return true only when the message reads as something its author expects the \+agent to respond to. Return false when it is commentary about the agent or \+its work addressed to other people, or unrelated discussion.++You are given the thread around the agent's part in it, as lines of \+'[speaker] message' where the agent's own messages are marked '[agent]'. Some \+messages may be hidden; judge on what you are shown.";++#[derive(Debug, Deserialize)]+struct JudgeOutput {+ addressed_to_agent: bool,+ #[expect(dead_code, reason = "the model reasons better when asked to explain")]+ reason: String,+}++/// Judges implicit triggers with [`PredefinedModel::Fast`], recording token+/// usage against the message's sender.+pub struct FastModelTriggerJudge {+ model: PredefinedModel,+ recorder: Arc<dyn UsageRecorder>,+}++impl FastModelTriggerJudge {+ /// Creates a judge using the fast agent model.+ pub fn new(recorder: Arc<dyn UsageRecorder>) -> Self {+ Self {+ model: PredefinedModel::Fast,+ recorder,+ }+ }+}++impl ImplicitTriggerJudge for FastModelTriggerJudge {+ async fn is_addressed_to_agent(+ &self,+ posted: &ChannelMessagePostedMetadata,+ transcript: &str,+ ) -> Result<bool> {+ let schema = DynamicSchema {+ name: "ImplicitTriggerJudgeOutput".to_string(),+ description: Some(+ "Judgement for whether a thread message is addressed to the agent.".to_string(),+ ),+ schema: json!({+ "type": "object",+ "additionalProperties": false,+ "required": ["addressed_to_agent", "reason"],+ "properties": {+ "addressed_to_agent": {+ "type": "boolean",+ "description": "True only if the message is directed at the agent."+ },+ "reason": {+ "type": "string",+ "description": "A concise reason for the judgement."+ }+ }+ }),+ };+ // The judge runs on behalf of whoever posted the message, so their+ // account carries the tokens; a non-user sender never reaches this+ // point, but attribute it to the system rather than fail if one does.+ let ctx = match posted.sender.as_user() {+ Some(user) => UsageContext::new(AiFeature::Automation, user.clone()),+ None => UsageContext::system(AiFeature::Automation),+ };++ let prompt = if transcript.is_empty() {+ format!("The message to judge:\n{}", posted.content)+ } else {+ format!(+ "The thread so far:\n{transcript}\nThe message to judge:\n{}",+ posted.content+ )+ };++ let value = dynamic_structured_completion(+ self.model,+ SYSTEM_PROMPT,+ vec![Message::user(prompt)],+ schema,+ self.recorder.as_ref(),+ ctx,+ )+ .await?;++ let output: JudgeOutput = serde_json::from_value(value).map_err(|error| {+ anyhow::anyhow!("implicit trigger judge returned malformed output: {error}")+ })?;+ Ok(output.addressed_to_agent)+ }+}diff --git a/crates/agent_trigger/src/outbound/lexical_reply_detector.rs b/crates/agent_trigger/src/outbound/lexical_reply_detector.rsnew file mode 100644index 0000000000..ebad953ffb--- /dev/null+++ b/crates/agent_trigger/src/outbound/lexical_reply_detector.rs@@ -0,0 +1,25 @@+//! Quote-reply detection backed by the lexical service.++use agent_session::domain::error::Result;+use lexical_client::LexicalClient;++use crate::domain::service::ReplyDetector;++/// Detects quote-replies by parsing the markdown with the lexical service,+/// so detection matches the nodes the editor itself produces.+pub struct LexicalReplyDetector {+ client: LexicalClient,+}++impl LexicalReplyDetector {+ /// Creates a detector calling the given lexical service client.+ pub const fn new(client: LexicalClient) -> Self {+ Self { client }+ }+}++impl ReplyDetector for LexicalReplyDetector {+ async fn is_quote_reply(&self, markdown: &str) -> Result<bool> {+ Ok(self.client.is_quote_reply(markdown).await?)+ }+}diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rsnew file mode 100644index 0000000000..403e63efac--- /dev/null+++ b/crates/agent_trigger/src/outbound/mod.rs@@ -0,0 +1,9 @@+//! Adapters implementing the trigger's implicit-evaluation ports.++mod channel_thread_history;+mod fast_model_judge;+mod lexical_reply_detector;++pub use channel_thread_history::ChannelThreadHistory;+pub use fast_model_judge::FastModelTriggerJudge;+pub use lexical_reply_detector::LexicalReplyDetector;diff --git a/crates/coding_agent_worker/src/webhook/test.rs b/crates/coding_agent_worker/src/webhook/test.rsindex 106708fe86..2fdd790db1 100644--- a/crates/coding_agent_worker/src/webhook/test.rs+++ b/crates/coding_agent_worker/src/webhook/test.rs@@ -45,6 +45,7 @@ fn follow_up(content: &str) -> AgentTriggerTopicEvent {agent_trigger::domain::broker_events::ChannelEventMetadata {bot_id: bot_id::BotId::TEST_A,session_id: test_session(),+ kind: agent_trigger::domain::broker_events::ChannelKind::MentionThread,message: message(content, Some(Uuid::from_u128(7))),},))diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rsindex fecc1d98f0..ae115863e1 100644--- a/crates/lexical_client/src/parse_markdown.rs+++ b/crates/lexical_client/src/parse_markdown.rs@@ -34,6 +34,17 @@ struct MentionsRequest<'a> {markdown: &'a str,}+#[derive(Debug, serde::Serialize)]+struct QuoteReplyRequest<'a> {+ markdown: &'a str,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+struct QuoteReplyResponse {+ is_quote_reply: bool,+}+/// An entity mention extracted from markdown by the lexical service/// `/mentions` endpoint, in the shape channel messages track them.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]@@ -290,6 +301,24 @@ impl LexicalClient {Ok(data.markdown)}+ /// Parses `markdown` via the lexical service and reports whether it is+ /// composed as a quote-reply: a leading blockquote followed by the reply+ /// itself, the shape the editor produces when replying to a message.+ #[tracing::instrument(skip(self, markdown), err)]+ pub async fn is_quote_reply(&self, markdown: &str) -> Result<bool> {+ let url = format!("{}/quote-reply", self.url);+ let response = check_response(+ self.client+ .post(&url)+ .json(&QuoteReplyRequest { markdown })+ .send()+ .await?,+ )+ .await?;+ let data: QuoteReplyResponse = response.json().await.context("unexpected response")?;+ Ok(data.is_quote_reply)+ }+async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T> {let response = check_response(self.client.get(url).send().await?).await?;response.json().await.context("unexpected response")diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 9c8e6846d3..56203bcfcd 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -1345,6 +1345,7 @@ fn agent_trigger_existing_event()ExistingAgentSessionEvent::Channel(ChannelEventMetadata {bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),session_id: agent_session::domain::model::AgentSessionId::TEST_A,+ kind: agent_trigger::domain::broker_events::ChannelKind::MentionThread,message: ChannelMessagePostedMetadata {channel_id: uuid::Uuid::from_u128(1),message_id: uuid::Uuid::from_u128(2),diff --git a/docker/docker-compose.yml b/docker/docker-compose.ymlindex 95226b3641..3e9ff6237f 100644--- a/docker/docker-compose.yml+++ b/docker/docker-compose.yml@@ -314,6 +314,9 @@ services:# In-network gateway address; the local default (http://localhost:8082)# would point at this container itself.- OVERRIDE_CONNECTION_GATEWAY_URL=http://connection-gateway:8080+ # In-network lexical address; the local default (http://localhost:8096)+ # would point at this container itself.+ - OVERRIDE_LEXICAL_SERVICE_URL=http://lexical-service:8096volumes:# The local container provider drives the host's Docker daemon, so# sandboxes are siblings of this container rather than children. Harmless@@ -323,6 +326,7 @@ services:- postgres- kafka- connection_gateway+ - lexical_servicenetworks:- databases- servicesdiff --git a/packages/lexical-core/tests/quote-reply.test.ts b/packages/lexical-core/tests/quote-reply.test.tsnew file mode 100644index 0000000000..61a22d429c--- /dev/null+++ b/packages/lexical-core/tests/quote-reply.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { isQuoteReplyMarkdown } from '../utils/quote-reply';++describe('isQuoteReplyMarkdown', () => {+ it('detects a quote followed by a reply', () => {+ expect(isQuoteReplyMarkdown('> can you fix the tests\n\nyes, on it')).toBe(+ true+ );+ });++ it('detects a multi-line quote', () => {+ expect(+ isQuoteReplyMarkdown('> first line\n> second line\n\nlooks right to me')+ ).toBe(true);+ });++ it('rejects plain text', () => {+ expect(isQuoteReplyMarkdown('just a normal message')).toBe(false);+ });++ it('rejects a bare quote with no reply', () => {+ expect(isQuoteReplyMarkdown('> quoted with nothing to say')).toBe(false);+ });++ it('rejects a quote appearing after the reply', () => {+ expect(isQuoteReplyMarkdown('as I said\n\n> earlier message')).toBe(false);+ });++ it('rejects empty markdown', () => {+ expect(isQuoteReplyMarkdown('')).toBe(false);+ });+});diff --git a/packages/lexical-core/utils/quote-reply.ts b/packages/lexical-core/utils/quote-reply.tsnew file mode 100644index 0000000000..125abe1626--- /dev/null+++ b/packages/lexical-core/utils/quote-reply.ts@@ -0,0 +1,35 @@+import { createHeadlessEditor } from '@lexical/headless';+import { $convertFromMarkdownString } from '@lexical/markdown';+import { $isQuoteNode } from '@lexical/rich-text';+import { $getRoot } from 'lexical';+import { NodeReplacements, SupportedNodeTypes } from '../node-list';+import { ALL_TRANSFORMERS } from '../transformers';++/**+ * Whether a macro markdown string is composed as a quote-reply: a leading+ * blockquote quoting the replied-to message, followed by the reply itself —+ * the shape `buildQuoteReplyValue` produces in the channel input.+ *+ * A bare blockquote with nothing after it is not a reply; there is no message+ * of the author's own.+ */+export function isQuoteReplyMarkdown(markdown: string): boolean {+ const editor = createHeadlessEditor({+ nodes: [...SupportedNodeTypes, ...NodeReplacements],+ });++ editor.update(+ () => {+ $convertFromMarkdownString(markdown, ALL_TRANSFORMERS);+ },+ { discrete: true }+ );++ return editor.getEditorState().read(() => {+ const [first, ...rest] = $getRoot().getChildren();+ return (+ $isQuoteNode(first) &&+ rest.some((node) => node.getTextContent().trim() !== '')+ );+ });+}diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 28b0134a0c..b874fbc8c6 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -413,6 +413,7 @@ async fn run() -> anyhow::Result<()> {let mut trigger = tokio::spawn(trigger::supervise(pool.clone(),config.kafka_brokers.as_ref().to_owned(),+ config.internal_api_key.clone(),));// The consumer: every agent-session event, filtered to our bot.diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rsindex eaf9ce9bc3..b88d19c1a5 100644--- a/services/agent_harness_service/src/trigger.rs+++ b/services/agent_harness_service/src/trigger.rs@@ -3,15 +3,19 @@use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;use agent_trigger::domain::service::{AgentBotLookup, AgentTriggerService};+use agent_trigger::outbound::{ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector};use bot_id::BotId;use bots::domain::ports::BotRepo as _;use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::broker_events::ChannelMacroEvent;+use channels::outbound::pg_channels_repo::PgChannelsRepo;use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};+use lexical_client::LexicalClient;use macro_event_broker::{KafkaConsumerAdapter, KafkaEventPublisher, MacroEvent as _, MacroEventBrokerService,MacroEventCollection as _, MacroEventConsumerService,};+use macro_service_urls::LexicalServiceUrl;use rdkafka::consumer::CommitMode;use rdkafka::message::{BorrowedMessage, Message as _};use sqlx::PgPool;@@ -49,19 +53,29 @@ fn commit_message(consumer: &TriggerConsumer, message: &BorrowedMessage<'_>) ->}/// Keeps the channel trigger consumer running across transient failures.-pub async fn supervise(pool: PgPool, kafka_brokers: String) {+pub async fn supervise(pool: PgPool, kafka_brokers: String, internal_api_key: String) {loop {- if let Err(error) = run(pool.clone(), kafka_brokers.clone()).await {+ if let Err(error) = run(+ pool.clone(),+ kafka_brokers.clone(),+ internal_api_key.clone(),+ )+ .await+ {tracing::error!(error = ?error, "agent trigger stopped; restarting");sleep(Duration::from_secs(1)).await;}}}-async fn run(pool: PgPool, kafka_brokers: String) -> anyhow::Result<()> {+async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> anyhow::Result<()> {+ let lexical = LexicalClient::new(internal_api_key, LexicalServiceUrl::new()?.to_string());let trigger = AgentTriggerService::new(PgAgentSessionRepo::new(pool.clone()),- PgAgentBotLookup(PgBotsRepo::new(pool)),+ PgAgentBotLookup(PgBotsRepo::new(pool.clone())),+ LexicalReplyDetector::new(lexical),+ FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),+ ChannelThreadHistory::new(PgChannelsRepo::new(pool)),);let publisher = MacroEventBrokerService::new(KafkaEventPublisher::new(&kafka_brokers)?,diff --git a/services/agent_trigger_service/Cargo.toml b/services/agent_trigger_service/Cargo.tomlindex 9628686155..a326c46605 100644--- a/services/agent_trigger_service/Cargo.toml+++ b/services/agent_trigger_service/Cargo.toml@@ -11,15 +11,18 @@ path = "src/main.rs"[dependencies]agent_session = { path = "../../crates/agent_session" }agent_trigger = { path = "../../crates/agent_trigger" }+ai_usage = { path = "../../crates/ai_usage" }anyhow = { workspace = true }bots = { path = "../../crates/bots", default-features = false, features = ["outbound", "ports"] }-channels = { path = "../../crates/channels", default-features = false, features = ["ports"] }+channels = { path = "../../crates/channels", default-features = false, features = ["outbound", "ports"] }database_env_vars = { path = "../../crates/database_env_vars" }kafka_util = { path = "../../crates/kafka_util" }+lexical_client = { path = "../../crates/lexical_client" }macro_config = { path = "../../crates/macro_config" }macro_entrypoint = { path = "../../crates/macro_entrypoint" }macro_env_var = { path = "../../crates/macro_env_var" }macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }+macro_service_urls = { path = "../../crates/macro_service_urls" }rdkafka = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rsindex 856d9bfde5..7aaa4f7b16 100644--- a/services/agent_trigger_service/src/config.rs+++ b/services/agent_trigger_service/src/config.rs@@ -17,6 +17,8 @@ pub struct Config {pub database_url: DatabaseUrl,/// Kafka bootstrap servers.pub kafka_brokers: KafkaBrokers,+ /// Key for internal service-to-service calls (the lexical service).+ pub internal_api_key: String,}impl Config {diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rsindex 33c45645d7..242cba00dc 100644--- a/services/agent_trigger_service/src/main.rs+++ b/services/agent_trigger_service/src/main.rs@@ -5,18 +5,22 @@ mod config;use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;use agent_trigger::domain::service::{AgentBotLookup, AgentTriggerService};+use agent_trigger::outbound::{ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector};use anyhow::Context as _;use bots::domain::models::BotId;use bots::domain::ports::BotRepo as _;use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::broker_events::ChannelMacroEvent;+use channels::outbound::pg_channels_repo::PgChannelsRepo;use config::Config;use kafka_util::{GroupName, KafkaEventConsumer, consumer_span, record_span_error};+use lexical_client::LexicalClient;use macro_entrypoint::{MacroEntrypoint, shutdown_signal};use macro_event_broker::{KafkaConsumerAdapter, KafkaEventPublisher, MacroEvent as _, MacroEventBrokerService,MacroEventCollection as _, MacroEventConsumerService,};+use macro_service_urls::LexicalServiceUrl;use rdkafka::consumer::CommitMode;use rdkafka::message::{BorrowedMessage, Message as _};use sqlx::postgres::PgPoolOptions;@@ -69,9 +73,16 @@ async fn run() -> anyhow::Result<()> {.await.context("failed to connect to macrodb")?;+ let lexical = LexicalClient::new(+ config.internal_api_key.clone(),+ LexicalServiceUrl::new()?.to_string(),+ );let trigger = AgentTriggerService::new(PgAgentSessionRepo::new(pool.clone()),- PgAgentBotLookup(PgBotsRepo::new(pool)),+ PgAgentBotLookup(PgBotsRepo::new(pool.clone())),+ LexicalReplyDetector::new(lexical),+ FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),+ ChannelThreadHistory::new(PgChannelsRepo::new(pool)),);let publisher = MacroEventBrokerService::new(KafkaEventPublisher::new(config.kafka_brokers.as_ref())?,diff --git a/services/lexical-service/src/endpoints/quote-reply.ts b/services/lexical-service/src/endpoints/quote-reply.tsnew file mode 100644index 0000000000..6d3073ac45--- /dev/null+++ b/services/lexical-service/src/endpoints/quote-reply.ts@@ -0,0 +1,51 @@+import { OpenAPIRoute } from 'chanfana';+import type { Context } from 'hono';+import { z } from 'zod';+import { handleEndpointError } from '../lib/error-handler';+import { standardErrorResponses } from '../lib/schemas';+import { isQuoteReplyMarkdown } from '@macro-inc/lexical-core/utils/quote-reply';++const quoteReplyRequest = z.object({+ markdown: z.string(),+});++const quoteReplyResponse = z.object({+ isQuoteReply: z.boolean(),+});++export class QuoteReplyEndpoint extends OpenAPIRoute {+ schema = {+ summary: 'Detect whether markdown is a quote-reply',+ description:+ 'Parses a macro markdown string as Lexical editor state and reports whether it is composed as a quote-reply: a leading blockquote quoting the replied-to message, followed by the reply itself.',+ request: {+ body: {+ content: {+ 'application/json': {+ schema: quoteReplyRequest,+ },+ },+ },+ },+ responses: {+ 200: {+ description: 'Successfully evaluated the markdown',+ content: {+ 'application/json': {+ schema: quoteReplyResponse,+ },+ },+ },+ ...standardErrorResponses,+ },+ };++ async handle(c: Context) {+ try {+ const { body } = await this.getValidatedData<typeof this.schema>();+ return c.json({ isQuoteReply: isQuoteReplyMarkdown(body.markdown) });+ } catch (error) {+ return handleEndpointError(error, c);+ }+ }+}diff --git a/services/lexical-service/src/index.ts b/services/lexical-service/src/index.tsindex fc7bd1366f..67ec26d6b4 100644--- a/services/lexical-service/src/index.ts+++ b/services/lexical-service/src/index.ts@@ -9,6 +9,7 @@ import { CognitionV2Endpoint } from "./endpoints/cognition-v2";import { MarkdownEndpoint } from "./endpoints/markdown";import { MarkdownSnapshotEndpoint } from "./endpoints/markdown-snapshot";import { MentionsEndpoint } from "./endpoints/mentions";+import { QuoteReplyEndpoint } from "./endpoints/quote-reply";import { XmlEndpoint } from "./endpoints/xml";import { PlaintextEndpoint } from "./endpoints/plaintext";import { SearchTextEndpoint } from "./endpoints/search-text";@@ -42,6 +43,7 @@ app.use("/xml/*", internalAuth);app.use("/markdown/*", internalAuth);app.use("/snapshot/*", internalAuth);app.use("/mentions", internalAuth);+app.use("/quote-reply", internalAuth);app.use("/agent-announcement", internalAuth);app.use("/internal/health", internalAuth);@@ -66,6 +68,7 @@ openapi.get("/markdown/:docId", MarkdownEndpoint);openapi.get("/xml/:docId", XmlEndpoint);openapi.post("/snapshot/markdown", MarkdownSnapshotEndpoint);openapi.post("/mentions", MentionsEndpoint);+openapi.post("/quote-reply", QuoteReplyEndpoint);openapi.post("/agent-announcement", AgentAnnouncementEndpoint);openapi.get("/internal/health", (c) => c.json({ status: "healthy" }));