Spaces:
Running

File size: 2,479 Bytes
891fe52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""@mention parser for Polyhedra v3.0.

Detects ``@<role>`` 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 ``@<word>`` 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()