Class: Events::Subscribers::SubagentMessageRouter

Inherits:
Object
  • Object
show all
Includes:
Events::Subscriber
Defined in:
lib/events/subscribers/subagent_message_router.rb

Overview

Routes agent text messages between parent and child sessions, enabling bidirectional @mention communication.

Subscribes to MessageCreated and filters on message_type == “agent_message” — the Message record is the single source of truth for LLM-produced text, so routing hangs off the persistence lifecycle rather than a parallel domain-event emission.

**Child → Parent:** When a sub-agent persists an agent_message, the router enqueues a PendingMessage on the parent with sub-agent attribution. The PM’s after_create_commit kicks off the drain pipeline when the parent is idle; otherwise the message queues silently and the idle-wake rule picks it up.

**Parent → Child:** When a parent agent persists an agent_message containing @name mentions, the router enqueues a PendingMessage in each matching child session with a [from parent]: origin label.

Both directions delegate to Session#enqueue_user_message.

This replaces the return_result tool — sub-agents communicate through natural text messages instead of structured tool calls.

Constant Summary collapse

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

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. For parent sessions: scans for @mentions and routes to matching children.

Parameters:

  • event (Hash)

    Rails.event notification hash with :payload carrying the persisted Message record under :message



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/events/subscribers/subagent_message_router.rb', line 45

def emit(event)
  message = event.dig(:payload, :message)
  return unless message.is_a?(Message)
  return unless message.message_type == "agent_message"

  content = message.payload["content"].to_s
  return if content.empty?

  session = message.session

  if session.sub_agent?
    route_to_parent(session, content)
  else
    route_mentions_to_children(session, content)
  end
end