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(agent-trigger): extract explicit reply targets instead of detecting them (#6144)
Wolf Mermelstein38a04843f46c
diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rsindex 970d7851c5..aa19d2f689 100644--- a/crates/agent_trigger/src/domain/processing.rs+++ b/crates/agent_trigger/src/domain/processing.rs@@ -7,7 +7,7 @@ use macro_event_broker::{EventBrokerError, MacroEvent as _, MacroEventBroker};use super::broker_events::AgentTriggerEventName;use super::service::{- AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyDetector,+ AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyExtractor,ImplicitTriggerJudge, TeamMembershipLookup, ThreadHistory,};@@ -39,7 +39,7 @@ whereBots: AgentBotLookup,Teams: TeamMembershipLookup,Channels: ChannelParticipationLookup,- Replies: ExplicitReplyDetector,+ Replies: ExplicitReplyExtractor,Judge: ImplicitTriggerJudge,History: ThreadHistory,Broker: MacroEventBroker,diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rsindex 5166d538a6..a5a12b610d 100644--- a/crates/agent_trigger/src/domain/service.rs+++ b/crates/agent_trigger/src/domain/service.rs@@ -13,6 +13,7 @@ use bots::domain::models::{Agent, AgentChannelScope, Bot, BotKind, BotOwner};use channels::domain::broker_events::ChannelMessagePostedMetadata;use channels::domain::side_effects::bot_mention_ids;+use channel_sender::ChannelSender;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;@@ -71,12 +72,31 @@ pub trait ChannelParticipationLookup: Send + Sync + 'static {) -> impl Future<Output = Result<bool>> + Send;}-/// Detects whether a message is composed as an explicit reply: a leading-/// reply target followed by the author's response.+/// The leading reply-target of an explicit reply: who the author answered,+/// and which message they pointed at.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExtractedExplicitReply {+ /// Channel containing the targeted message.+ pub channel_id: String,+ /// Targeted channel message.+ pub target_message_id: String,+ /// Thread containing the targeted message.+ pub target_thread_id: String,+ /// Static one-line preview rendered by the reply target.+ pub display_text: String,+ /// Sender of the targeted message — who the author replied to.+ pub sender_id: String,+}++/// Extracts the leading reply-target from markdown composed as an explicit+/// reply: a `ReplyTargetNode` followed by the author's response.#[cfg_attr(test, mockall::automock)]-pub trait ExplicitReplyDetector: Send + Sync + 'static {- /// Whether this markdown is an explicit reply.- fn is_explicit_reply(&self, markdown: &str) -> impl Future<Output = Result<bool>> + Send;+pub trait ExplicitReplyExtractor: Send + Sync + 'static {+ /// The leading reply-target when this markdown is an explicit reply.+ fn extract_explicit_reply(+ &self,+ markdown: &str,+ ) -> impl Future<Output = Result<Option<ExtractedExplicitReply>>> + Send;}/// Reads whole threads, so an unmentioned message can be judged against the@@ -123,7 +143,7 @@ whereBots: AgentBotLookup,Teams: TeamMembershipLookup,Channels: ChannelParticipationLookup,- Replies: ExplicitReplyDetector,+ Replies: ExplicitReplyExtractor,Judge: ImplicitTriggerJudge,History: ThreadHistory,{@@ -306,13 +326,16 @@ where}/// Evaluates an unmentioned message against the sessions rooted at its- /// thread: an explicit reply is forwarded outright, anything else only when- /// the judge reads it as addressed to the agent.+ /// thread: an explicit reply that targets a live session's bot, or that+ /// session's originating message, 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.+ /// An extracted reply names who and which message it answers, so it can+ /// pick among several live agents. The inferred path still only fires when+ /// exactly one agent is live; picking among several by recency would route+ /// on nothing the author meant.///- /// Detector and judge failures are treated as "no" rather than propagated:+ /// Extractor 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(@@ -333,6 +356,19 @@ wherecandidates.push(session);}}++ if !candidates.is_empty()+ && let Some(session) = self.explicit_reply_session(posted, &candidates).await+ {+ // The reply-target says who it answers on its face, so it needs no+ // thread read at all.+ return Ok(Some(channel_event(+ session,+ ChannelKind::ExplicitReply,+ posted,+ )));+ }+let session = match candidates.as_slice() {[] => return Ok(None),[session] => session.clone(),@@ -348,44 +384,43 @@ where}};- let kind = if self.is_explicit_reply(posted).await {- // An explicit reply says who it answers on its face, so it needs no- // thread read at all.- ChannelKind::ExplicitReply- } else if self+ 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);- };+ return Ok(Some(channel_event(session, ChannelKind::Inferred, posted)));+ }- Ok(Some(AgentSessionMacroEvent::channel_event(- ChannelEventMetadata {- bot_id: session.bot_id,+ log_no_event(+ posted,+ None,+ NoEventReason::NotAddressedToAgent {session_id: session.id,- kind,- message: posted.clone(),},- )))+ );+ Ok(None)}- async fn is_explicit_reply(&self, posted: &ChannelMessagePostedMetadata) -> bool {- self.replies- .is_explicit_reply(&posted.content)+ /// The live session the extracted reply-target names: either its bot, or+ /// uniquely its originating message.+ async fn explicit_reply_session(+ &self,+ posted: &ChannelMessagePostedMetadata,+ candidates: &[AgentSession],+ ) -> Option<AgentSession> {+ let reply = self+ .replies+ .extract_explicit_reply(&posted.content).await.inspect_err(|error| {- tracing::warn!(error = ?error, "explicit reply detection failed; treating as not a reply");+ tracing::warn!(+ error = ?error,+ "explicit reply extraction failed; treating as not a reply"+ );})- .unwrap_or(false)+ .ok()+ .flatten()?;+ session_targeted_by_reply(candidates, &reply).cloned()}/// The thread around the points where the agent took part: its own@@ -465,3 +500,49 @@ fn session_id(session: &ChannelSession) -> Option<AgentSessionId> {ChannelSession::None => None,}}++fn channel_event(+ session: AgentSession,+ kind: ChannelKind,+ posted: &ChannelMessagePostedMetadata,+) -> AgentSessionMacroEvent {+ AgentSessionMacroEvent::channel_event(ChannelEventMetadata {+ bot_id: session.bot_id,+ session_id: session.id,+ kind,+ message: posted.clone(),+ })+}++/// The live session the reply-target names: its bot as addressee, or uniquely+/// the message that opened the session.+fn session_targeted_by_reply<'a>(+ candidates: &'a [AgentSession],+ reply: &ExtractedExplicitReply,+) -> Option<&'a AgentSession> {+ if let Some(session) = session_named_by_bot(candidates, reply) {+ return Some(session);+ }+ session_named_by_originating_message(candidates, reply)+}++fn session_named_by_bot<'a>(+ candidates: &'a [AgentSession],+ reply: &ExtractedExplicitReply,+) -> Option<&'a AgentSession> {+ let sender = ChannelSender::parse_from_str(&reply.sender_id).ok()?;+ let bot_id = sender.as_bot()?.bot_id();+ candidates.iter().find(|session| session.bot_id == bot_id)+}++fn session_named_by_originating_message<'a>(+ candidates: &'a [AgentSession],+ reply: &ExtractedExplicitReply,+) -> Option<&'a AgentSession> {+ let target = Uuid::parse_str(&reply.target_message_id).ok()?;+ let mut matches = candidates+ .iter()+ .filter(|session| session.originating_message_id == Some(target));+ let session = matches.next()?;+ matches.next().is_none().then_some(session)+}diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 93cab619c6..c04409a878 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -137,7 +137,7 @@ type TestService = AgentTriggerService<MockAgentBotLookup,MockTeamMembershipLookup,MockChannelParticipationLookup,- MockExplicitReplyDetector,+ MockExplicitReplyExtractor,MockImplicitTriggerJudge,MockThreadHistory,>;@@ -165,7 +165,7 @@ impl From<MockAgentBotLookup> for FactMocks {fn service(sessions: MockAgentSessionRepo,facts: impl Into<FactMocks>,- replies: MockExplicitReplyDetector,+ replies: MockExplicitReplyExtractor,judge: MockImplicitTriggerJudge,) -> TestService {service_reading(sessions, facts, replies, judge, thread_of(vec![]))@@ -174,7 +174,7 @@ fn service(fn service_reading(sessions: MockAgentSessionRepo,facts: impl Into<FactMocks>,- replies: MockExplicitReplyDetector,+ replies: MockExplicitReplyExtractor,judge: MockImplicitTriggerJudge,history: MockThreadHistory,) -> TestService {@@ -202,9 +202,9 @@ fn thread_of(messages: Vec<ThreadMessage>) -> MockThreadHistory {/// Mocks for tests whose message never reaches the implicit path; any call is/// a test failure.-fn no_implicit() -> (MockExplicitReplyDetector, MockImplicitTriggerJudge) {+fn no_implicit() -> (MockExplicitReplyExtractor, MockImplicitTriggerJudge) {(- MockExplicitReplyDetector::new(),+ MockExplicitReplyExtractor::new(),MockImplicitTriggerJudge::new(),)}@@ -582,15 +582,39 @@ fn agent_bots() -> MockAgentBotLookup {bots}-fn detector(result: Result<bool>) -> MockExplicitReplyDetector {- let mut replies = MockExplicitReplyDetector::new();+fn extractor(result: Result<Option<ExtractedExplicitReply>>) -> MockExplicitReplyExtractor {+ let mut replies = MockExplicitReplyExtractor::new();replies- .expect_is_explicit_reply()+ .expect_extract_explicit_reply().once().return_once(move |_| Box::pin(async move { result }));replies}+fn reply_to_bot(bot_id: BotId) -> ExtractedExplicitReply {+ ExtractedExplicitReply {+ channel_id: Uuid::from_u128(1).to_string(),+ target_message_id: Uuid::from_u128(10).to_string(),+ target_thread_id: Uuid::from_u128(3).to_string(),+ display_text: "please fix this".to_owned(),+ sender_id: bot_id.into_storage_id().as_ref().to_owned(),+ }+}++fn reply_to_user() -> ExtractedExplicitReply {+ reply_to_user_message(Uuid::from_u128(10))+}++fn reply_to_user_message(target_message_id: Uuid) -> ExtractedExplicitReply {+ ExtractedExplicitReply {+ channel_id: Uuid::from_u128(1).to_string(),+ target_message_id: target_message_id.to_string(),+ target_thread_id: Uuid::from_u128(3).to_string(),+ display_text: "please fix this".to_owned(),+ sender_id: user().as_ref().to_owned(),+ }+}+fn judge_saying(result: Result<bool>) -> MockImplicitTriggerJudge {let mut judge = MockImplicitTriggerJudge::new();judge@@ -629,7 +653,7 @@ async fn an_explicit_reply_in_a_session_thread_triggers_without_a_mention() {let service = service(sessions,agent_bots(),- detector(Ok(true)),+ extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),MockImplicitTriggerJudge::new(),);@@ -647,7 +671,7 @@ async fn a_message_the_judge_reads_as_addressed_triggers_as_inferred() {let service = service(sessions,agent_bots(),- detector(Ok(false)),+ extractor(Ok(None)),judge_saying(Ok(true)),);@@ -663,7 +687,7 @@ async fn a_message_addressed_to_nobody_yields_nothing() {let service = service(sessions,agent_bots(),- detector(Ok(false)),+ extractor(Ok(None)),judge_saying(Ok(false)),);@@ -736,7 +760,7 @@ async fn implicit_triggering_skips_sessions_of_agentless_bots() {let service = service(sessions,bots,- detector(Ok(true)),+ extractor(Ok(Some(reply_to_bot(BotId::TEST_B)))),MockImplicitTriggerJudge::new(),);@@ -753,8 +777,12 @@ async fn two_live_agents_in_a_thread_yield_nothing() {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);+ let service = service(+ sessions,+ agent_bots(),+ extractor(Ok(None)),+ MockImplicitTriggerJudge::new(),+ );assert!(service@@ -766,13 +794,13 @@ async fn two_live_agents_in_a_thread_yield_nothing() {}#[tokio::test]-async fn a_failing_detector_falls_through_to_the_judge() {+async fn a_failing_extractor_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!(+ extractor(Err(AgentSessionError::Unknown(anyhow::anyhow!("lexical service unavailable")))),judge_saying(Ok(true)),@@ -792,7 +820,7 @@ async fn a_failing_judge_yields_nothing_instead_of_an_error() {let service = service(sessions,agent_bots(),- detector(Ok(false)),+ extractor(Ok(None)),judge_saying(Err(AgentSessionError::Unknown(anyhow::anyhow!("model unavailable")))),@@ -821,7 +849,7 @@ async fn the_judge_reads_the_thread_around_the_agent() {let service = service_reading(sessions,agent_bots(),- detector(Ok(false)),+ extractor(Ok(None)),judge_expecting("[user macro|[email protected]] unrelated chatter\n\[agent] on it\n\@@ -846,7 +874,7 @@ async fn an_explicit_reply_never_reads_the_thread() {let service = service_reading(sessions,agent_bots(),- detector(Ok(true)),+ extractor(Ok(Some(reply_to_bot(BotId::TEST_A)))),MockImplicitTriggerJudge::new(),history,);@@ -873,7 +901,7 @@ async fn an_unreadable_thread_still_judges_the_message_alone() {let service = service_reading(sessions,agent_bots(),- detector(Ok(false)),+ extractor(Ok(None)),judge_expecting(""),history,);@@ -884,3 +912,106 @@ async fn an_unreadable_thread_still_judges_the_message_alone() {ChannelKind::Inferred);}++#[tokio::test]+async fn an_explicit_reply_to_the_originating_message_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(),+ extractor(Ok(Some(reply_to_user_message(Uuid::from_u128(3))))),+ 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::ExplicitReply);+}++#[tokio::test]+async fn an_explicit_reply_to_another_user_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(),+ extractor(Ok(Some(reply_to_user()))),+ 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 an_explicit_reply_to_one_of_two_live_agents_routes_to_that_agent() {+ 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 service = service(+ sessions,+ agent_bots(),+ extractor(Ok(Some(reply_to_bot(BotId::TEST_B)))),+ 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);+ assert_eq!(metadata.kind, ChannelKind::ExplicitReply);+}++#[tokio::test]+async fn an_explicit_reply_to_neither_of_two_live_agents_yields_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 service = service(+ sessions,+ agent_bots(),+ extractor(Ok(Some(reply_to_user()))),+ MockImplicitTriggerJudge::new(),+ );++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}++#[tokio::test]+async fn an_explicit_reply_to_a_shared_originating_message_yields_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 service = service(+ sessions,+ agent_bots(),+ extractor(Ok(Some(reply_to_user_message(Uuid::from_u128(3))))),+ MockImplicitTriggerJudge::new(),+ );++ assert!(+ service+ .evaluate(&posted)+ .await+ .expect("evaluate message")+ .is_empty()+ );+}diff --git a/crates/agent_trigger/src/domain/yield_event.rs b/crates/agent_trigger/src/domain/yield_event.rsindex d401e688cb..d3e2582004 100644--- a/crates/agent_trigger/src/domain/yield_event.rs+++ b/crates/agent_trigger/src/domain/yield_event.rs@@ -40,7 +40,7 @@ pub enum NoEventReason {session_id: AgentSessionId,},/// The message sat in a session's thread without a mention, and neither- /// explicit reply detection nor the model judged it addressed to the agent.+ /// an explicit reply to the agent nor the model judged it addressed.NotAddressedToAgent {/// Session whose thread carried the message.session_id: AgentSessionId,diff --git a/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rs b/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rsdeleted file mode 100644index ae4c81bf88..0000000000--- a/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rs+++ /dev/null@@ -1,25 +0,0 @@-//! Explicit-reply detection backed by the lexical service.--use agent_session::domain::error::Result;-use lexical_client::LexicalClient;--use crate::domain::service::ExplicitReplyDetector;--/// Detects explicit replies by parsing the markdown with the lexical service,-/// so detection matches the `ReplyTargetNode` the editor itself produces.-pub struct LexicalExplicitReplyDetector {- client: LexicalClient,-}--impl LexicalExplicitReplyDetector {- /// Creates a detector calling the given lexical service client.- pub const fn new(client: LexicalClient) -> Self {- Self { client }- }-}--impl ExplicitReplyDetector for LexicalExplicitReplyDetector {- async fn is_explicit_reply(&self, markdown: &str) -> Result<bool> {- Ok(self.client.is_explicit_reply(markdown).await?)- }-}diff --git a/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs b/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rsnew file mode 100644index 0000000000..88de7fed3c--- /dev/null+++ b/crates/agent_trigger/src/outbound/lexical_explicit_reply_extractor.rs@@ -0,0 +1,38 @@+//! Explicit-reply extraction backed by the lexical service.++use agent_session::domain::error::Result;+use lexical_client::LexicalClient;++use crate::domain::service::{ExplicitReplyExtractor, ExtractedExplicitReply};++/// Extracts explicit replies by parsing the markdown with the lexical service,+/// so the reply-target matches the `ReplyTargetNode` the editor itself produces.+pub struct LexicalExplicitReplyExtractor {+ client: LexicalClient,+}++impl LexicalExplicitReplyExtractor {+ /// Creates an extractor calling the given lexical service client.+ pub const fn new(client: LexicalClient) -> Self {+ Self { client }+ }+}++impl ExplicitReplyExtractor for LexicalExplicitReplyExtractor {+ async fn extract_explicit_reply(+ &self,+ markdown: &str,+ ) -> Result<Option<ExtractedExplicitReply>> {+ Ok(self+ .client+ .extract_explicit_reply(markdown)+ .await?+ .map(|reply| ExtractedExplicitReply {+ channel_id: reply.channel_id,+ target_message_id: reply.target_message_id,+ target_thread_id: reply.target_thread_id,+ display_text: reply.display_text,+ sender_id: reply.sender_id,+ }))+ }+}diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rsindex 05f05406d4..088ca9b3f4 100644--- a/crates/agent_trigger/src/outbound/mod.rs+++ b/crates/agent_trigger/src/outbound/mod.rs@@ -3,9 +3,9 @@mod bot_repo_agent_lookup;mod channel_thread_history;mod fast_model_judge;-mod lexical_explicit_reply_detector;+mod lexical_explicit_reply_extractor;pub use bot_repo_agent_lookup::BotRepoAgentLookup;pub use channel_thread_history::ChannelThreadHistory;pub use fast_model_judge::FastModelTriggerJudge;-pub use lexical_explicit_reply_detector::LexicalExplicitReplyDetector;+pub use lexical_explicit_reply_extractor::LexicalExplicitReplyExtractor;diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rsindex 26ba28ae1a..6402b97d68 100644--- a/crates/lexical_client/src/parse_markdown.rs+++ b/crates/lexical_client/src/parse_markdown.rs@@ -35,14 +35,31 @@ struct MentionsRequest<'a> {}#[derive(Debug, serde::Serialize)]-struct ExplicitReplyRequest<'a> {+struct ExtractReplyRequest<'a> {markdown: &'a str,}+/// The leading `ReplyTargetNode` extracted from markdown by the lexical+/// service `/extract-reply` endpoint, when the markdown is an explicit reply.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ExtractedExplicitReply {+ /// Channel containing the targeted message.+ pub channel_id: String,+ /// Targeted channel message.+ pub target_message_id: String,+ /// Thread containing the targeted message.+ pub target_thread_id: String,+ /// Static one-line preview rendered by the reply target.+ pub display_text: String,+ /// Sender of the targeted message — who the author replied to.+ pub sender_id: String,+}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "camelCase")]-struct ExplicitReplyResponse {- is_explicit_reply: bool,+struct ExtractReplyResponse {+ reply: Option<ExtractedExplicitReply>,}/// An entity mention extracted from markdown by the lexical service@@ -362,22 +379,25 @@ impl LexicalClient {Ok(data.markdown)}- /// Parses `markdown` via the lexical service and reports whether it starts- /// with a `ReplyTargetNode` followed by the author's non-empty reply.+ /// Parses `markdown` via the lexical service and returns the leading+ /// `ReplyTargetNode` when it is followed by the author's non-empty reply./// Standard Markdown blockquotes carry no reply semantics.#[tracing::instrument(skip(self, markdown), err)]- pub async fn is_explicit_reply(&self, markdown: &str) -> Result<bool> {- let url = format!("{}/explicit-reply", self.url);+ pub async fn extract_explicit_reply(+ &self,+ markdown: &str,+ ) -> Result<Option<ExtractedExplicitReply>> {+ let url = format!("{}/extract-reply", self.url);let response = check_response(self.client.post(&url)- .json(&ExplicitReplyRequest { markdown })+ .json(&ExtractReplyRequest { markdown }).send().await?,).await?;- let data: ExplicitReplyResponse = response.json().await.context("unexpected response")?;- Ok(data.is_explicit_reply)+ let data: ExtractReplyResponse = response.json().await.context("unexpected response")?;+ Ok(data.reply)}async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T> {@@ -484,4 +504,29 @@ mod tests {_ => panic!("expected dssImage node"),}}++ #[test]+ fn extract_reply_response_deserializes_a_target() {+ let json = r#"{+ "reply": {+ "channelId": "channel-1",+ "targetMessageId": "message-1",+ "targetThreadId": "thread-1",+ "displayText": "please fix this",+ "senderId": "bot|00000000-0000-0000-0000-00000000b07a"+ }+ }"#;++ let response: ExtractReplyResponse = serde_json::from_str(json).unwrap();+ let reply = response.reply.expect("reply");+ assert_eq!(reply.channel_id, "channel-1");+ assert_eq!(reply.target_message_id, "message-1");+ assert_eq!(reply.sender_id, "bot|00000000-0000-0000-0000-00000000b07a");+ }++ #[test]+ fn extract_reply_response_deserializes_null() {+ let response: ExtractReplyResponse = serde_json::from_str(r#"{ "reply": null }"#).unwrap();+ assert!(response.reply.is_none());+ }}diff --git a/packages/lexical-core/tests/explicit-reply.test.ts b/packages/lexical-core/tests/explicit-reply.test.tsindex caef1dd4d7..b9738744cd 100644--- a/packages/lexical-core/tests/explicit-reply.test.ts+++ b/packages/lexical-core/tests/explicit-reply.test.ts@@ -1,38 +1,47 @@import { describe, expect, it } from 'vitest';import { buildReplyTargetMarkdown } from '../nodes/ReplyTargetNode';-import { isExplicitReplyMarkdown } from '../utils/explicit-reply';--describe('isExplicitReplyMarkdown', () => {- it('detects a reply-target node followed by a response', () => {- const reply = buildReplyTargetMarkdown({- channelId: 'channel-1',- targetMessageId: 'reply-1',- targetThreadId: 'thread-1',- displayText: 'please fix this',- senderId: 'macro|[email protected]',+import { extractExplicitReply } from '../utils/explicit-reply';++const target = {+ channelId: 'channel-1',+ targetMessageId: 'reply-1',+ targetThreadId: 'thread-1',+ displayText: 'please fix this',+ senderId: 'macro|[email protected]',+};++describe('extractExplicitReply', () => {+ it('extracts the leading reply-target when followed by a response', () => {+ const reply = buildReplyTargetMarkdown(target);++ expect(extractExplicitReply(`${reply}\n\nyes, on it`)).toEqual(target);+ expect(extractExplicitReply(reply)).toBeNull();+ });++ it('rejects a second reply-target as authored content', () => {+ const first = buildReplyTargetMarkdown(target);+ const second = buildReplyTargetMarkdown({+ ...target,+ targetMessageId: 'reply-2',+ displayText: 'another preview',});- expect(isExplicitReplyMarkdown(`${reply}\n\nyes, on it`)).toBe(true);- expect(isExplicitReplyMarkdown(reply)).toBe(false);+ expect(extractExplicitReply(`${first}\n\n${second}`)).toBeNull();});it('rejects plain text', () => {- expect(isExplicitReplyMarkdown('just a normal message')).toBe(false);+ expect(extractExplicitReply('just a normal message')).toBeNull();});it('does not treat a blockquote followed by content as an explicit reply', () => {- expect(isExplicitReplyMarkdown('> quoted text\n\nordinary response')).toBe(- false- );+ expect(extractExplicitReply('> quoted text\n\nordinary response')).toBeNull();});it('rejects a quote appearing after the reply', () => {- expect(isExplicitReplyMarkdown('as I said\n\n> earlier message')).toBe(- false- );+ expect(extractExplicitReply('as I said\n\n> earlier message')).toBeNull();});it('rejects empty markdown', () => {- expect(isExplicitReplyMarkdown('')).toBe(false);+ expect(extractExplicitReply('')).toBeNull();});});diff --git a/packages/lexical-core/utils/explicit-reply.ts b/packages/lexical-core/utils/explicit-reply.tsindex 054ab4d6b2..2500492c40 100644--- a/packages/lexical-core/utils/explicit-reply.ts+++ b/packages/lexical-core/utils/explicit-reply.ts@@ -2,17 +2,23 @@ import { createHeadlessEditor } from '@lexical/headless';import { $convertFromMarkdownString } from '@lexical/markdown';import { $getRoot } from 'lexical';import { NodeReplacements, SupportedNodeTypes } from '../node-list';-import { $isReplyTargetNode } from '../nodes/ReplyTargetNode';+import {+ $isReplyTargetNode,+ type ReplyTargetData,+} from '../nodes/ReplyTargetNode';import { ALL_TRANSFORMERS } from '../transformers';/**- * Whether a macro markdown string is composed as an explicit reply: a leading- * reply-target node followed by the author's response.+ * The leading reply-target of an explicit reply, when the markdown is composed+ * as a `ReplyTargetNode` followed by the author's own response.** A bare reference with nothing after it is not a reply; there is no message* of the author's own. Standard Markdown blockquotes carry no reply semantics.+ * Nested reply-target nodes do not count as authored content.*/-export function isExplicitReplyMarkdown(markdown: string): boolean {+export function extractExplicitReply(+ markdown: string+): ReplyTargetData | null {const editor = createHeadlessEditor({nodes: [...SupportedNodeTypes, ...NodeReplacements],});@@ -26,9 +32,11 @@ export function isExplicitReplyMarkdown(markdown: string): boolean {return editor.getEditorState().read(() => {const [first, ...rest] = $getRoot().getChildren();- return (- $isReplyTargetNode(first) &&- rest.some((node) => node.getTextContent().trim() !== '')+ if (!$isReplyTargetNode(first)) return null;+ const hasAuthoredContent = rest.some(+ (node) =>+ !$isReplyTargetNode(node) && node.getTextContent().trim() !== '');+ return hasAuthoredContent ? first.exportComponentProps() : null;});}diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rsindex bd42e17f2c..34402f7b06 100644--- a/services/agent_harness_service/src/trigger.rs+++ b/services/agent_harness_service/src/trigger.rs@@ -4,7 +4,7 @@ use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;use agent_trigger::domain::service::AgentTriggerService;use agent_trigger::outbound::{- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyDetector,+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyExtractor,};use bots::outbound::pg_bots_repo::PgBotsRepo;use channels::domain::broker_events::ChannelMacroEvent;@@ -63,7 +63,7 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> aBotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),- LexicalExplicitReplyDetector::new(lexical),+ LexicalExplicitReplyExtractor::new(lexical),FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),ChannelThreadHistory::new(PgChannelsRepo::new(pool)),);diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rsindex c5373514e6..eb04667516 100644--- a/services/agent_trigger_service/src/main.rs+++ b/services/agent_trigger_service/src/main.rs@@ -6,7 +6,7 @@ use agent_session::outbound::postgres::PgAgentSessionRepo;use agent_trigger::domain::processing::process_channel_event;use agent_trigger::domain::service::AgentTriggerService;use agent_trigger::outbound::{- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyDetector,+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyExtractor,};use anyhow::Context as _;use bots::outbound::pg_bots_repo::PgBotsRepo;@@ -70,7 +70,7 @@ async fn run() -> anyhow::Result<()> {BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),- LexicalExplicitReplyDetector::new(lexical),+ LexicalExplicitReplyExtractor::new(lexical),FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),ChannelThreadHistory::new(PgChannelsRepo::new(pool)),);diff --git a/services/lexical-service/src/endpoints/explicit-reply.ts b/services/lexical-service/src/endpoints/extract-reply.tssimilarity index 50%rename from services/lexical-service/src/endpoints/explicit-reply.tsrename to services/lexical-service/src/endpoints/extract-reply.tsindex 51830326a8..2b3c243783 100644--- a/services/lexical-service/src/endpoints/explicit-reply.ts+++ b/services/lexical-service/src/endpoints/extract-reply.ts@@ -1,28 +1,36 @@-import { isExplicitReplyMarkdown } from "@macro-inc/lexical-core/utils/explicit-reply";+import { extractExplicitReply } from "@macro-inc/lexical-core/utils/explicit-reply";import { OpenAPIRoute } from "chanfana";import type { Context } from "hono";import { z } from "zod";import { handleEndpointError } from "../lib/error-handler";import { standardErrorResponses } from "../lib/schemas";-const explicitReplyRequest = z.object({+const extractReplyRequest = z.object({markdown: z.string(),});-const explicitReplyResponse = z.object({- isExplicitReply: z.boolean(),+const replyTarget = z.object({+ channelId: z.string(),+ targetMessageId: z.string(),+ targetThreadId: z.string(),+ displayText: z.string(),+ senderId: z.string(),});-export class ExplicitReplyEndpoint extends OpenAPIRoute {+const extractReplyResponse = z.object({+ reply: replyTarget.nullable(),+});++export class ExtractReplyEndpoint extends OpenAPIRoute {schema = {- summary: "Detect whether Markdown is an explicit reply",+ summary: "Extract an explicit reply target from Markdown",description:- "Reports whether Macro Markdown begins with a ReplyTarget node followed by authored content. Standard blockquotes do not count as replies.",+ "Parses Macro Markdown and returns the leading ReplyTarget node when it is followed by authored content. Standard blockquotes do not count as replies.",request: {body: {content: {"application/json": {- schema: explicitReplyRequest,+ schema: extractReplyRequest,},},},@@ -32,7 +40,7 @@ export class ExplicitReplyEndpoint extends OpenAPIRoute {description: "Successfully evaluated the markdown",content: {"application/json": {- schema: explicitReplyResponse,+ schema: extractReplyResponse,},},},@@ -44,7 +52,7 @@ export class ExplicitReplyEndpoint extends OpenAPIRoute {try {const { body } = await this.getValidatedData<typeof this.schema>();return c.json({- isExplicitReply: isExplicitReplyMarkdown(body.markdown),+ reply: extractExplicitReply(body.markdown),});} catch (error) {return handleEndpointError(error, c);diff --git a/services/lexical-service/src/index.ts b/services/lexical-service/src/index.tsindex 98420a9be9..985d7ff1a5 100644--- a/services/lexical-service/src/index.ts+++ b/services/lexical-service/src/index.ts@@ -11,7 +11,7 @@ import { MarkdownEndpoint } from "./endpoints/markdown";import { MarkdownSnapshotEndpoint } from "./endpoints/markdown-snapshot";import { MentionsEndpoint } from "./endpoints/mentions";import { PlaintextEndpoint } from "./endpoints/plaintext";-import { ExplicitReplyEndpoint } from "./endpoints/explicit-reply";+import { ExtractReplyEndpoint } from "./endpoints/extract-reply";import { SearchTextEndpoint } from "./endpoints/search-text";import { XmlEndpoint } from "./endpoints/xml";@@ -44,7 +44,7 @@ app.use("/xml/*", internalAuth);app.use("/markdown/*", internalAuth);app.use("/snapshot/*", internalAuth);app.use("/mentions", internalAuth);-app.use("/explicit-reply", internalAuth);+app.use("/extract-reply", internalAuth);app.use("/agent-announcement", internalAuth);app.use("/agent-context", internalAuth);app.use("/internal/health", internalAuth);@@ -70,7 +70,7 @@ openapi.get("/markdown/:docId", MarkdownEndpoint);openapi.get("/xml/:docId", XmlEndpoint);openapi.post("/snapshot/markdown", MarkdownSnapshotEndpoint);openapi.post("/mentions", MentionsEndpoint);-openapi.post("/explicit-reply", ExplicitReplyEndpoint);+openapi.post("/extract-reply", ExtractReplyEndpoint);openapi.post("/agent-announcement", AgentAnnouncementEndpoint);openapi.post("/agent-context", AgentContextEndpoint);openapi.get("/internal/health", (c) => c.json({ status: "healthy" }));