Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Address an agent mentioned before punctuation, and not inside an address
Himanshu Deshhratar9ad0d8e8bcfa
diff --git a/core/switch_core/clients/mentions.py b/core/switch_core/clients/mentions.pyindex 6eb64ee79..cc0ccf614 100644--- a/core/switch_core/clients/mentions.py+++ b/core/switch_core/clients/mentions.py@@ -4,12 +4,21 @@ import functoolsimport re# Characters that may appear inside an agent / role / alias name (e.g.-# "cc-bug-fixing-2", "claude-code.my-project.alice"). An `@name` is-# only a real mention when the character right after the name is NOT one of-# these (or the string ends) — otherwise a name that is a prefix of a longer one-# (`@cc-bug-fixing` inside `@cc-bug-fixing-2`) would be falsely matched.+# "cc-bug-fixing-2", "claude-code.my-project.alice").NAME_CHAR = r"[A-Za-z0-9._-]"+# Where a mention may start: an `@` that does not continue a word, so an+# address such as `root@staging` or `[email protected]` names nobody.+_MENTION_START = r"(?<![A-Za-z0-9])"++# Where a mention ends: no more name characters that reach a letter or digit.+# A name that is a prefix of a longer one (`@cc-bug-fixing` inside+# `@cc-bug-fixing-2`) is therefore not matched, while the `.`, `-` or `_` that+# closes a sentence or an emphasis (`@reviewer.`, `@reviewer...`, `_@reviewer_`)+# is punctuation rather than part of the name — the same rule+# `room_wide_mention.py` applies to `@channel.`.+_MENTION_END = rf"(?!{NAME_CHAR}*[A-Za-z0-9])"+# Markdown / Slack-mrkdwn emphasis markers that can wrap or abut an @mention —# a bolded mention arrives as "@*name*", which would otherwise hide the name# from the token regex (the `*` is not a name char) and break matching. We@@ -17,7 +26,9 @@ NAME_CHAR = r"[A-Za-z0-9._-]"# a valid character in agent and role names._EMPHASIS = re.compile(r"[*~]")-_MENTION_TOKEN = re.compile(rf"@({NAME_CHAR}+)")+# A token ends on a letter or digit, so trailing punctuation is left out of it+# by the same rule `_MENTION_END` uses.+_MENTION_TOKEN = re.compile(rf"{_MENTION_START}@({NAME_CHAR}*[A-Za-z0-9])")def strip_emphasis(text: str) -> str:@@ -25,20 +36,26 @@ def strip_emphasis(text: str) -> str:return _EMPHASIS.sub("", text)+def mention_pattern(name: str) -> str:+ """The regex source matching `@name` as a whole mention (see+ `mention_regex`), for a caller that extends it."""+ return _MENTION_START + re.escape(f"@{name}") + _MENTION_END++@functools.lru_cache(maxsize=16384)def mention_regex(name: str) -> re.Pattern[str]:- """Compile a case-insensitive regex matching `@name` only at a full-token- boundary, so a prefix name is never matched inside a longer name. Kept- per name: `re`'s own cache holds 512 patterns, fewer than the names a- large deployment tags."""- return re.compile(re.escape(f"@{name}") + rf"(?!{NAME_CHAR})", re.IGNORECASE)+ """Compile a case-insensitive regex matching `@name` as a whole mention:+ not inside a word before it, and not as the prefix of a longer name after+ it. Kept per name: `re`'s own cache holds 512 patterns, fewer than the+ names a large deployment tags."""+ return re.compile(mention_pattern(name), re.IGNORECASE)def mention_tokens(text: str) -> list[str]:"""Every `@token` name in `text`, in order of appearance (with duplicates).- Tokens span the same characters a name may contain, so each token matches- what `mention_regex` would treat as one whole mention.+ Each token is what `mention_regex` treats as one whole mention, without the+ punctuation that may follow it."""return _MENTION_TOKEN.findall(strip_emphasis(text))diff --git a/core/switch_core/delivery/conversation.py b/core/switch_core/delivery/conversation.pyindex ec456ca77..e1d7680ea 100644--- a/core/switch_core/delivery/conversation.py+++ b/core/switch_core/delivery/conversation.py@@ -52,7 +52,7 @@ from switch_core.clients.admin_messages import (PLATFORM_MARKER,SENDER_IS_APP_MARKER,)-from switch_core.clients.mentions import NAME_CHAR+from switch_core.clients.mentions import mention_tokensfrom switch_core.delivery.addressing import IncomingMessageif TYPE_CHECKING:@@ -99,10 +99,6 @@ _SMALL_TALK = frozenset(_TRAILING_PUNCTUATION = re.compile(r"[\s.!?,;:]+$")-# A mention-shaped token: an `@` that starts a word, followed by name-# characters. An email address (`[email protected]`) is not one.-_MENTION = re.compile(rf"(?<!{NAME_CHAR})@({NAME_CHAR}+)")-def is_small_talk(body: str) -> bool:"""True for thanks or praise ("thanks!", "great"), which ends an exchange@@ -112,13 +108,13 @@ def is_small_talk(body: str) -> bool:def mentioned_names(body: str) -> set[str]:"""The names @-mentioned in the text, lowercased."""- return {name.lower() for name in _MENTION.findall(body)}+ return {name.lower() for name in mention_tokens(body)}def mentions_anyone(body: str) -> bool:"""Whether the text @-mentions anyone, by the same token rule mentions use.A mention always wins, so the rules stand aside."""- return _MENTION.search(body) is not None+ return bool(mention_tokens(body))NOT_TAKING_PART = "the agent is not taking part in this thread"diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.pyindex fb3d271e9..88be776fc 100644--- a/core/switch_core/delivery/recipient.py+++ b/core/switch_core/delivery/recipient.py@@ -59,7 +59,7 @@ from switch_core.clients.admin_messages import (platform_replies_in_channel,)from switch_core.clients.mentions import (- NAME_CHAR as _NAME_CHAR,+ mention_pattern as _mention_pattern,)from switch_core.clients.mentions import (mention_regex as _mention_regex,@@ -1871,7 +1871,7 @@ class AgentRecipient:def _strip_mention(self, text: str) -> str:pattern = re.compile(- re.escape(f"@{self.agent.name}") + rf"(?!{_NAME_CHAR}):?",+ _mention_pattern(self.agent.name) + ":?",re.IGNORECASE,)return pattern.sub("", text).strip()diff --git a/core/tests/switch_core/clients/test_mentions.py b/core/tests/switch_core/clients/test_mentions.pynew file mode 100644index 000000000..5d501a2fd--- /dev/null+++ b/core/tests/switch_core/clients/test_mentions.py@@ -0,0 +1,122 @@+"""Where an `@name` mention starts and ends."""++from __future__ import annotations++import pytest++from switch_core.clients.mention_warnings import unmatched_mentions+from switch_core.clients.mentions import (+ mention_regex,+ mention_tokens,+ unique_mention_tokens,+)+from switch_core.delivery.conversation import mentioned_names, mentions_anyone+++def _mentions(name: str, text: str) -> bool:+ return mention_regex(name).search(text) is not None+++class TestMentionEnd:+ @pytest.mark.parametrize(+ "text",+ [+ "Can you review this, @reviewer.",+ "Can you review this @reviewer...",+ "@reviewer, can you look?",+ "thanks @reviewer!",+ "is that right @reviewer?",+ "(@reviewer)",+ "_@reviewer_ please",+ "@reviewer- and the rest",+ "@reviewer.\nNext line",+ "@reviewer",+ ],+ )+ def test_trailing_punctuation_is_not_part_of_the_name(self, text: str) -> None:+ assert _mentions("reviewer", text)++ @pytest.mark.parametrize(+ "text",+ [+ "@reviewer.bot please",+ "@reviewer-2 please",+ "@reviewer_two please",+ "@reviewers please",+ ],+ )+ def test_a_longer_name_is_not_a_mention_of_its_prefix(self, text: str) -> None:+ assert not _mentions("reviewer", text)++ def test_prefix_name_inside_a_longer_name(self) -> None:+ assert not _mentions("cc-bug-fixing", "@cc-bug-fixing-2 take this")+ assert _mentions("cc-bug-fixing-2", "@cc-bug-fixing-2 take this")++ def test_a_dotted_name_matches_whole(self) -> None:+ assert _mentions(+ "claude-code.my-project.alice", "@claude-code.my-project.alice."+ )++ def test_case_insensitive(self) -> None:+ assert _mentions("reviewer", "@Reviewer.")+++class TestMentionStart:+ @pytest.mark.parametrize(+ "text",+ [+ "ssh root@staging is failing",+ "mail ops@staging.",+ "ops@staging",+ ],+ )+ def test_an_at_inside_a_word_is_not_a_mention(self, text: str) -> None:+ assert not _mentions("staging", text)++ def test_an_email_address_names_nobody(self) -> None:+ assert not _mentions("example", "write to [email protected]")+ assert mention_tokens("write to [email protected]") == []++ @pytest.mark.parametrize(+ "text", ["@staging", " @staging", "(@staging)", ".@staging"]+ )+ def test_an_at_that_starts_a_word_is_a_mention(self, text: str) -> None:+ assert _mentions("staging", text)+++class TestMentionTokens:+ def test_tokens_leave_trailing_punctuation_out(self) -> None:+ assert mention_tokens("ping @reviewer. and @helper... and @ops-") == [+ "reviewer",+ "helper",+ "ops",+ ]++ def test_tokens_keep_inner_punctuation(self) -> None:+ assert mention_tokens("@claude-code.my-project.alice.") == [+ "claude-code.my-project.alice"+ ]++ def test_tokens_skip_addresses(self) -> None:+ assert mention_tokens("ssh root@staging, then @deployer") == ["deployer"]++ def test_unique_tokens(self) -> None:+ assert unique_mention_tokens("@Reviewer. @reviewer, @helper") == [+ "Reviewer",+ "helper",+ ]++ def test_a_sentence_end_mention_is_not_unmatched(self) -> None:+ assert unmatched_mentions("Look at this, @reviewer.", ["reviewer"]) == []++ def test_an_address_is_not_unmatched(self) -> None:+ assert unmatched_mentions("ssh root@staging", []) == []+++class TestConversationMentions:+ def test_mentioned_names_without_punctuation(self) -> None:+ assert mentioned_names("thanks @Reviewer.") == {"reviewer"}++ def test_mentions_anyone(self) -> None:+ assert mentions_anyone("over to you, @reviewer.")+ assert not mentions_anyone("write to [email protected]")