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
Fix !command so @mentions resolve and code-wrapped commands run, like /command (CHOO-2342) (#313)
Abel Dantas5594010b7485
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 43863c178..27fe1bcd0 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -167,6 +167,12 @@ class BridgeCore:# (channel_id, agent_name) -> the last message the agent reported having# been handed. Cleared when its turn ends. See _follow_reported_anchor.self._reported_anchors: dict[tuple[str, str], str] = {}+ # Matrix-event -> external-post anchors written synchronously right after+ # room_send, before the durable _record_message_map commit, so a fast+ # command reply relayed during that DB await still resolves the command's+ # thread root instead of dropping to the channel root. Popped on commit.+ # Same race class as _provisioning_channels. See _prerecord_message_map.+ self._pending_message_maps: dict[str, str] = {}# Identity provisioning runs in the background — see _create_agent_identities.self._identity_task: asyncio.Task[None] | None = None@@ -628,7 +634,7 @@ class BridgeCore:content: dict[str, object] = {"command": cmd.command,- "args": cmd.args,+ "args": self._adapter.translate_inbound(cmd.args),"user_id": puppet.matrix_user_id,"user_name": cmd.sender_name,}@@ -660,11 +666,18 @@ class BridgeCore:# Mattermost root post (the command post for a top-level command, or the# thread root for an in-thread command whose root we hadn't recorded).if existing_matrix_root is None and thread_root_post is not None:- await self._record_message_map(- external_channel_id=cmd.channel_id,- matrix_event_id=resp.event_id,- external_post_id=thread_root_post,- )+ # Anchor in memory before the DB write: the write awaits a query that+ # yields the loop, and a fast reply (e.g. !help) relayed in that gap+ # would miss the row and land at the channel root. Popped on commit.+ self._prerecord_message_map(resp.event_id, thread_root_post)+ try:+ await self._record_message_map(+ external_channel_id=cmd.channel_id,+ matrix_event_id=resp.event_id,+ external_post_id=thread_root_post,+ )+ finally:+ self._pending_message_maps.pop(resp.event_id, None)async def _handle_agent_joined_channel(self, join: InboundAgentJoin) -> None:lock = self._channel_locks.setdefault(join.channel_id, asyncio.Lock())@@ -1769,6 +1782,21 @@ class BridgeCore:# ── Message-map helpers ───────────────────────────────────────────────────+ def _prerecord_message_map(+ self, matrix_event_id: str, external_post_id: str+ ) -> None:+ """Anchor a Matrix-event → external-post mapping in memory, synchronously,+ so it resolves before the durable _record_message_map write commits.++ _record_message_map awaits a DB round-trip that yields the event loop; a+ fast command reply (e.g. !help) can be relayed during that yield and miss+ the not-yet-committed row, dropping the result at the channel root rather+ than in the command's thread. Callers set this immediately after+ room_send returns, with NO await in between, and pop it once the row is+ committed. Same discipline as begin_provisioning for the room-mapping+ race."""+ self._pending_message_maps[matrix_event_id] = external_post_id+async def _record_message_map(self, *, external_channel_id: str, matrix_event_id: str, external_post_id: str) -> None:@@ -1800,6 +1828,9 @@ class BridgeCore:return mapping.matrix_event_id if mapping is not None else Noneasync def _external_post_for_matrix_event(self, matrix_event_id: str) -> str | None:+ pending = self._pending_message_maps.get(matrix_event_id)+ if pending is not None:+ return pendingasync with self._session_factory() as session:mapping = await self._bridge_message_map_store.get_by_matrix_event_id(session, self._bridge_id, matrix_event_iddiff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 3c3b7bde3..194bd9a2d 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -1833,6 +1833,28 @@ class SlackAdapter(CollaborationAdapter):message = re.sub(r"<(https?://[^|>]+)\|([^>]+)>", r"[\2](\1)", message)return re.sub(r"<(https?://[^>]+)>", r"\1", message)+ @staticmethod+ def _unwrap_code_span(text: str) -> str:+ """Return the inside of a message that is *entirely* one Slack code span+ (```x``` or `x`), else the stripped text unchanged.++ Slack keeps the backticks in the delivered text, so a `!cmd` in a code+ span no longer starts with "!" and gets treated as chatter instead of a+ command. This happens a lot when people copy-paste a command. Unwrapping+ a whole-message span lets it run, while a span sitting inside prose (e.g.+ "run `!remove-alias @bot` to undo") is left alone.+ """+ stripped = text.strip()+ for fence in ("```", "`"):+ if (+ len(stripped) > 2 * len(fence)+ and stripped.startswith(fence)+ and stripped.endswith(fence)+ and fence not in stripped[len(fence) : -len(fence)]+ ):+ return stripped[len(fence) : -len(fence)].strip()+ return stripped+def prime_mention_targets(self, targets: dict[str, str]) -> None:for name, external_id in targets.items():self._remember_mention_target(name, external_id)@@ -2029,6 +2051,8 @@ class SlackAdapter(CollaborationAdapter):message_ref = f"{channel_id}:{message_ts}"stripped = text.strip()+ if user_id and not bot_id:+ stripped = self._unwrap_code_span(stripped)if stripped.startswith("!") and self._on_command:parts = stripped.split(None, 1)command = parts[0].lstrip("!")diff --git a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.pyindex 06b72c6ab..422fc4f8a 100644--- a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py+++ b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py@@ -1,6 +1,6 @@from __future__ import annotations-from types import SimpleNamespace+from types import MethodType, SimpleNamespacefrom nio import RoomSendError@@ -8,14 +8,20 @@ from switch_core.bridges.collaboration.bridge_core import BridgeCorefrom switch_core.bridges.collaboration.models import InboundCommand-def _cmd(*, message_ref: str | None, root_id: str | None = None) -> InboundCommand:+def _cmd(+ *,+ message_ref: str | None,+ root_id: str | None = None,+ command: str = "status",+ args: str = "",+) -> InboundCommand:return InboundCommand(channel_id="chan-1",channel_type="channel_private",sender_id="ext-user",sender_name="louisa",- command="status",- args="",+ command=command,+ args=args,message_ref=message_ref,root_id=root_id,)@@ -25,6 +31,7 @@ def _fake_bridge(room_send_result: object,*,external_to_matrix: dict[str, str] | None = None,+ translate_inbound: object = None,) -> SimpleNamespace:"""A minimal BridgeCore stand-in for _handle_inbound_command.@@ -33,7 +40,12 @@ def _fake_bridge("""recorded: list[dict[str, str]] = []sent_content: list[dict] = []+ pending: dict[str, str] = {}lookup = external_to_matrix or {}+ translate = translate_inbound or (lambda raw: raw)++ def _prerecord_message_map(matrix_event_id: str, external_post_id: str) -> None:+ pending[matrix_event_id] = external_post_idasync def _ensure_user_in_matrix_room(**_kw: object) -> SimpleNamespace:async def _room_send(_room_id: str, _type: str, content: dict) -> object:@@ -53,11 +65,15 @@ def _fake_bridge(return SimpleNamespace(_channel_to_room={"chan-1": ("room-uuid", "!matrix:switch.local")},+ _adapter=SimpleNamespace(translate_inbound=translate),_ensure_user_in_matrix_room=_ensure_user_in_matrix_room,_matrix_event_for_external_post=_matrix_event_for_external_post,_record_message_map=_record_message_map,+ _prerecord_message_map=_prerecord_message_map,+ _pending_message_maps=pending,recorded=recorded,sent_content=sent_content,+ pending=pending,)@@ -125,3 +141,113 @@ class TestCommandThreadMapping:await BridgeCore._handle_inbound_command(bridge, _cmd(message_ref="mm-post-1"))assert bridge.recorded == []++ async def test_command_args_translated_via_adapter(self) -> None:+ # A `!command`'s args reach the funnel with the bridge's native mention+ # markup — an agent picked from Slack autocomplete arrives as its group+ # tag `<!subteam^S…>`, not `@name`. The funnel must run args through the+ # adapter's inbound translation (as slash commands already do) so the+ # dispatcher's first-@token targeting resolves the agent. Regression for+ # `!invite-agent @agent` failing while `/invite-agent` worked.+ bridge = _fake_bridge(+ SimpleNamespace(event_id="$cmd-event"),+ translate_inbound=lambda raw: raw.replace(+ "<!subteam^S123>", "@switch-onboarder"+ ),+ )+ await BridgeCore._handle_inbound_command(+ bridge,+ _cmd(+ message_ref="mm-post-1",+ command="invite-agent",+ args="<!subteam^S123>",+ ),+ )++ assert bridge.sent_content[0]["args"] == "@switch-onboarder"+++class TestCommandResultThreadingRace:+ async def test_external_post_prefers_pending_anchor_over_db(self) -> None:+ # While the durable row is still being written, the in-memory anchor must+ # resolve without touching the DB. The store raises to prove the DB is+ # not consulted on a pending hit.+ def _boom(*_a: object, **_k: object) -> object:+ raise AssertionError("DB consulted despite a pending anchor")++ bridge = SimpleNamespace(+ _pending_message_maps={"$cmd-event": "chan-1:100.1"},+ _bridge_id="b",+ _bridge_message_map_store=SimpleNamespace(get_by_matrix_event_id=_boom),+ _session_factory=_boom,+ )+ got = await BridgeCore._external_post_for_matrix_event(bridge, "$cmd-event")+ assert got == "chan-1:100.1"++ async def test_top_level_command_result_threads_during_db_write(self) -> None:+ # Regression for the intermittent root-posting of fast system commands+ # (the !help screenshot): the reply is relayed WHILE _record_message_map+ # is still awaiting its write. The anchor set before that await must+ # resolve the command's thread root, and is popped once the write returns.+ resolved: dict[str, str | None] = {}++ async def _ensure_user_in_matrix_room(**_kw: object) -> SimpleNamespace:+ async def _room_send(_room_id: str, _type: str, _content: dict) -> object:+ return SimpleNamespace(event_id="$cmd-event")++ return SimpleNamespace(+ matrix_user_id="@puppet:switch.local",+ client=SimpleNamespace(room_send=_room_send),+ )++ async def _matrix_event_for_external_post(_post: str) -> str | None:+ return None # top-level command: its own post is not yet bridged++ async def _get_none(*_a: object, **_k: object) -> None:+ return None++ class _NullSession:+ async def __aenter__(self) -> object:+ return object()++ async def __aexit__(self, *_a: object) -> bool:+ return False++ bridge = SimpleNamespace(+ _channel_to_room={"chan-1": ("room-uuid", "!matrix:switch.local")},+ _adapter=SimpleNamespace(translate_inbound=lambda s: s),+ _pending_message_maps={},+ _bridge_id="b",+ _bridge_message_map_store=SimpleNamespace(get_by_matrix_event_id=_get_none),+ _session_factory=lambda: _NullSession(),+ _ensure_user_in_matrix_room=_ensure_user_in_matrix_room,+ _matrix_event_for_external_post=_matrix_event_for_external_post,+ )+ bridge._prerecord_message_map = MethodType(+ BridgeCore._prerecord_message_map, bridge+ )+ bridge._external_post_for_matrix_event = MethodType(+ BridgeCore._external_post_for_matrix_event, bridge+ )++ async def _record_message_map(+ *, external_channel_id: str, matrix_event_id: str, external_post_id: str+ ) -> None:+ # Simulate the reply's outbound relay resolving the thread root while+ # this write is still in flight.+ resolved["mid"] = await bridge._external_post_for_matrix_event(+ matrix_event_id+ )++ bridge._record_message_map = _record_message_map++ await BridgeCore._handle_inbound_command(+ bridge, _cmd(message_ref="chan-1:100.1", command="help")+ )++ # Mid-write the anchor resolved to the command post (threads under it)...+ assert resolved["mid"] == "chan-1:100.1"+ # ...and it is cleared once the write returns...+ assert bridge._pending_message_maps == {}+ # ...after which resolution falls through to the DB (empty here).+ assert await bridge._external_post_for_matrix_event("$cmd-event") is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 9c1503941..25e0bd7ae 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -43,6 +43,17 @@ def _capture_messages(adapter: SlackAdapter) -> list[InboundMessage]:return captured+def _capture_commands(adapter: SlackAdapter) -> list[InboundCommand]:+ captured: list[InboundCommand] = []++ async def on_command(cmd: InboundCommand) -> None:+ captured.append(cmd)++ adapter._on_command = on_command+ adapter._channel_name_cache["C123"] = "general"+ return captured++class _FakeWebClient:"""Captures chat_postMessage / chat_delete kwargs and returns canned ts."""@@ -1362,3 +1373,88 @@ def test_send_attachment_upload_failure_falls_back_to_disclosed_text() -> None:assert "cat.png" in fake.calls[0]["text"]assert fake.calls[0]["username"] == "agent-a"assert ref == "C123:999.9"+++# ── Code-formatted commands (near-miss intake) ───────────────────────────────+++def test_unwrap_code_span() -> None:+ unwrap = SlackAdapter._unwrap_code_span+ assert unwrap("`!cmd`") == "!cmd"+ assert unwrap("```!cmd```") == "!cmd"+ assert unwrap(" `!invite-agent @x` ") == "!invite-agent @x"+ # Not a whole-message span: prose around it, or two spans — left untouched.+ assert unwrap("run `!cmd` now") == "run `!cmd` now"+ assert unwrap("`!a` `!b`") == "`!a` `!b`"+ # Plain text and degenerate fences are returned as-is.+ assert unwrap("plain text") == "plain text"+ assert unwrap("`") == "`"+++def test_backtick_wrapped_command_from_human_is_run() -> None:+ adapter = _adapter()+ commands = _capture_commands(adapter)+ messages = _capture_messages(adapter)++ _run(+ adapter._handle_message_event(+ {+ "channel": "C123",+ "ts": "100.1",+ "user": "U1",+ "text": "`!invite-agent @switch-onboarder`",+ "channel_type": "channel",+ }+ )+ )++ # The command runs despite the code formatting, and is not also bridged as+ # an ordinary message.+ assert len(commands) == 1+ assert commands[0].command == "invite-agent"+ assert commands[0].args == "@switch-onboarder"+ assert messages == []+++def test_code_span_command_inside_prose_is_not_run() -> None:+ adapter = _adapter()+ commands = _capture_commands(adapter)+ messages = _capture_messages(adapter)++ _run(+ adapter._handle_message_event(+ {+ "channel": "C123",+ "ts": "100.1",+ "user": "U1",+ "text": "run `!invite-agent @x` to add it",+ "channel_type": "channel",+ }+ )+ )++ # A reference embedded in prose stays an ordinary message, never a command.+ assert commands == []+ assert len(messages) == 1+++def test_backtick_wrapped_command_from_bot_is_not_run() -> None:+ adapter = _adapter()+ adapter._bot_id = "BSELF"+ commands = _capture_commands(adapter)+ _capture_messages(adapter)++ _run(+ adapter._handle_message_event(+ {+ "channel": "C123",+ "ts": "100.1",+ "text": "`!invite-agent @x`",+ "channel_type": "channel",+ "bot_id": "BDATADOG",+ }+ )+ )++ # An agent posting a `!command` reference must never trigger it.+ assert commands == []