"""@mention parser for Polyhedra v3.0. Detects ``@`` patterns in incoming messages and resolves them to known roles from the active session's RoleRegistry. Supports both plain-text (@scout) and Slack-style (<@USERID>) formats. The Slack-specific resolution layer maps user/bot IDs to role names and is injected by the messaging integration layer. """ from __future__ import annotations import re from dataclasses import dataclass from polyhedra.agents.base import Mention from polyhedra.core.role_registry import RoleRegistry # Matches @word or @word-word (hyphenated) _AT_MENTION_RE = re.compile(r"@([\w-]+)", re.IGNORECASE) @dataclass class ParsedMention: """The result of parsing a raw message for @mentions.""" mentioned_roles: list[str] # resolved role names (lowercase) human_addressed: bool # True if message is directed at the human (held role) raw_text: str class MentionParser: """ Extract @mention role references from raw message text. The parser is platform-agnostic: it just looks for ``@`` patterns. Platform adapters (Slack, Teams) must normalise their mention syntax (e.g. ``<@U12345>``) before passing to ``parse()``. """ def __init__(self, registry: RoleRegistry) -> None: self._registry = registry def parse(self, text: str, from_role: str = "human") -> list[Mention]: """ Parse all @mentions from ``text`` and return a list of Mention objects. Unrecognised role names are silently ignored. """ matches = _AT_MENTION_RE.findall(text) mentions: list[Mention] = [] seen: set[str] = set() for raw_role in matches: role = raw_role.lower() if role in seen: continue seen.add(role) if self._registry.get(role) is not None: mentions.append( Mention( mentioned_role=role, from_role=from_role, content=text, ) ) return mentions def extract_roles(self, text: str) -> list[str]: """Return just the list of recognised role names mentioned in text.""" return [m.mentioned_role for m in self.parse(text)] def strip_mentions(self, text: str) -> str: """Remove @mention tokens from text (useful before feeding to LLM).""" return _AT_MENTION_RE.sub("", text).strip()