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
Decode Slack's &, < and > in what people send to agents
Himanshu Deshhrataraa6c8e29e68e
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 7fc49eb6d..abd3c2f6c 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -97,6 +97,13 @@ _SLACK_MASS_MENTION_WORD = re.compile(r"<!(channel|here|everyone|group)(?:\|[^>]*)?>", re.IGNORECASE)+# A channel link, `<#C123|general>`. The label may be empty (`<#C123|>`).+_SLACK_CHANNEL_LINK = re.compile(r"<#([A-Z0-9]+)(?:\|([^>]*))?>")++# The only three characters Slack escapes in the text it delivers.+_SLACK_ENTITY = re.compile(r"&(amp|lt|gt);")+_SLACK_ENTITY_CHARS = {"amp": "&", "lt": "<", "gt": ">"}+# Stamped on the description of every user group we mint for an agent, so a# reload can tell ours apart from the workspace's own groups._AGENT_GROUP_MARKER = "Switch agent — "@@ -3221,12 +3228,52 @@ class SlackAdapter(PlatformAdapter):return escape_mrkdwn(super().escape_label_for_body(label))def translate_inbound(self, raw_message: str) -> str:+ return self._unescape_entities(self._translate_markup(raw_message))++ def _translate_markup(self, raw_message: str) -> str:+ """Rewrite Slack's `<…>` sequences, leaving its entity escaping alone.++ Running this twice changes nothing, which is why a command's arguments+ get only this from the adapter: `CollaborationCore` runs every+ command's arguments through `translate_inbound` again, and the entities+ must be decoded exactly once, or a person's literal `&lt;` would+ reach the agent as `<`.+ """return self._translate_links_to_markdown(- self._translate_mass_mentions_to_markdown(- self._translate_mentions_to_markdown(raw_message)+ self._translate_channel_links(+ self._translate_mass_mentions_to_markdown(+ self._translate_mentions_to_markdown(raw_message)+ )))+ @staticmethod+ def _unescape_entities(message: str) -> str:+ """Decode `&`, `<` and `>` back to what the person typed.++ Must run after every `<…>` sequence is translated: until then a `<`+ can only be Slack's own markup, because Slack escapes the ones people+ type. Decoding is one pass, so `&lt;` becomes the `<` that was+ typed rather than `<`.+ """+ return _SLACK_ENTITY.sub(+ lambda match: _SLACK_ENTITY_CHARS[match.group(1)], message+ )++ def _translate_channel_links(self, message: str) -> str:+ """Show a channel link `<#C123|general>` as `#general`.++ A link without a label falls back to the channel's cached name, and to+ its id when the name is not known yet.+ """++ def _replace(match: re.Match[str]) -> str:+ channel_id = match.group(1)+ name = match.group(2) or self._channel_name_cache.get(channel_id)+ return f"#{name or channel_id}"++ return _SLACK_CHANNEL_LINK.sub(_replace, message)+@staticmethoddef _translate_mass_mentions_to_markdown(message: str) -> str:"""Show a person's `<!channel>`, `<!here>` or `<!everyone>` as the word.@@ -3590,7 +3637,7 @@ class SlackAdapter(PlatformAdapter):if stripped.startswith("!") and self._on_command:parts = stripped.split(None, 1)command = parts[0].lstrip("!")- args = self.translate_inbound(parts[1].strip()) if len(parts) > 1 else ""+ args = self._translate_markup(parts[1].strip()) if len(parts) > 1 else ""await self._on_command(InboundCommand(channel_id=channel_id,@@ -3657,7 +3704,7 @@ class SlackAdapter(PlatformAdapter):# Slack encodes @mentions in command arguments as `<@U…>`; normalise# them to `@name` so the command dispatcher's first `@` token resolves# to the target agent or role.- args = self.translate_inbound(text)+ args = self._translate_markup(text)try:channel_type = await self.get_channel_type(channel_id)diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex b466296fa..dc196ca25 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -1012,6 +1012,111 @@ def test_translate_inbound_leaves_a_user_group_to_its_own_rule() -> None:assert _adapter().translate_inbound("<!subteam^S123|@ops> hi") == "@ops hi"+ ("raw", "expected"),+ [+ (+ "is `if a < b && b > c` right?",+ "is `if a < b && b > c` right?",+ ),+ ("cat log.txt > out.txt", "cat log.txt > out.txt"),+ ("List<String> and x -> y", "List<String> and x -> y"),+ ("R&D and Q&A", "R&D and Q&A"),+ ("```\nfoo && bar\n```", "```\nfoo && bar\n```"),+ ],+)+def test_translate_inbound_decodes_slack_entities(raw: str, expected: str) -> None:+ assert _adapter().translate_inbound(raw) == expected+++def test_translate_inbound_decodes_once() -> None:+ # A person who types `<` literally is sent `&lt;`.+ assert _adapter().translate_inbound("write &lt; for <") == "write < for <"+++def test_translate_inbound_leaves_other_entities_alone() -> None:+ # Slack escapes only `&`, `<` and `>`, so anything else is what was typed.+ assert (+ _adapter().translate_inbound(""hi" '") == ""hi" '"+ )+++def test_translate_inbound_a_typed_angle_bracket_is_not_markup() -> None:+ adapter = _adapter()+ adapter._user_cache["U999"] = SlackUser(name="worker", display_name="Worker")+ assert (+ adapter.translate_inbound("<@U999> and <https://example.com>")+ == "<@U999> and <https://example.com>"+ )+++def test_translate_inbound_decodes_a_link_url() -> None:+ assert (+ _adapter().translate_inbound("<https://example.com/?a=1&b=2|search>")+ == "[search](https://example.com/?a=1&b=2)"+ )+++ ("raw", "expected"),+ [+ ("see <#C0123ABCD|general>", "see #general"),+ ("see <#C0123ABCD|>", "see #ops-room"),+ ("see <#C0123ABCD>", "see #ops-room"),+ ("see <#C9999>", "see #C9999"),+ ],+)+def test_translate_inbound_shows_a_channel_link_as_its_name(+ raw: str, expected: str+) -> None:+ adapter = _adapter()+ adapter._channel_name_cache["C0123ABCD"] = "ops-room"+ assert adapter.translate_inbound(raw) == expected+++def test_typed_command_args_are_decoded_once_end_to_end() -> None:+ # The adapter hands the core arguments it has not decoded; the core's own+ # `translate_inbound` then decodes them once.+ adapter = _adapter()+ adapter._user_cache["U1"] = SlackUser(name="jane", display_name="Jane")+ adapter._user_cache["U999"] = SlackUser(name="worker", display_name="Worker")+ adapter._channel_name_cache["C123"] = "general"+ commands = _capture_commands(adapter)++ _run(+ adapter._handle_message_event(+ {+ "channel": "C123",+ "ts": "100.1",+ "user": "U1",+ "text": "!assign <@U999> a < b &lt;",+ "channel_type": "channel",+ }+ )+ )++ assert adapter.translate_inbound(commands[0].args) == "@worker a < b <"+++def test_slash_command_args_are_decoded_once_end_to_end() -> None:+ adapter = _adapter()+ adapter._web_client = _FakeSlashWebClient() # type: ignore[assignment]+ commands = _capture_commands(adapter)++ _run(+ adapter._handle_slash_command(+ {+ "command": "/assign",+ "text": "@worker a < b &lt;",+ "channel_id": "C123",+ "user_id": "U123",+ }+ )+ )++ assert adapter.translate_inbound(commands[0].args) == "@worker a < b <"++def test_slash_command_without_channel_is_ignored() -> None:adapter = _adapter()commands = _capture_commands(adapter)