Class: Events::Subscribers::SubagentMessageRouter
- Inherits:
-
Object
- Object
- Events::Subscribers::SubagentMessageRouter
- Includes:
- Events::Subscriber
- Defined in:
- lib/events/subscribers/subagent_message_router.rb
Overview
Routes text messages between parent and child sessions, enabling bidirectional @mention communication.
**Child → Parent:** When a sub-agent emits an AgentMessage, the router creates a UserMessage in the parent session with attribution prefix. If the parent is idle, persists directly and wakes it via AgentRequestJob. If the parent is mid-turn, emits a pending message that is promoted after the current loop completes — same mechanism as SessionChannel#speak.
**Parent → Child:** When a parent agent emits an AgentMessage containing ‘@name` mentions, the router persists the message in each matching child session with a [from parent]: origin label and wakes them via AgentRequestJob.
Both directions delegate to Session#enqueue_user_message, which respects the target session’s processing state — persisting directly when idle, deferring via pending queue when mid-turn.
This replaces the return_result tool — sub-agents communicate through natural text messages instead of structured tool calls.
Constant Summary collapse
- ATTRIBUTION_FORMAT =
Tools::ResponseTruncator::ATTRIBUTION_FORMAT
- PARENT_ATTRIBUTION_FORMAT =
Origin label for messages routed from parent agent to sub-agent. Lets the sub-agent distinguish delegated work from direct user input.
"[from parent]: %s"- MENTION_PATTERN =
Regex to extract @mention names from parent agent messages.
/@(\w[\w-]*)/
Instance Method Summary collapse
-
#emit(event) ⇒ void
Routes agent text messages between parent and child sessions.
Instance Method Details
#emit(event) ⇒ void
This method returns an undefined value.
Routes agent text messages between parent and child sessions.
For sub-agent sessions: forwards to parent with attribution prefix. For parent sessions: scans for @mentions and routes to matching children.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/events/subscribers/subagent_message_router.rb', line 47 def emit(event) payload = event[:payload] return unless payload.is_a?(Hash) return unless payload[:type] == "agent_message" session_id = payload[:session_id] return unless session_id content = payload[:content].to_s return if content.empty? session = Session.find_by(id: session_id) return unless session if session.sub_agent? route_to_parent(session, content) else route_mentions_to_children(session, content) end end |