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
feat(rooms): room-wide mention that pages a room's people and wakes no agent (CHOO-1420) (#542)
Christian McDermott4e82a7f10465
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex a4d583f8f..ac255bf33 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -209,6 +209,22 @@ attending without giving up the one you are.**Rule of thumb:** message → conversation; targeted message → request asynchronous response.+**Paging everyone in the room.** `target_names=["everyone"]` is a room-wide+mention: it notifies every *person* in the room on its chat platform —+`@channel` on Slack and Mattermost, `@everyone` on Discord — and wakes **no+agent**. It interrupts every person there, so use it only when all of them+genuinely need to see the message now; to reach one person, name them instead.+Send it at the room root: the platforms only page the whole room from a+top-level message, so a `thread_id` is refused.+`target_statuses` reports what happened under `everyone`: `sent`,+`unsupported` (Teams has no channel-wide mention a bot can send, so the message+posts but pages nobody), `no_bridge` (the room has no chat platform) or+`bridge_unavailable` (its bridge is down). That is what Switch sent, not what+the platform confirmed. Writing `@everyone`, `@channel`, `@here` or `@all` into+a body pages nobody — Switch defuses those words — so this target is the only+way to do it. It is refused in a room where an agent, alias or role is itself+named `everyone`.+**Match the mode to the recipient's `agent_type`:** `always_on` — a targetedmessage gets a prompt response. `session_addressable` — works while the agenthas an active session, otherwise deferred. `session_passive` — do **not**@@ -783,7 +799,7 @@ Every Switch tool you call in normal operation, one line each.- `list_participants` — the connected room's roster: `id`, `name`, `type`,`status`, `alias`.- `post_message` — broadcast to the room.-- `send_targeted_message` — broadcast addressed to names and/or roles.+- `send_targeted_message` — broadcast addressed to names, roles, or `everyone` (the room's people).- `send_attachment` — post one or more files to the room.- `download_attachment` — fetch a file seen in history, by `mxc`.- `list_roles` — the room's assumable roles and who holds them.diff --git a/core/switch_core/agent_display_name.py b/core/switch_core/agent_display_name.pyindex bffb4b13c..3eb5ac6af 100644--- a/core/switch_core/agent_display_name.py+++ b/core/switch_core/agent_display_name.py@@ -23,7 +23,7 @@ from typing import NoReturn# that a display name stays a label rather than a sentence.MAX_DISPLAY_NAME_LENGTH = 64-_ZERO_WIDTH_SPACE = "\u200b"+ZERO_WIDTH_SPACE = "\u200b"class InvalidDisplayName(ValueError):@@ -109,8 +109,8 @@ def defuse_label_markup(label: str) -> str:the far end, while a zero-width space is inert in every escaping pipelineit may pass through afterwards, so it cannot compound with one."""- return label.replace("@", "@" + _ZERO_WIDTH_SPACE).replace(- "]", "]" + _ZERO_WIDTH_SPACE+ return label.replace("@", "@" + ZERO_WIDTH_SPACE).replace(+ "]", "]" + ZERO_WIDTH_SPACE)diff --git a/core/switch_core/aliases.py b/core/switch_core/aliases.pyindex 708b2d9d5..b1c8a70c0 100644--- a/core/switch_core/aliases.py+++ b/core/switch_core/aliases.py@@ -10,6 +10,8 @@ case-insensitive, mirroring the mention regex.import re+from switch_core.room_wide_mention import is_reserved_mention_name+_ALIAS_RE = re.compile(r"^[A-Za-z0-9._-]+$")@@ -18,12 +20,18 @@ class AliasError(ValueError):def validate_alias_format(alias: str) -> None:- """Raise AliasError unless `alias` is a single `@`-token-safe handle."""+ """Raise AliasError unless `alias` is a single `@`-token-safe handle that+ is not one of the room-wide mention words."""if not _ALIAS_RE.match(alias or ""):raise AliasError(f"Invalid alias '{alias}': aliases may contain only letters, digits, ""'.', '-' and '_' (no spaces or '@').")+ if is_reserved_mention_name(alias):+ raise AliasError(+ f"Alias '{alias}' is reserved for room-wide mentions, so it cannot "+ "name an agent."+ )def check_alias_collisions(diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 10c3274c6..1cfd9af0f 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -770,6 +770,12 @@ async def send_targeted_message(this tool adds them for each target.target_names: Agent or user names (the `name` field fromlist_participants, not ids) to address. Prepended as `@name`.+ The reserved name `everyone` is a room-wide mention: it notifies+ every person in the room on its chat platform (`@channel` on Slack+ and Mattermost, `@everyone` on Discord) and wakes no agent. Use it+ only when every person there genuinely needs to see the message.+ It cannot go in a thread: the platforms only page the whole room+ from a top-level message.target_roles: Role names (from list_roles) to address. Each isprepended as `@role` and fans out to every live holder of thatrole — the single holder for an exclusive role, all current@@ -796,6 +802,15 @@ async def send_targeted_message(sent, and it will answer in the room saying it cannot act on it — soread its reply rather than treating this as a failed send. Reaching itanother way is a matter for whoever owns it, not for a retry.++ A room-wide mention reports under `everyone`: `sent` (the platform+ pages the room, or — on Telegram — already notifies every member of+ every message), `unsupported` (the platform has no channel-wide+ mention a bot can send, as on Teams; the message still posts),+ `no_bridge` (the room has no chat platform) or `bridge_unavailable`+ (its bridge is down or has no channel for the room, so the message+ never reaches the platform). It says what Switch sent, not what the+ platform confirmed."""agent_id = get_agent_id()room_id = await require_connected_room()diff --git a/core/switch_core/bridges/agent/protocol/instructions.py b/core/switch_core/bridges/agent/protocol/instructions.pyindex b19357780..0be203e05 100644--- a/core/switch_core/bridges/agent/protocol/instructions.py+++ b/core/switch_core/bridges/agent/protocol/instructions.py@@ -68,6 +68,11 @@ def _interaction_modes(profile: IntegrationProfile) -> str:"(via `target_roles`), who then receive it as an *addressed* event ""(they will respond). A role target fans out to every live holder of ""that role. Others see it as context.",+ '- **`send_targeted_message(target_names=["everyone"])`** — a '+ "room-wide mention: notifies every *person* in the room on its chat "+ "platform (`@channel` on Slack) and wakes no agent. Use it only when "+ "all of them need to see the message; writing `@channel` or "+ "`@everyone` into a body pages nobody.",]if caps.can_delegate or caps.can_accept:lines.append(diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex be7d9cce5..6b2ffe36e 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -49,6 +49,7 @@ from switch_core.bridges.agent.protocol.types import (RegistrationResult,RoomDescriptor,RoomDetailDescriptor,+ RoomWideMentionStatus,SendTargetedResult,ToolCallReport,ToolSpec,@@ -103,6 +104,12 @@ from switch_core.events import (ToolCallReport as MatrixToolCallReport,)from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE+from switch_core.room_wide_mention import (+ ROOM_WIDE_TARGET,+ is_reserved_mention_name,+ reject_reserved_mention_name,+ room_wide_mention_content,+)from switch_core.sessions.attachments import normalise_mime_typefrom switch_core.telemetry import TelemetryService, emit_safelyfrom switch_core.telemetry.ages import age_days@@ -373,7 +380,8 @@ class ProtocolService:Raises:ValueError: name is invalid (lowercase alphanumeric, dots, hyphens,- or underscores — no spaces).+ or underscores — no spaces), or is a room-wide mention word+ and no agent already has it.RuntimeError: no tenant is bound. Checked before anything iswritten, because the agent's row and its bridge identitiesboth belong to a tenant and neither can be placed without one.@@ -456,6 +464,10 @@ class ProtocolService:)logger.info("Re-registered agent: %s (%s)", name, agent_id)else:+ # New agents only: one registered under the name before it was+ # reserved keeps reconnecting, and a room-wide mention in a+ # room it belongs to is refused instead.+ reject_reserved_mention_name(name, kind="Agent name")agent_id = await self._create_agent(session=session,name=name,@@ -1202,11 +1214,14 @@ class ProtocolService:room_id: str,content: str,thread_id: str | None = None,+ *,+ extra_content: dict[str, object] | None = None,) -> str:"""Send a message to a room. Returns event_id.When thread_id is set the message is posted as a reply in that thread- (the id is normalised to the thread root). Raises ValueError if the+ (the id is normalised to the thread root). `extra_content` carries+ `com.switch.*` markers alongside the body. Raises ValueError if theagent is not a room member, the client is not running, or thread_iddoes not resolve to an event in the room.Raises PermissionError if auth fails (should not happen in same-process).@@ -1227,6 +1242,7 @@ class ProtocolService:room.matrix_room_id,content,thread_root_id=thread_root_id,+ extra_content=extra_content,metered=True,)if event_id is None:@@ -1419,19 +1435,45 @@ class ProtocolService:role); others still see the message as room context. When thread_id isset the message is posted into that thread.+ The reserved name `everyone` is a room-wide mention: it notifies the+ room's people on its chat platform and addresses no agent. It is+ marked on the message rather than read from the text, so only this+ call can page a room (see `room_wide_mention`).+Returns the posted event_id plus the reachability status of eachaddressed agent at send time — for role targets this is each liveholder. User targets are omitted from target_statuses — their- reachability is the bridge's concern.+ reachability is the bridge's concern. A room-wide mention reports+ under `everyone` what the room's bridge does with it.Raises ValueError if no targets are given, if a name does not match a- room participant, or if a role does not exist in the room.+ room participant, if a role does not exist in the room, or if a+ room-wide mention would address an agent that predates the name being+ reserved."""roles = target_roles or []if not target_names and not roles:raise ValueError("at least one of target_names / target_roles is required")+ # `@everyone` too: agents write the sigil out of habit.+ room_wide = any(+ n.lstrip("@").casefold() == ROOM_WIDE_TARGET for n in target_names+ )+ target_names = [+ n for n in target_names if n.lstrip("@").casefold() != ROOM_WIDE_TARGET+ ]+ if room_wide and thread_id is not None:+ # Slack sends no channel-wide alert from a thread, and Discord's+ # reaches only people already in it: a threaded room-wide mention+ # would report "sent" having paged next to nobody.+ raise ValueError(+ "A room-wide mention cannot go in a thread: the chat platforms "+ "only page the whole room from a top-level message. Send it "+ "without thread_id."+ )participants = await self.list_participants(room_id)+ if room_wide:+ await self._refuse_room_wide_mention_collisions(room_id, participants)participant_by_name = {p.name: p for p in participants}# Allow addressing an agent by its room alias: resolve any target that# isn't a known participant name through the room's aliases. The alias@@ -1449,9 +1491,14 @@ class ProtocolService:participant_by_name[name] = participant_by_id[resolved_id]unknown = [n for n in target_names if n not in participant_by_name]if unknown:+ hint = (+ f" For a room-wide mention, target {ROOM_WIDE_TARGET!r}."+ if any(is_reserved_mention_name(n.lstrip("@")) for n in unknown)+ else ""+ )raise ValueError(f"Targets not in room: {', '.join(unknown)}. "- f"Room participants: {', '.join(sorted(participant_by_name))}"+ f"Room participants: {', '.join(sorted(participant_by_name))}.{hint}")# Validate role targets and resolve their live holders (for statuses).@@ -1511,10 +1558,19 @@ class ProtocolService:):refused.add(name)- mention_tokens = [f"@{name}" for name in target_names]+ # The room-wide token goes first: a bridge replaces exactly that+ # leading token with its platform's own channel-wide mention.+ mention_tokens = [f"@{ROOM_WIDE_TARGET}"] if room_wide else []+ mention_tokens += [f"@{name}" for name in target_names]mention_tokens += [f"@{role}" for role in roles]body = f"{' '.join(mention_tokens)} {content}"- event_id = await self.send_message(agent_id, room_id, body, thread_id=thread_id)+ event_id = await self.send_message(+ agent_id,+ room_id,+ body,+ thread_id=thread_id,+ extra_content=room_wide_mention_content() if room_wide else None,+ )# Reachability: direct agent name targets plus each role's live holders.status_names = {@@ -1528,18 +1584,74 @@ class ProtocolService:# matter to the sender, but only one of them explains a reply that says# no — and "live" for an agent that will decline is the reading that# sends someone looking for a bug.- target_statuses = {- name: (- AgentStatus.NOT_PERMITTED- if name in refused- else participant_by_name[name].status- )- for name in status_names- if name in participant_by_name- and (name in refused or participant_by_name[name].status is not None)- }+ target_statuses: dict[str, AgentStatus | RoomWideMentionStatus] = {}+ for name in status_names:+ participant = participant_by_name.get(name)+ if participant is None:+ continue+ if name in refused:+ target_statuses[name] = AgentStatus.NOT_PERMITTED+ elif participant.status is not None:+ target_statuses[name] = participant.status+ if room_wide:+ target_statuses[ROOM_WIDE_TARGET] = self._room_wide_mention_status(+ room_id, room_row.bridge_id if room_row is not None else None+ )return SendTargetedResult(event_id=event_id, target_statuses=target_statuses)+ async def _refuse_room_wide_mention_collisions(+ self, room_id: str, participants: list[ParticipantDescriptor]+ ) -> None:+ """Raise ValueError if anything in the room answers to `@everyone`.++ Addressing matches a mention against an agent's name, its room alias+ and a role it holds, case-insensitively. The name is reserved for all+ three, but a row made before the reservation still matches, and a+ room-wide mention that woke it would break the one promise the feature+ makes. So the send is refused, naming what to rename.+ """+ clashes = [+ f"agent {p.name!r}"+ for p in participants+ if p.type == "agent" and p.name.casefold() == ROOM_WIDE_TARGET+ ]+ async with self.session_factory() as session:+ aliases = await self.room_store.list_aliases(session, room_id)+ roles = await self.room_role_store.list_roles(session, room_id)+ clashes += [+ f"alias {alias!r}"+ for alias in aliases.values()+ if alias.casefold() == ROOM_WIDE_TARGET+ ]+ clashes += [+ f"role {role.name!r}"+ for role in roles+ if role.name.casefold() == ROOM_WIDE_TARGET+ ]+ if clashes:+ raise ValueError(+ "Cannot send a room-wide mention: in this room "+ f"`@{ROOM_WIDE_TARGET}` would also address {', '.join(clashes)}. "+ "Rename it first — the name is reserved for room-wide mentions."+ )++ def _room_wide_mention_status(+ self, room_id: str, bridge_id: str | None+ ) -> RoomWideMentionStatus:+ """What the room's bridge does with a room-wide mention.++ This is what Switch sends, not what the platform confirmed: the bridge+ posts after this call has returned.+ """+ if bridge_id is None:+ return RoomWideMentionStatus.NO_BRIDGE+ bridge_core = self.collab_lifecycle.get(bridge_id)+ if bridge_core is None or not bridge_core.relays_room(room_id):+ return RoomWideMentionStatus.BRIDGE_UNAVAILABLE+ if bridge_core.adapter.room_wide_mention_notifies:+ return RoomWideMentionStatus.SENT+ return RoomWideMentionStatus.UNSUPPORTED+async def set_typing(self,agent_id: str,diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.pyindex 1a86a03c5..22265c77d 100644--- a/core/switch_core/bridges/agent/protocol/types.py+++ b/core/switch_core/bridges/agent/protocol/types.py@@ -120,9 +120,29 @@ class AgentStatus(StrEnum):NOT_PERMITTED = "not_permitted"+class RoomWideMentionStatus(StrEnum):+ """What a room-wide mention did, reported under `everyone`.++ What Switch sent, not what the platform confirmed: the bridge posts after+ `send_targeted_message` has returned.+ """++ # The bridge posts it as the platform's channel-wide mention, or the+ # platform already notifies every member of every message (Telegram).+ SENT = "sent"+ # The platform has no channel-wide mention a bot can send (Teams). The+ # message still posts; nobody is paged by it.+ UNSUPPORTED = "unsupported"+ # The room has no chat platform, so there is nobody to page.+ NO_BRIDGE = "no_bridge"+ # The room's bridge is not running, or has no channel for the room, so the+ # message reaches the room but not its chat platform.+ BRIDGE_UNAVAILABLE = "bridge_unavailable"++class SendTargetedResult(BaseModel):event_id: str- target_statuses: dict[str, AgentStatus]+ target_statuses: dict[str, AgentStatus | RoomWideMentionStatus]class DelegateTaskResult(BaseModel):diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 275e37dbb..938789fdf 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -6,7 +6,7 @@ from abc import ABC, abstractmethodfrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Any, ClassVar, Literal, Protocol, runtime_checkable+from typing import Any, ClassVar, Literal, Protocol, final, runtime_checkablefrom switch_core.agent_display_name import defuse_label_markupfrom switch_core.agent_icon import default_icon_url@@ -34,6 +34,11 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (request_summary,turn_summary,)+from switch_core.room_wide_mention import (+ ROOM_WIDE_TARGET,+ defuse_mass_mention_words,+ strip_room_wide_target,+)from switch_core.sessions.contract import (Item,SnapshotRequest,@@ -354,6 +359,18 @@ class CollaborationAdapter(ABC):#: them is a notification they already had.notifies_only_by_mention: ClassVar[bool] = False+ #: The token that pages every member of a channel, for a room-wide mention.+ #:+ #: None where the platform has none a bot can send. A room-wide mention+ #: there still posts, opening with an inert `@everyone`, and the agent is+ #: told it paged nobody — unless `every_message_notifies_members` says the+ #: platform does that work itself.+ channel_mention: ClassVar[str | None] = None++ #: Whether every message already notifies every member of the chat, so a+ #: room-wide mention needs no token of its own to reach them all.+ every_message_notifies_members: ClassVar[bool] = False+#: Whether a ticking clock is reason enough to redraw a running turn.#:#: True where the status is a small line of its own that a reader watches@@ -610,6 +627,8 @@ class CollaborationAdapter(ABC):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:"""Post a message to the external channel.@@ -617,6 +636,11 @@ class CollaborationAdapter(ABC):thread root (e.g. Mattermost root_id) — the message should be posted asa reply within that thread. Adapters whose platform does not supportthreads ignore it.++ room_wide_mention is set when `content` came from+ `render_room_wide_mention`, for a platform that has to permit a+ channel-wide mention on the request as well as write it in the text+ (Discord's `allowed_mentions`). Everywhere else the text alone does it."""...@@ -1228,8 +1252,52 @@ class CollaborationAdapter(ABC):@abstractmethodasync def get_channel_agent_names(self, channel_id: str) -> list[str]: ...+ @final+ def translate_outbound(self, content: str) -> str:+ """Render a Switch body in this platform's markup, unable to page.++ Final so that no adapter can forget the defusal: a platform renders in+ `_render_outbound`, and nothing a body says can then page a channel.+ Only `render_room_wide_mention` does that, for a message the server+ marked.+ """+ return self.defuse_mass_mentions(self._render_outbound(content))+@abstractmethod- def translate_outbound(self, content: str) -> str: ...+ def _render_outbound(self, content: str) -> str:+ """Render a Switch body in this platform's markup."""++ def defuse_mass_mentions(self, text: str) -> str:+ """Break every channel-wide mention in text on its way to the platform.++ Safe by default: the words — `@everyone`, `@channel`, `@here`, `@all`+ — are defused everywhere, code and URLs included, which is what a+ platform that pages from plain text (Mattermost) needs. A platform+ whose text cannot page on its own overrides this to leave code, URLs+ and addresses exact, and one with a syntax of its own for the same+ thing (Slack's `<!channel>`) escapes that too.+ """+ return defuse_mass_mention_words(text)++ def render_room_wide_mention(self, body: str) -> str:+ """The platform text of a message the server marked as room-wide.++ The body opens with the `@everyone` the server wrote. That token is+ taken off before translation, so a person on the platform who happens+ to be called `everyone` is not the one it resolves to, and the+ platform's own channel-wide mention goes in its place after+ translation, so the defusal the rest of the body gets cannot break it.+ """+ rest = self.translate_outbound(strip_room_wide_target(body))+ opening = self.channel_mention or defuse_mass_mention_words(+ f"@{ROOM_WIDE_TARGET}"+ )+ return f"{opening} {rest}" if rest else opening++ @property+ def room_wide_mention_notifies(self) -> bool:+ """Whether a room-wide mention reaches every member here."""+ return self.channel_mention is not None or self.every_message_notifies_members@abstractmethoddef translate_inbound(self, raw_message: str) -> str: ...diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 99333e18b..c21f848a3 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -59,6 +59,7 @@ from switch_core.observability.catalogue import (from switch_core.observability.metrics import metricsfrom switch_core.provisioning import Provisioningfrom switch_core.room_service import RoomCreateConfig+from switch_core.room_wide_mention import is_room_wide_mentionfrom switch_core.session_activity.bridge_answers import ApprovalAnswersfrom switch_core.session_activity.bridge_publisher import (SessionActivityBridgePublisher,@@ -276,6 +277,14 @@ class BridgeCore:def adapter(self) -> CollaborationAdapter:return self._adapter+ def relays_room(self, room_id: str) -> bool:+ """Whether a message in this Switch room reaches the platform now.++ A bridge is registered before `start` has loaded its channel map, and a+ room it has no channel for is dropped by `handle_outbound_message`, so+ being registered is not the same as relaying."""+ return self._find_channel(room_id=room_id) is not None+@propertydef tenant_id(self) -> str:return self._bridge_tenant_id@@ -1942,11 +1951,19 @@ class BridgeCore:)else:assert sender_name is not None # guarded above+ # Only the marker pages a channel. An `@channel` an agent wrote+ # itself is defused by `translate_outbound` like any other text.+ room_wide = is_room_wide_mention(event_content)message_ref = await self._adapter.send_message(channel_id,sender_name,- self._adapter.translate_outbound(event.body),+ (+ self._adapter.render_room_wide_mention(event.body)+ if room_wide+ else self._adapter.translate_outbound(event.body)+ ),thread_root_id=thread_root_ref,+ room_wide_mention=room_wide,)if message_ref is not None:diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 3040d28b3..250f66835 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -35,7 +35,10 @@ from switch_core.bridges.collaboration.discord.chunking import (MAX_MESSAGE,chunk_message,)-from switch_core.bridges.collaboration.discord.connection import DiscordConnection+from switch_core.bridges.collaboration.discord.connection import (+ NO_MASS_MENTIONS,+ DiscordConnection,+)from switch_core.bridges.collaboration.discord.slash import (SlashArgError,build_app_commands,@@ -73,6 +76,10 @@ from switch_core.bridges.collaboration.session.renderers.neutral import (render_request,turn_status,)+from switch_core.room_wide_mention import (+ CODE_AND_URLS,+ defuse_mass_mention_words_in_prose,+)from switch_core.sessions.contract import TURN_ENDEDlogger = logging.getLogger(__name__)@@ -113,13 +120,9 @@ _UNKNOWN_MESSAGE_CODE = 10008# and not the reader's._UNKNOWN_MEMBER_CODE = 10007-# Applied to the bot posts that inline an agent's name into the body — the DM-# path, which has no webhook identity to carry it. Escaping the text is not-# enough on its own: Discord decides who a message pings from the raw content-# it receives, so `@everyone` in a name is refused here rather than in markup.-# Only the mass mentions are withheld; a user or role the agent deliberately-# mentioned still resolves.-_NO_MASS_MENTIONS = discord.AllowedMentions(everyone=False)+# The one exception, for a message the server marked as a room-wide mention.+# Discord needs both halves: `@everyone` in the text and this on the request.+_ROOM_WIDE_MENTION = discord.AllowedMentions(everyone=True)# Inserted after the `<` of anything that looks like a Discord entity. Discord# has no escape for `<`, so the syntax is broken rather than escaped — the same@@ -515,6 +518,7 @@ class DiscordAdapter(CollaborationAdapter):# channel root is in none of those, so a reply that names nobody reaches# nobody.notifies_only_by_mention: ClassVar[bool] = True+ channel_mention: ClassVar[str | None] = "@everyone"# The status is the turn's one post, so the clock rides along with the next# real change rather than rewriting a message somebody is reading. See the@@ -769,6 +773,8 @@ class DiscordAdapter(CollaborationAdapter):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:try:target = await self._get_channel(int(channel_id))@@ -785,7 +791,7 @@ class DiscordAdapter(CollaborationAdapter):lambda part: target.send(part,suppress_embeds=True,- allowed_mentions=_NO_MASS_MENTIONS,+ allowed_mentions=NO_MASS_MENTIONS,),where=f"DM {channel_id}",)@@ -816,6 +822,7 @@ class DiscordAdapter(CollaborationAdapter):# chunk and could split one message across two different avatars.agent = await self.agent_rendering(sender_name)identity = _WebhookIdentity(agent.field_label, sender_name)+ allowed_mentions = _ROOM_WIDE_MENTION if room_wide_mention else NO_MASS_MENTIONSreturn await self._send_chunked(content,lambda part: identity.send(@@ -824,6 +831,7 @@ class DiscordAdapter(CollaborationAdapter):"content": part,"avatar_url": agent.icon_url,"suppress_embeds": True,+ "allowed_mentions": allowed_mentions,"wait": True,**kwargs,},@@ -925,7 +933,7 @@ class DiscordAdapter(CollaborationAdapter):msg = await target.send(content,file=discord.File(io.BytesIO(data), filename=filename),- allowed_mentions=_NO_MASS_MENTIONS,+ allowed_mentions=NO_MASS_MENTIONS,)return f"{msg.channel.id}:{msg.id}"except discord.HTTPException:@@ -965,6 +973,7 @@ class DiscordAdapter(CollaborationAdapter):"content": body,"avatar_url": agent.icon_url,"file": discord.File(io.BytesIO(data), filename=filename),+ "allowed_mentions": NO_MASS_MENTIONS,"wait": True,**kwargs,},@@ -1029,7 +1038,9 @@ class DiscordAdapter(CollaborationAdapter):return await self._send_chunked(self._admin_body(self.translate_outbound(content), drawn),- lambda part: target.send(part, suppress_embeds=True),+ lambda part: target.send(+ part, suppress_embeds=True, allowed_mentions=NO_MASS_MENTIONS+ ),where=f"channel {channel_id}",)@@ -1476,7 +1487,7 @@ class DiscordAdapter(CollaborationAdapter):sent = await target.send(text,suppress_embeds=True,- allowed_mentions=_NO_MASS_MENTIONS,+ allowed_mentions=NO_MASS_MENTIONS,**kwargs,)except Exception as error:@@ -1510,7 +1521,7 @@ class DiscordAdapter(CollaborationAdapter):"content": text,"avatar_url": agent.icon_url,"suppress_embeds": True,- "allowed_mentions": _NO_MASS_MENTIONS,+ "allowed_mentions": NO_MASS_MENTIONS,"wait": True,}if thread is not None:@@ -1699,7 +1710,7 @@ class DiscordAdapter(CollaborationAdapter):target = await self._get_channel(int(location_id or channel_id))message = await target.fetch_message(int(message_id))await message.edit(- content=text, view=view, allowed_mentions=_NO_MASS_MENTIONS+ content=text, view=view, allowed_mentions=NO_MASS_MENTIONS)returnkwargs: dict[str, Any] = {}@@ -1710,7 +1721,7 @@ class DiscordAdapter(CollaborationAdapter):int(message_id),content=text,view=view,- allowed_mentions=_NO_MASS_MENTIONS,+ allowed_mentions=NO_MASS_MENTIONS,**kwargs,)except Exception as error:@@ -2560,7 +2571,7 @@ class DiscordAdapter(CollaborationAdapter):# ── Translation ──────────────────────────────────────────────────────────- def translate_outbound(self, content: str) -> str:+ def _render_outbound(self, content: str) -> str:# Discord renders markdown natively (bold, code, headers, masked# links), so only @name mentions need rewriting to real Discord# mentions: a resolved user, or an agent that has a role of its own so@@ -2575,6 +2586,14 @@ class DiscordAdapter(CollaborationAdapter):return re.sub(r"@([a-z0-9][a-z0-9._-]*)", _replace, content)+ def defuse_mass_mentions(self, text: str) -> str:+ """Defuse the words as prose: `allowed_mentions` is Discord's guard.++ Every send refuses `@everyone` and `@here` on the request unless the+ server marked the message, so the words are defused only for how they+ read, leaving code and links exact."""+ return defuse_mass_mention_words_in_prose(text, keep=CODE_AND_URLS)+def escape_label_for_body(self, label: str) -> str:"""Defuse Discord's markdown, mentions and `<…>` entity syntax.diff --git a/core/switch_core/bridges/collaboration/discord/connection.py b/core/switch_core/bridges/collaboration/discord/connection.pyindex 4191dccef..19e1bf430 100644--- a/core/switch_core/bridges/collaboration/discord/connection.py+++ b/core/switch_core/bridges/collaboration/discord/connection.py@@ -16,6 +16,14 @@ logger = logging.getLogger(__name__)_READY_TIMEOUT = 30.0+# The client's default, and passed again on every post that carries text+# Switch did not write, so no single path depends on the other. Escaping the+# text is not enough on its own: Discord decides who a message pings from the+# raw content it receives, so `@everyone` is refused here rather than in+# markup. Only the mass mentions are withheld; a user or role the agent+# deliberately mentioned still resolves.+NO_MASS_MENTIONS = discord.AllowedMentions(everyone=False)+# A member search is a Gateway send, and discord.py holds every send past 110 a# minute on one socket until the minute is up. On the shared connection that# budget is every organisation's at once, so searches get about half of it and@@ -186,7 +194,9 @@ class DiscordConnection:`_READY_TIMEOUT`. On timeout the half-open client is torn down; on aconnect-task failure it is left as-is for the caller's `close()`."""- client = discord.Client(intents=self._intents)+ client = discord.Client(+ intents=self._intents, allowed_mentions=NO_MASS_MENTIONS+ )client.event(self._make_on_message())# Presses on a card's buttons. Registered alongside the command tree# rather than through it: the tree is handed application-commanddiff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex ee5d26a7a..e6b3c1810 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -279,6 +279,7 @@ class MattermostAdapter(CollaborationAdapter):#: post with nobody to name says as much. This is the legacy ping's policy,#: carried over: it is the one that reaches the person who can do something.notifies_only_by_mention: ClassVar[bool] = True+ channel_mention: ClassVar[str | None] = "@channel"#: The status is the turn's one post, not a line beside it, so the clock#: advancing is not on its own worth rewriting what a reader is reading.@@ -718,6 +719,8 @@ class MattermostAdapter(CollaborationAdapter):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:bot_driver = self._bot_drivers.get(sender_name)if not bot_driver:@@ -2349,12 +2352,8 @@ class MattermostAdapter(CollaborationAdapter):# ── Translation ──────────────────────────────────────────────────────────- def translate_outbound(self, content: str) -> str:- return re.sub(- r"@(\w+):\S+",- r"@\1",- content,- )+ def _render_outbound(self, content: str) -> str:+ return re.sub(r"@(\w+):\S+", r"@\1", content)def translate_inbound(self, raw_message: str) -> str:return raw_messagediff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 579db8e59..9a41ec5a0 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -62,10 +62,27 @@ from switch_core.bridges.collaboration.slack.agent_groups import ()from switch_core.bridges.collaboration.slack.avatar import on_slack_backgroundfrom switch_core.bridges.collaboration.slack.mrkdwn import escape_mrkdwn+from switch_core.room_wide_mention import (+ CODE_AND_URLS,+ defuse_mass_mention_words_in_prose,+)from switch_core.sessions.contract import TURN_ENDEDlogger = logging.getLogger(__name__)+# A channel-wide mention in Slack's own syntax, with or without the `|label`+# a client may add. `group` is the legacy name for `channel` in a private one.+_SLACK_MASS_MENTION = re.compile(+ r"<(!(?:channel|here|everyone|group)(?:\|[^>]*)?)>", re.IGNORECASE+)++# The same mention as it arrives, read back to the word a person typed. A raw+# `<!channel>` in delivered text is always a real mention: Slack escapes a `<`+# a person types, so nobody can write one by hand.+_SLACK_MASS_MENTION_WORD = re.compile(+ r"<!(channel|here|everyone|group)(?:\|[^>]*)?>", re.IGNORECASE+)+# 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 — "@@ -312,6 +329,7 @@ class _ActivityStream:class SlackAdapter(CollaborationAdapter):draws_session_activity: ClassVar[bool] = Trueseparate_attention_slot: ClassVar[bool] = True+ channel_mention: ClassVar[str | None] = "<!channel>"#: Cheap on a stream in a way it never was on an edit. An append is rate#: limited at 100+/min and redraws nothing, so the clock ticks in the one#: message without disturbing what is open in front of a reader.@@ -498,6 +516,8 @@ class SlackAdapter(CollaborationAdapter):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:if not self._web_client:logger.error("Cannot send message: Slack client not connected")@@ -512,7 +532,12 @@ class SlackAdapter(CollaborationAdapter):if ":" in thread_root_idelse thread_root_id)- elif self._channel_type_cache.get(channel_id) in ("im", "mpim"):+ elif (+ self._channel_type_cache.get(channel_id) in ("im", "mpim")+ and not room_wide_mention+ ):+ # Not for a room-wide mention: Slack sends no channel-wide alert+ # from a thread.thread_ts = self._last_user_message_ts.get(channel_id)agent = await self.agent_rendering(sender_name)@@ -2480,9 +2505,23 @@ class SlackAdapter(CollaborationAdapter):# ── Translation ──────────────────────────────────────────────────────────- def translate_outbound(self, content: str) -> str:+ def _render_outbound(self, content: str) -> str:return self._markdown_to_mrkdwn(self._translate_mentions_to_slack(content))+ def defuse_mass_mentions(self, text: str) -> str:+ """Escape Slack's own channel-wide syntax; defuse the words as prose.++ `<!channel>`, `<!here>`, `<!everyone>` and the legacy `<!group>` page+ a channel from any text Slack parses, and this runs on the finished+ mrkdwn because the translation can write one: a Markdown link to+ `!channel` comes out of it as `<!channel|…>`. Escaping shows the token+ as written rather than hiding it. The words themselves page nobody on+ Slack, so they are defused only where that leaves code and links+ exact."""+ return defuse_mass_mention_words_in_prose(+ _SLACK_MASS_MENTION.sub(r"<\1>", text), keep=CODE_AND_URLS+ )+def escape_label_for_body(self, label: str) -> str:"""Escape the three characters Slack reserves, over the base defusal.@@ -2504,9 +2543,26 @@ class SlackAdapter(CollaborationAdapter):def translate_inbound(self, raw_message: str) -> str:return self._translate_links_to_markdown(- self._translate_mentions_to_markdown(raw_message)+ self._translate_mass_mentions_to_markdown(+ self._translate_mentions_to_markdown(raw_message)+ ))+ @staticmethod+ def _translate_mass_mentions_to_markdown(message: str) -> str:+ """Show a person's `<!channel>`, `<!here>` or `<!everyone>` as the word.++ Agents read the room's history as text, and the raw code says nothing to+ them. The word wakes no agent, because these names are reserved and+ none can carry them. `group` is the legacy spelling of `channel`.+ """++ def _replace(match: re.Match[str]) -> str:+ word = match.group(1).lower()+ return "@channel" if word == "group" else f"@{word}"++ return _SLACK_MASS_MENTION_WORD.sub(_replace, message)+@staticmethoddef _translate_links_to_markdown(message: str) -> str:"""Convert Slack link syntax `<url|label>` / `<url>` to markdown."""diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex f5f48af18..c3284761c 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -81,6 +81,10 @@ from switch_core.bridges.collaboration.teams.crypto import (load_certificate_der_b64,)from switch_core.bridges.collaboration.teams.graph import GraphClient+from switch_core.room_wide_mention import (+ CODE_AND_URLS,+ defuse_mass_mention_words_in_prose,+)from switch_core.sessions.contract import TURN_ENDEDlogger = logging.getLogger(__name__)@@ -1202,6 +1206,8 @@ class TeamsAdapter(CollaborationAdapter):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:if self._connector is None:raise RuntimeError("Cannot send message: Teams adapter not started")@@ -2184,9 +2190,17 @@ class TeamsAdapter(CollaborationAdapter):)return self._mention_pattern- def translate_outbound(self, content: str) -> str:+ def _render_outbound(self, content: str) -> str:return self._mark_mentions(content)+ def defuse_mass_mentions(self, text: str) -> str:+ """Defuse the words as prose: Teams pages nobody from text.++ A Teams mention needs an entity alongside the `<at>` markup, and there+ is no entity for a whole channel, so the words are defused only for+ how they read, leaving code and links exact."""+ return defuse_mass_mention_words_in_prose(text, keep=CODE_AND_URLS)+def escape_label_for_body(self, label: str) -> str:"""Add the `<at>` tag to what the base class already defuses.diff --git a/core/switch_core/bridges/collaboration/telegram/adapter.py b/core/switch_core/bridges/collaboration/telegram/adapter.pyindex 2f397febe..4ec226922 100644--- a/core/switch_core/bridges/collaboration/telegram/adapter.py+++ b/core/switch_core/bridges/collaboration/telegram/adapter.py@@ -82,10 +82,20 @@ from switch_core.bridges.collaboration.telegram.chunking import (MAX_MESSAGE,chunk_message,)+from switch_core.room_wide_mention import (+ CODE_AND_URLS,+ defuse_mass_mention_words_in_prose,+)from switch_core.sessions.contract import TURN_ENDEDlogger = logging.getLogger(__name__)+# Code and links as `_render_outbound` leaves them: rendered HTML, not Markdown.+_TELEGRAM_KEEP = re.compile(+ rf"<pre>.*?</pre>|<code>.*?</code>|{CODE_AND_URLS.pattern}",+ re.DOTALL | re.IGNORECASE,+)+# A caption over this is posted as its own message ahead of the file. The# message-length cap lives in `chunking`, which owns the splitting._MAX_CAPTION_CHARS = 1024@@ -474,6 +484,7 @@ class TelegramAdapter(CollaborationAdapter):#: named, so a mention is an emphasis rather than the only route to a#: reader. Naming the asker still happens; it is not what delivery rests on.notifies_only_by_mention: ClassVar[bool] = False+ every_message_notifies_members: ClassVar[bool] = True#: The status is the turn's one post, so the seconds ride along with the#: next real change rather than rewriting it on a timer. Telegram's edit@@ -944,6 +955,8 @@ class TelegramAdapter(CollaborationAdapter):sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:"""Post as the bot with the agent's name at the head of the message.@@ -2116,7 +2129,7 @@ class TelegramAdapter(CollaborationAdapter):_ITALIC_USCORE_RE = re.compile(r"(?<![\w_])_([^_\n]+?)_(?![\w_])")_MENTION_RE = re.compile(r"@([A-Za-z0-9][A-Za-z0-9._-]*)")- def translate_outbound(self, content: str) -> str:+ def _render_outbound(self, content: str) -> str:"""Render Switch's Markdown as the HTML subset Telegram accepts.Telegram's own MarkdownV2 is not Markdown — it requires escaping a long@@ -2181,6 +2194,15 @@ class TelegramAdapter(CollaborationAdapter):text = text.replace(f"\x00{index}\x00", rendered)return text+ def defuse_mass_mentions(self, text: str) -> str:+ """Defuse the words as prose: Telegram has no channel-wide mention.++ What it does to a public `@here` is link it, so the words are still+ defused, but outside code and links. By the time this runs a code span+ is `<code>` or `<pre>` HTML rather than backticks, which is why its+ pattern is this adapter's own."""+ return defuse_mass_mention_words_in_prose(text, keep=_TELEGRAM_KEEP)+def _render_mention(self, match: re.Match[str]) -> str:"""An `@name` we can resolve becomes a real mention; anything else isleft as written.diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.pyindex 89dd86149..767137bd1 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/admin_client.py@@ -32,6 +32,7 @@ from switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.events import CommandEvent+from switch_core.room_wide_mention import is_reserved_mention_namefrom switch_core.transport import InboundMessage, RoomRefif TYPE_CHECKING:@@ -239,8 +240,9 @@ class AdminClient(ClientBase[ClientConfig]):An `@name` that resolves to a registered agent which is not in this roomroutes to nobody, so the admin posts a heads-up in the triggeringmessage's thread naming the absent agent(s). Tokens that map to a- room-role (handled by `_warn_unreachable_roles`), to a current member, or- to no agent at all (a human user or a typo) are ignored.+ room-role (handled by `_warn_unreachable_roles`), to a current member,+ to no agent at all (a human user or a typo), or that is a room-wide+ mention word (`@everyone` pages the room's people) are ignored."""body = getattr(event, "body", "") or ""if "@" not in body:@@ -256,7 +258,7 @@ class AdminClient(ClientBase[ClientConfig]):for role in await self._room_role_store.list_roles(session, room_id)}for token in tokens:- if token.lower() in role_names:+ if token.lower() in role_names or is_reserved_mention_name(token):continueagent = await self._agent_store.get_by_name_insensitive(session, token)if agent is None or agent.id in member_ids:diff --git a/core/switch_core/db/stores/room_role_store.py b/core/switch_core/db/stores/room_role_store.pyindex 503f24463..bc55b004a 100644--- a/core/switch_core/db/stores/room_role_store.py+++ b/core/switch_core/db/stores/room_role_store.py@@ -20,6 +20,20 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.sql.elements import ColumnElementfrom switch_core.db.models import RoleLease, RoomRole+from switch_core.room_wide_mention import reject_reserved_mention_name+++def validate_role_name(name: str) -> None:+ """Raise ValueError unless `name` can be addressed as a role.++ Roles are addressed with `@<name>` tokens (in messages and+ `send_targeted_message`), so a name with a space could never be matched as+ a single mention token, and a room-wide mention word would page the room's+ people and its role holder with the same tag.+ """+ if not name or any(ch.isspace() for ch in name):+ raise ValueError("Role name must be non-empty and contain no whitespace")+ reject_reserved_mention_name(name, kind="Role name")class RoomRoleStore:@@ -60,13 +74,10 @@ class RoomRoleStore:) -> RoomRole:"""Create a role.- Raises ValueError if the name is empty, contains whitespace, or already- exists in the room. Whitespace is rejected because roles are addressed- with `@<name>` tokens (in messages and `send_targeted_message`); a name- with a space could never be matched as a single mention token.+ Raises ValueError if `validate_role_name` rejects the name or it+ already exists in the room."""- if not name or any(ch.isspace() for ch in name):- raise ValueError("Role name must be non-empty and contain no whitespace")+ validate_role_name(name)existing = await self.get_role(session, room_id, name)if existing is not None:raise ValueError(f"Role '{name}' already exists in this room")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 8523e5eaf..c87556f14 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -21,7 +21,7 @@ from typing import TYPE_CHECKING, Any, Literalfrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.aliases import validate_alias_map+from switch_core.aliases import validate_alias_format, validate_alias_mapfrom switch_core.authz import Principal, can, validate_visibility_pairfrom switch_core.bridges.collaboration.models import (ChannelCreationUnsupported,@@ -33,6 +33,7 @@ from switch_core.db.models import Room, RoomGroup, RoomRolefrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_role_store import validate_role_namefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.provisioning import Provisioning@@ -476,6 +477,13 @@ class RoomService:async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:await self._validate_attachments(config)+ # Before anything is provisioned: a name refused after the channel and+ # the room exist would leave both behind. Alias collisions need the+ # resolved agents and are checked with them, below.+ for spec in config.roles or []:+ validate_role_name(spec.name)+ for alias in (config.aliases or {}).values():+ validate_alias_format(alias)# Validate the group up front so a bad id fails before we provision a# Matrix room / external channel.if config.group_id is not None:diff --git a/core/switch_core/room_wide_mention.py b/core/switch_core/room_wide_mention.pynew file mode 100644index 000000000..260332e33--- /dev/null+++ b/core/switch_core/room_wide_mention.py@@ -0,0 +1,122 @@+"""The room-wide mention: an agent notifying every person in a room at once.++An agent asks for one with the reserved target `everyone` on+`send_targeted_message`. It reaches the people, never the agents. Addressing+matches only an agent's name, its room alias or a role it holds (see+`delivery/addressing.py`), and `everyone` is reserved so that none of those can+be it. Where a name predates the reservation, the send refuses rather than+wake whoever holds it.++What makes a bridge ping the channel is the marker below, never the message+text. The body opens with a readable `@everyone` for the transcript, but only a+message the server marked is rendered as the platform's channel-wide mention.+Every other outbound body has these words defused, so an agent typing+`@channel` into an ordinary message cannot page anyone.++`channel`, `here` and `all` are reserved alongside `everyone` because they are+the platforms' own words for it: Mattermost passes a person's `@channel`+through as text, so an agent named `channel` would be addressed every time+somebody paged the room.+"""++from __future__ import annotations++import re+from collections.abc import Mapping++from switch_core.agent_display_name import ZERO_WIDTH_SPACE+from switch_core.clients.mentions import NAME_CHAR++ROOM_WIDE_TARGET = "everyone"++RESERVED_MENTION_NAMES = frozenset({ROOM_WIDE_TARGET, "channel", "here", "all"})++# Stamped on the content of a message the server sent as a room-wide mention.+# Only `ProtocolService.send_targeted_message` writes it; a bridge reads it to+# decide whether to render the platform's channel-wide mention.+ROOM_WIDE_MENTION_MARKER = "com.switch.room_wide_mention"++_WORD = rf"(?:{'|'.join(sorted(RESERVED_MENTION_NAMES))})[._-]*(?!{NAME_CHAR})"++# A reserved word after `@`, allowing the trailing `.`, `-` or `_` a platform+# strips before matching (Mattermost pages the channel for `@channel.`), but+# not a longer handle that merely starts with one (`@allison`, `@all-hands`).+_ANY_AT = re.compile(rf"@(?={_WORD})", re.IGNORECASE)++# The same, only where a word starts, so `ops@here` is left an address.+_WORD_START_AT = re.compile(rf"(?<![A-Za-z0-9])@(?={_WORD})", re.IGNORECASE)++# Code and URLs, approximately. Only good enough for a platform whose text+# cannot page anyone anyway, where this keeps a copied command or a link to+# `…/package/@here/sdk` exact; it does not follow Markdown's rules, so a+# platform that pages from text must not rely on it.+CODE_AND_URLS = re.compile(+ r"```.*?```|~~~.*?~~~|`[^`\n]*`|https?://[A-Za-z0-9]\S*",+ re.DOTALL | re.IGNORECASE,+)++_LEADING_TARGET = re.compile(rf"\A@{ROOM_WIDE_TARGET}(?!{NAME_CHAR})[ \t]*")+++def is_reserved_mention_name(name: str) -> bool:+ return name.casefold() in RESERVED_MENTION_NAMES+++def reject_reserved_mention_name(name: str, *, kind: str) -> None:+ """Raise ValueError when `name` is one of the room-wide mention words.++ `kind` names what was being created ("Agent name", "Role name") so the+ message says which field to change.+ """+ if is_reserved_mention_name(name):+ raise ValueError(+ f"{kind} {name!r} is reserved for room-wide mentions, so it cannot "+ "name an agent, alias or role."+ )+++def room_wide_mention_content() -> dict[str, object]:+ """The `extra_content` that marks a message as a room-wide mention."""+ return {ROOM_WIDE_MENTION_MARKER: {}}+++def is_room_wide_mention(content: Mapping[str, object]) -> bool:+ return ROOM_WIDE_MENTION_MARKER in content+++def strip_room_wide_target(body: str) -> str:+ """Remove the leading `@everyone` the server wrote, so a bridge can put its+ own platform's mention in its place."""+ return _LEADING_TARGET.sub("", body, count=1)+++def defuse_mass_mention_words(text: str) -> str:+ """Break every `@everyone`, `@channel`, `@here` and `@all`, wherever it is.++ A zero-width space after the `@` leaves the word legible and the mention+ dead, the same defusal `defuse_label_markup` applies to display names.+ This is the form for a platform where the text is the only guard: no+ exemption for code or URLs, because deciding what counts as either means+ parsing Markdown the way that platform does, and a near miss pages a room.+ """+ return _ANY_AT.sub("@" + ZERO_WIDTH_SPACE, text)+++def defuse_mass_mention_words_in_prose(text: str, *, keep: re.Pattern[str]) -> str:+ """The words where a word starts, outside the spans `keep` matches.++ For a platform whose text cannot page anyone on its own — Slack pages only+ on `<!channel>`, Discord only when the request permits it — so defusing is+ about how the message reads, and leaving code, URLs and addresses exact+ matters more.+ """+ parts: list[str] = []+ last = 0+ for span in keep.finditer(text):+ parts.append(+ _WORD_START_AT.sub("@" + ZERO_WIDTH_SPACE, text[last : span.start()])+ )+ parts.append(span.group(0))+ last = span.end()+ parts.append(_WORD_START_AT.sub("@" + ZERO_WIDTH_SPACE, text[last:]))+ return "".join(parts)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.pyindex d38313f1e..8342afa0a 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py@@ -7,7 +7,10 @@ import pytestfrom switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService-from switch_core.bridges.agent.protocol.types import AgentStatus+from switch_core.bridges.agent.protocol.types import (+ AgentStatus,+ RoomWideMentionStatus,+)class _FakeSession:@@ -45,11 +48,15 @@ class _FakeAgentStore:class _FakeRoomStore:- def __init__(self, group_id: str | None) -> None:+ def __init__(self, group_id: str | None, bridge_id: str | None) -> None:self._group_id = group_id+ self._bridge_id = bridge_idasync def get(self, _session: Any, _room_id: str) -> Any:- return SimpleNamespace(group_id=self._group_id)+ return SimpleNamespace(group_id=self._group_id, bridge_id=self._bridge_id)++ async def list_aliases(self, _session: Any, _room_id: str) -> dict[str, str]:+ return {}def _participant(@@ -86,13 +93,18 @@ def _build_service(svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, holders) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]- svc.room_store = _FakeRoomStore(group_id) # type: ignore[assignment]+ svc.room_store = _FakeRoomStore(group_id, None) # type: ignore[assignment]async def _list_participants(_room_id: str) -> list[Any]:return list(participants)async def _send_message(- _agent_id: str, _room_id: str, body: str, thread_id: str | None = None+ _agent_id: str,+ _room_id: str,+ body: str,+ thread_id: str | None = None,+ *,+ extra_content: dict[str, object] | None = None,) -> str:sent_bodies.append(body)return "evt-1"@@ -320,3 +332,93 @@ class TestSendTargetedAddressingGate:"sender", "room-1", ["alice"], "ping")assert out_of_group.target_statuses == {"alice": AgentStatus.NOT_PERMITTED}+++class TestRoomWideMentionStatus:+ """What the room's bridge does with a room-wide mention, reported under+ `everyone`. Whether it wakes an agent is pinned against a real database in+ `test_room_wide_mention_wakes_no_agent.py`."""++ async def _send(self, bridges: dict[str, Any], bridge_id: str | None) -> Any:+ svc, bodies = _build_service(+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],+ roles=[],+ holders={},+ agents={},+ )+ svc.room_store = _FakeRoomStore(None, bridge_id) # type: ignore[assignment]+ svc.collab_lifecycle = SimpleNamespace(get=bridges.get) # type: ignore[assignment]+ result = await svc.send_targeted_message("sender", "room-1", ["everyone"], "hi")+ assert bodies == ["@everyone hi"]+ return result.target_statuses++ @staticmethod+ def _bridge(notifies: bool, relays: bool) -> Any:+ return SimpleNamespace(+ adapter=SimpleNamespace(room_wide_mention_notifies=notifies),+ relays_room=lambda _room_id: relays,+ )++ async def test_a_platform_that_pages_the_room(self) -> None:+ statuses = await self._send({"b1": self._bridge(True, True)}, "b1")+ assert statuses == {"everyone": RoomWideMentionStatus.SENT}++ async def test_a_platform_with_no_channel_mention(self) -> None:+ statuses = await self._send({"b1": self._bridge(False, True)}, "b1")+ assert statuses == {"everyone": RoomWideMentionStatus.UNSUPPORTED}++ async def test_a_bridge_that_is_not_running(self) -> None:+ statuses = await self._send({}, "b1")+ assert statuses == {"everyone": RoomWideMentionStatus.BRIDGE_UNAVAILABLE}++ async def test_a_bridge_with_no_channel_for_the_room(self) -> None:+ # Registered is not relaying: a bridge still starting, or one with no+ # channel mapped for this room, drops the message.+ statuses = await self._send({"b1": self._bridge(True, False)}, "b1")+ assert statuses == {"everyone": RoomWideMentionStatus.BRIDGE_UNAVAILABLE}++ async def test_a_room_with_no_bridge(self) -> None:+ statuses = await self._send({}, None)+ assert statuses == {"everyone": RoomWideMentionStatus.NO_BRIDGE}++ async def test_a_platform_word_points_at_the_real_target(self) -> None:+ svc, bodies = _build_service(+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],+ roles=[],+ holders={},+ agents={},+ )+ with pytest.raises(ValueError, match="target 'everyone'"):+ await svc.send_targeted_message("sender", "room-1", ["channel"], "hi")+ assert bodies == []++ async def test_the_sigil_is_forgiven(self) -> None:+ # Agents write `@` out of habit; `@everyone` means the same thing.+ svc, bodies = _build_service(+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],+ roles=[],+ holders={},+ agents={},+ )+ svc.collab_lifecycle = SimpleNamespace(get=lambda _b: None) # type: ignore[assignment]+ result = await svc.send_targeted_message(+ "sender", "room-1", ["@Everyone"], "hi"+ )+ assert bodies == ["@everyone hi"]+ assert result.target_statuses == {"everyone": RoomWideMentionStatus.NO_BRIDGE}++ async def test_a_thread_is_refused(self) -> None:+ # Slack sends no channel-wide alert from a thread, and Discord's+ # reaches only the thread's members, so it would report "sent" having+ # paged next to nobody.+ svc, bodies = _build_service(+ participants=[_participant("alice", "agent", AgentStatus.LIVE)],+ roles=[],+ holders={},+ agents={},+ )+ with pytest.raises(ValueError, match="cannot go in a thread"):+ await svc.send_targeted_message(+ "sender", "room-1", ["everyone"], "hi", thread_id="sw_root"+ )+ assert bodies == []diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.pyindex 7d6c065f0..deefef0ff 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_display_names.py@@ -124,7 +124,7 @@ class _BareAdapter(CollaborationAdapter):async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...def translate_inbound(self, *a: Any, **k: Any) -> Any: ...- def translate_outbound(self, *a: Any, **k: Any) -> Any: ...+ def _render_outbound(self, *a: Any, **k: Any) -> Any: ...class TestBridgeCoreResolver:diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.pyindex 3a0148d9f..e016aa8c1 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_agent_icons.py@@ -68,7 +68,7 @@ class _Adapter(CollaborationAdapter):async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...def translate_inbound(self, *a: Any, **k: Any) -> Any: ...- def translate_outbound(self, *a: Any, **k: Any) -> Any: ...+ def _render_outbound(self, *a: Any, **k: Any) -> Any: ...class TestBridgeCoreResolver:diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.pyindex a37e32a0f..da1f94baa 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py@@ -59,6 +59,8 @@ class _RecordingAdapter:sender_name: str,content: str,thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,) -> str | None:self.message_calls.append(content)return "ref-msg"diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.pyindex d60a98b1a..0a2a8b70f 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_adapter.py@@ -623,6 +623,63 @@ def test_send_message_posts_via_webhook_with_agent_identity() -> None:assert ref == f"{CHANNEL_ID}:901"+def test_an_agent_message_cannot_page_the_channel() -> None:+ # Discord decides who a message pings from the request, not the markup, so+ # the webhook path pins the same guard every other send path does.+ adapter = _adapter()+ adapter._connection._client = _FakeClient({CHANNEL_ID: _FakeChannel()})+ webhook = _FakeWebhook()+ adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook++ _run(adapter.send_message(str(CHANNEL_ID), "my-agent", "hello"))++ assert webhook.sent[0]["allowed_mentions"].everyone is False+++def test_a_room_wide_mention_is_permitted_on_the_request() -> None:+ adapter = _adapter()+ adapter._connection._client = _FakeClient({CHANNEL_ID: _FakeChannel()})+ webhook = _FakeWebhook()+ adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook++ _run(+ adapter.send_message(+ str(CHANNEL_ID),+ "my-agent",+ adapter.render_room_wide_mention("@everyone deploy at five"),+ room_wide_mention=True,+ )+ )++ assert webhook.sent[0]["content"] == "@everyone deploy at five"+ assert webhook.sent[0]["allowed_mentions"].everyone is True+++def test_an_attachment_caption_cannot_page_the_channel() -> None:+ adapter = _adapter()+ adapter._connection._client = _FakeClient({CHANNEL_ID: _FakeChannel()})+ webhook = _FakeWebhook()+ adapter._webhooks[(CHANNEL_ID, _WEBHOOK_NAME)] = webhook++ _run(+ adapter.send_attachment(+ str(CHANNEL_ID), "my-agent", "a.txt", "text/plain", b"x", "`@everyone`"+ )+ )++ assert webhook.sent[0]["allowed_mentions"].everyone is False+++def test_an_admin_message_cannot_page_the_channel() -> None:+ adapter = _adapter()+ channel = _FakeChannel()+ adapter._connection._client = _FakeClient({CHANNEL_ID: channel})++ _run(adapter.admin_message(str(CHANNEL_ID), "notice"))++ assert channel.sent[0]["allowed_mentions"].everyone is False++def test_long_message_is_split_across_posts_not_dropped() -> None:adapter = _adapter()channel = _FakeChannel()diff --git a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py b/core/tests/switch_core/bridges/collaboration/test_install_webhook.pyindex 7b72dc33f..cc0f29250 100644--- a/core/tests/switch_core/bridges/collaboration/test_install_webhook.py+++ b/core/tests/switch_core/bridges/collaboration/test_install_webhook.py@@ -111,7 +111,7 @@ class _SocketOnlyAdapter(CollaborationAdapter):async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...def translate_inbound(self, *a: Any, **k: Any) -> Any: ...- def translate_outbound(self, *a: Any, **k: Any) -> Any: ...+ def _render_outbound(self, *a: Any, **k: Any) -> Any: ...class _RecordingAdapter(_SocketOnlyAdapter):diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pyindex f0cf04f2e..52e802175 100644--- a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -94,7 +94,7 @@ class _StubAdapter(CollaborationAdapter):async def create_agent_identity(self, *a: Any, **k: Any) -> Any: ...async def remove_agent_identity(self, *a: Any, **k: Any) -> Any: ...def translate_inbound(self, *a: Any, **k: Any) -> Any: ...- def translate_outbound(self, *a: Any, **k: Any) -> Any: ...+ def _render_outbound(self, *a: Any, **k: Any) -> Any: ...class _StubConfig(BridgeConnectionConfig):diff --git a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.pyindex 7f71e724f..c2cee2e3f 100644--- a/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py+++ b/core/tests/switch_core/bridges/collaboration/test_rich_content_port.py@@ -67,7 +67,7 @@ class _BareAdapter(CollaborationAdapter):self.updated.append((channel_id, message_ref, new_content))self._update(new_content)- def translate_outbound(self, content: str) -> str:+ def _render_outbound(self, content: str) -> str:return self._translate(content)async def start(self, *a: Any, **k: Any) -> Any: ...diff --git a/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.py b/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.pynew file mode 100644index 000000000..c4a8f36a6--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_room_wide_mention_rendering.py@@ -0,0 +1,338 @@+"""How each platform renders a room-wide mention, and why nothing else pages.++Only a message the server marked may page a channel. So two things are pinned+for every real adapter: a marked message opens with the platform's own+channel-wide mention, and no ordinary body — whatever tokens an agent writes+into it — reaches the platform able to page anyone.+"""++from __future__ import annotations++from typing import Any++import pytest++from switch_core.bridges.collaboration.adapter import CollaborationAdapter+from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.discord.adapter import (+ DiscordAdapter,+ DiscordConnectionConfig,+)+from switch_core.bridges.collaboration.mattermost.adapter import (+ MattermostAdapter,+ MattermostConnectionConfig,+)+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.bridges.collaboration.teams.adapter import (+ TeamsAdapter,+ TeamsConnectionConfig,+)+from switch_core.bridges.collaboration.telegram.adapter import (+ TelegramAdapter,+ TelegramConnectionConfig,+)+from switch_core.room_wide_mention import room_wide_mention_content+from switch_core.transport import InboundMessage, RoomRef++ZWSP = "\u200b"+++def _slack() -> SlackAdapter:+ return SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"+ )+ )+++def _mattermost() -> MattermostAdapter:+ return MattermostAdapter(+ config=MattermostConnectionConfig(+ url="http://mm", admin_user="admin", admin_password="pw", team_name="team"+ )+ )+++def _discord() -> DiscordAdapter:+ return DiscordAdapter(config=DiscordConnectionConfig(bot_token="t", guild_id="900"))+++def _teams() -> TeamsAdapter:+ return TeamsAdapter(+ config=TeamsConnectionConfig(+ app_id="app-123",+ app_password="secret",+ tenant_id="tenant-9",+ team_id="team-7",+ public_base_url="https://switch.example",+ client_state="s3cr3t",+ )+ )+++def _telegram() -> TelegramAdapter:+ return TelegramAdapter(+ config=TelegramConnectionConfig(bot_token="token", bot_username="switch_bot")+ )+++ADAPTERS = {+ "slack": _slack,+ "mattermost": _mattermost,+ "discord": _discord,+ "teams": _teams,+ "telegram": _telegram,+}+++# ── A marked message ─────────────────────────────────────────────────────────+++ ("platform", "expected"),+ [+ ("slack", "<!channel> deploy at five"),+ ("mattermost", "@channel deploy at five"),+ ("discord", "@everyone deploy at five"),+ # No channel-wide mention a bot can send: the token stays legible and+ # inert, and the agent is told `unsupported`.+ ("teams", f"@{ZWSP}everyone deploy at five"),+ # Every member is notified of every message anyway, so an inert token+ # says who it was for without linking to a public `@everyone` handle.+ ("telegram", f"@{ZWSP}everyone deploy at five"),+ ],+)+def test_a_marked_message_opens_with_the_platforms_own_mention(+ platform: str, expected: str+) -> None:+ adapter = ADAPTERS[platform]()+ assert adapter.render_room_wide_mention("@everyone deploy at five") == expected+++ ("platform", "notifies"),+ [+ ("slack", True),+ ("mattermost", True),+ ("discord", True),+ ("teams", False),+ ("telegram", True),+ ],+)+def test_what_each_platform_reports_back(platform: str, notifies: bool) -> None:+ assert ADAPTERS[platform]().room_wide_mention_notifies is notifies+++def test_the_rest_of_a_marked_message_is_still_defused() -> None:+ # One page per message: an `@here` the agent wrote into the body of a+ # room-wide mention is not a second one.+ rendered = _mattermost().render_room_wide_mention("@everyone ping @here too")+ assert rendered == f"@channel ping @{ZWSP}here too"+++def test_a_person_called_everyone_is_not_who_a_room_wide_mention_names() -> None:+ adapter = _slack()+ adapter.prime_mention_targets({"everyone": "U999"})++ assert adapter.render_room_wide_mention("@everyone hi") == "<!channel> hi"+++def test_a_marked_message_with_no_body_is_just_the_mention() -> None:+ assert _slack().render_room_wide_mention("@everyone") == "<!channel>"+++# ── An ordinary message ──────────────────────────────────────────────────────++STRAY = [+ "@everyone",+ "@channel",+ "@here",+ "@all",+ "@Channel.",+ "ping @here, please",+]++[email protected]("platform", ADAPTERS)[email protected]("body", STRAY)+def test_no_ordinary_body_can_page_a_channel(platform: str, body: str) -> None:+ rendered = ADAPTERS[platform]().translate_outbound(body)++ assert f"@{ZWSP}" in rendered+ for word in ("everyone", "channel", "here", "all"):+ assert f"@{word}" not in rendered.lower()++[email protected]("platform", ADAPTERS)+def test_handles_that_merely_start_with_a_reserved_word_are_left_alone(+ platform: str,+) -> None:+ rendered = ADAPTERS[platform]().translate_outbound("cc @allison and @all-hands")+ assert ZWSP not in rendered++[email protected]("platform", ["slack", "discord", "teams"])+def test_code_keeps_its_text_exactly(platform: str) -> None:+ # Where text cannot page anyone on its own, `npm install @here/sdk`+ # copied out of a message must not carry a zero-width space with it.+ rendered = ADAPTERS[platform]().translate_outbound("run `npm i @here/sdk`")+ assert ZWSP not in rendered+++ "body",+ [+ "[docs](https://x.com),@channel",+ "\\`@channel\\`",+ "x ~~~ @channel ~~~",+ "run `npm i @here/sdk`",+ ],+)+def test_mattermost_defuses_the_words_even_in_code_and_links(body: str) -> None:+ # On Mattermost the text is the only guard, and telling code from prose+ # the way its Markdown does is a near miss away from paging the room. An+ # invisible character in a pasted command is the cheaper failure.+ rendered = _mattermost().translate_outbound(body)+ assert f"@{ZWSP}" in rendered+ for word in ("channel", "here"):+ assert f"@{word}" not in rendered+++ ("body", "expected"),+ [+ ("run `npm i @here/sdk`", "run <code>npm i @here/sdk</code>"),+ ("```\nnpm i @here/sdk\n```", "<pre>npm i @here/sdk</pre>"),+ ],+)+def test_telegram_code_keeps_its_text_exactly(body: str, expected: str) -> None:+ # Telegram's code is already HTML by the time it is defused, so the base+ # rule's backtick check cannot see it; the adapter's own override does.+ assert _telegram().translate_outbound(body) == expected+++ "body",+ [+ "<!channel>",+ "<!here>",+ "<!everyone>",+ "<!channel|channel>",+ "<!group>",+ # The Markdown translation writes Slack syntax itself: a link to+ # `!channel` comes out of it as `<!channel|x>`.+ "[x](!channel)",+ ],+)+def test_slacks_own_syntax_cannot_page_the_channel(body: str) -> None:+ rendered = _slack().translate_outbound(body)+ assert "<!" not in rendered+ assert "<!" in rendered+++def test_slacks_own_mentions_still_resolve() -> None:+ adapter = _slack()+ adapter.prime_mention_targets({"doe.jane": "U123"})+ assert adapter.translate_outbound("@doe.jane look") == "<@U123> look"++[email protected]("platform", ADAPTERS)+def test_the_defusal_is_not_an_adapters_to_forget(platform: str) -> None:+ # An adapter renders in `_render_outbound`; `translate_outbound` is the+ # base class's, final, and defuses whatever comes back.+ assert "translate_outbound" not in type(ADAPTERS[platform]()).__dict__+ assert getattr(CollaborationAdapter.translate_outbound, "__final__", False)+++# ── The relay ────────────────────────────────────────────────────────────────+++class _Recording:+ """An adapter that records what the relay asked it to send."""++ def __init__(self, platform: CollaborationAdapter) -> None:+ self._platform = platform+ self.sent: list[dict[str, Any]] = []++ def translate_outbound(self, content: str) -> str:+ return self._platform.translate_outbound(content)++ def render_room_wide_mention(self, body: str) -> str:+ return self._platform.render_room_wide_mention(body)++ async def send_message(+ self,+ channel_id: str,+ sender_name: str,+ content: str,+ thread_root_id: str | None = None,+ *,+ room_wide_mention: bool = False,+ ) -> str | None:+ self.sent.append({"content": content, "room_wide_mention": room_wide_mention})+ return "ref"+++async def _noop(*_args: Any, **_kwargs: Any) -> None:+ return None+++async def _tenant(*_args: Any, **_kwargs: Any) -> str:+ return "tenant-1"+++def _bridge(adapter: _Recording) -> BridgeCore:+ core = object.__new__(BridgeCore)+ core._bridge_type = "slack" # type: ignore[attr-defined]+ core._adapter = adapter # type: ignore[assignment]+ core._puppet_matrix_ids = set() # type: ignore[assignment]+ core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]+ core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]+ core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]+ core._room_tenant = _tenant # type: ignore[assignment]+ core._record_message_map = _noop # type: ignore[assignment]+ core._move_indicator_for_sender = _noop # type: ignore[assignment]+ core._outbound_thread_root_ref = _noop # type: ignore[assignment]+ return core+++def _event(body: str, content: dict[str, Any]) -> InboundMessage:+ return InboundMessage(+ room_id="!r:switch.local",+ event_id="$e1",+ sender="@switch-agent-scout:switch.local",+ timestamp=1700000000000,+ content={"body": body, **content},+ body=body,+ sender_name="scout",+ )+++async def test_the_relay_pages_the_channel_for_a_marked_message() -> None:+ adapter = _Recording(_slack())++ await _bridge(adapter).handle_outbound_message(+ RoomRef("!r:switch.local"),+ _event("@everyone deploy at five", room_wide_mention_content()),+ )++ assert adapter.sent == [+ {"content": "<!channel> deploy at five", "room_wide_mention": True}+ ]+++async def test_the_relay_does_not_page_for_the_same_text_unmarked() -> None:+ # An agent that writes `@everyone` itself, rather than targeting it, has+ # sent an ordinary message.+ adapter = _Recording(_slack())++ await _bridge(adapter).handle_outbound_message(+ RoomRef("!r:switch.local"), _event("@everyone deploy at five", {})+ )++ assert adapter.sent == [+ {"content": f"@{ZWSP}everyone deploy at five", "room_wide_mention": False}+ ]diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 67e2f684a..86fbdb5c6 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asynciofrom typing import Any+import pytestfrom slack_sdk.errors import SlackApiErrorfrom switch_core.bridges.collaboration.models import InboundCommand, InboundMessage@@ -539,6 +540,24 @@ def test_send_message_top_level_has_no_thread_ts() -> None:assert fake.calls[0]["thread_ts"] is None+def test_a_room_wide_mention_in_a_group_dm_is_not_auto_threaded() -> None:+ # A group DM threads an agent's reply under the last person's message,+ # and Slack sends no channel-wide alert from a thread.+ adapter = _adapter()+ fake = _FakeWebClient()+ adapter._web_client = fake # type: ignore[assignment]+ adapter._channel_type_cache["G1"] = "mpim"+ adapter._last_user_message_ts["G1"] = "100.1"++ _run(+ adapter.send_message("G1", "agent-bot", "<!channel> hi", room_wide_mention=True)+ )+ _run(adapter.send_message("G1", "agent-bot", "hi"))++ assert fake.calls[0]["thread_ts"] is None+ assert fake.calls[1]["thread_ts"] == "100.1"++# ── Thinking indicator threading ─────────────────────────────────────────────@@ -933,6 +952,29 @@ def test_translate_inbound_unknown_piped_mention_falls_back_to_id() -> None:assert adapter.translate_inbound("<@U0B1BF0JP6H|agent switch>") == "@U0B1BF0JP6H"+ ("raw", "expected"),+ [+ ("<!channel> deploy at five", "@channel deploy at five"),+ ("<!here> anyone?", "@here anyone?"),+ ("<!everyone> heads up", "@everyone heads up"),+ ("<!channel|@channel> labelled", "@channel labelled"),+ ("<!here|here> labelled", "@here labelled"),+ ("<!group> legacy private channel", "@channel legacy private channel"),+ ("<!CHANNEL> any case", "@channel any case"),+ ],+)+def test_translate_inbound_shows_a_channel_wide_mention_as_the_word(+ raw: str, expected: str+) -> None:+ assert _adapter().translate_inbound(raw) == expected+++def test_translate_inbound_leaves_a_user_group_to_its_own_rule() -> None:+ # `<!subteam^…>` shares the `<!` prefix and must not be read as a page.+ assert _adapter().translate_inbound("<!subteam^S123|@ops> hi") == "@ops hi"++def test_slash_command_without_channel_is_ignored() -> None:adapter = _adapter()commands = _capture_commands(adapter)diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_admin_client.pyindex a345d12f9..3bf69d0ba 100644--- a/core/tests/switch_core/clients/test_admin_client.py+++ b/core/tests/switch_core/clients/test_admin_client.py@@ -255,6 +255,18 @@ class TestAdminAbsentAgentWarning:await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)assert sent == []+ async def test_room_wide_mention_word_skipped(self) -> None:+ # `@everyone` pages the room's people. An agent registered under the+ # name before it was reserved is not who it was aimed at, and telling+ # the room that agent is absent would be a warning about nothing.+ agents = {+ "everyone": SimpleNamespace(id="a-old", name="everyone", display_name=None)+ }+ client, sent = _admin_client(agents_by_name=agents)+ event = _event("@everyone the deploy is at five")+ await AdminClient._warn_absent_agents(client, _room(), event, "room-1", None)+ assert sent == []+async def test_role_token_skipped(self) -> None:# A tagged role is left to _warn_unreachable_roles, not double-flagged.roles = [SimpleNamespace(id="r-mgr", name="manager")]diff --git a/core/tests/switch_core/test_room_wide_mention.py b/core/tests/switch_core/test_room_wide_mention.pynew file mode 100644index 000000000..92c3d7e8d--- /dev/null+++ b/core/tests/switch_core/test_room_wide_mention.py@@ -0,0 +1,201 @@+"""The room-wide mention words: defused in text, reserved as names.++Whether a room-wide mention wakes an agent is pinned end to end in+`test_room_wide_mention_wakes_no_agent.py`, and how each platform renders one+in `bridges/collaboration/test_room_wide_mention_rendering.py`. This covers+the pieces both rest on.+"""++from __future__ import annotations++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.aliases import AliasError, validate_alias_format+from switch_core.db.models import Agent, ApiKey, Room+from switch_core.db.stores.room_role_store import RoomRoleStore, validate_role_name+from switch_core.room_service import RoomCreateConfig, RoomService+from switch_core.room_wide_mention import (+ CODE_AND_URLS,+ defuse_mass_mention_words,+ defuse_mass_mention_words_in_prose,+ reject_reserved_mention_name,+ strip_room_wide_target,+)+from tests.switch_core.bridges.agent.protocol.registration_harness import (+ make_owner,+ make_service,+ register,+)++ZWSP = "\u200b"+RESERVED = ["everyone", "channel", "here", "all", "Everyone", "CHANNEL"]+++# ── Defusing ─────────────────────────────────────────────────────────────────+++ ("text", "expected"),+ [+ ("@channel hi", f"@{ZWSP}channel hi"),+ ("@everyone, look", f"@{ZWSP}everyone, look"),+ ("@Here", f"@{ZWSP}Here"),+ # Mattermost strips trailing `.`, `-` and `_` before matching, so+ # `@channel.` pages the channel just as `@channel` does.+ ("ping @all.", f"ping @{ZWSP}all."),+ ("ping @channel-", f"ping @{ZWSP}channel-"),+ # Strict means everywhere: each of these pages a Mattermost channel,+ # and each got past an exemption that tried to recognise code or a+ # link the way Markdown does.+ ("[docs](https://x.com),@channel", f"[docs](https://x.com),@{ZWSP}channel"),+ ("\\`@channel\\`", f"\\`@{ZWSP}channel\\`"),+ ("x ~~~ @channel ~~~", f"x ~~~ @{ZWSP}channel ~~~"),+ ("`@here`", f"`@{ZWSP}here`"),+ ],+)+def test_the_strict_form_defuses_the_words_everywhere(text: str, expected: str) -> None:+ assert defuse_mass_mention_words(text) == expected+++ "text", ["@allison", "@all-hands", "@everyone2", "@channels", "no mention here"]+)+def test_longer_handles_are_never_touched(text: str) -> None:+ assert defuse_mass_mention_words(text) == text+ assert defuse_mass_mention_words_in_prose(text, keep=CODE_AND_URLS) == text+++ "text",+ [+ "`@here`",+ "```\n@all\n```",+ "~~~\nnpm i @here/sdk\n~~~",+ "https://www.npmjs.com/package/@here/harp.gl",+ "[profile](https://mastodon.social/@all)",+ "ops@here",+ "[email protected]",+ ],+)+def test_the_prose_form_leaves_code_links_and_addresses_exact(text: str) -> None:+ assert defuse_mass_mention_words_in_prose(text, keep=CODE_AND_URLS) == text+++ ("text", "expected"),+ [+ ("ping @here, please", f"ping @{ZWSP}here, please"),+ ("see https://x.io then @here", f"see https://x.io then @{ZWSP}here"),+ # Not a URL: a host starts with a letter or digit.+ ("http://@channel", f"http://@{ZWSP}channel"),+ ],+)+def test_the_prose_form_still_defuses_prose(text: str, expected: str) -> None:+ assert defuse_mass_mention_words_in_prose(text, keep=CODE_AND_URLS) == expected+++def test_defusing_is_idempotent() -> None:+ once = defuse_mass_mention_words("@channel and @here")+ assert defuse_mass_mention_words(once) == once+++ ("body", "rest"),+ [+ ("@everyone deploy at five", "deploy at five"),+ ("@everyone @scout take this", "@scout take this"),+ ("@everyone", ""),+ # Only the leading token the server wrote is taken.+ ("@everyones deploy", "@everyones deploy"),+ ("deploy @everyone", "deploy @everyone"),+ ],+)+def test_the_leading_target_is_taken_off(body: str, rest: str) -> None:+ assert strip_room_wide_target(body) == rest+++# ── Reserving ────────────────────────────────────────────────────────────────++[email protected]("name", RESERVED)+def test_reserved_names_are_refused(name: str) -> None:+ with pytest.raises(ValueError, match="reserved for room-wide mentions"):+ reject_reserved_mention_name(name, kind="Name")++[email protected]("name", RESERVED)+def test_an_alias_cannot_be_a_room_wide_mention_word(name: str) -> None:+ with pytest.raises(AliasError, match="reserved"):+ validate_alias_format(name)++[email protected]("name", RESERVED)+def test_a_role_cannot_be_a_room_wide_mention_word(name: str) -> None:+ with pytest.raises(ValueError, match="reserved"):+ validate_role_name(name)++[email protected]("name", ["allison", "channels", "everyone2", "here-we-go"])+def test_names_that_only_start_with_one_are_fine(name: str) -> None:+ validate_alias_format(name)+ validate_role_name(name)+ reject_reserved_mention_name(name, kind="Name")+++async def test_define_role_refuses_a_reserved_name(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with session_factory() as session:+ room = Room(matrix_room_id="!r:test", name="r", description="r")+ session.add(room)+ await session.flush()+ with pytest.raises(ValueError, match="reserved"):+ await RoomRoleStore().define_role(session, room.id, "here", "x", False)+++async def test_create_room_refuses_a_reserved_alias_before_provisioning() -> None:+ # A bare service: had the check come after anything touched a store, a+ # bridge or the transport, this would fail on the missing attribute+ # instead, having left a channel and a room behind in real life.+ svc = object.__new__(RoomService)+ config = RoomCreateConfig(+ name="r", description="r", agent_names=["bot"], aliases={"bot": "here"}+ )++ with pytest.raises(AliasError, match="reserved"):+ await svc.create_room(config)+++class TestAgentNames:+ async def test_a_new_agent_cannot_take_a_reserved_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ svc = make_service(session_factory)+ owner = await make_owner(session_factory)++ with pytest.raises(ValueError, match="reserved"):+ await register(svc, "everyone", owner)++ async def test_an_agent_that_already_has_one_still_reconnects(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Refusing it would disconnect something running today. A room-wide+ # mention in a room it belongs to is refused instead.+ svc = make_service(session_factory)+ owner = await make_owner(session_factory)+ await register(svc, "legacy", owner)+ async with session_factory() as session:+ agent = (+ await session.execute(select(Agent).where(Agent.name == "legacy"))+ ).scalar_one()+ agent.name = "all"+ key = await session.get(ApiKey, agent.api_key_id)+ assert key is not None+ key.label = "all"+ await session.commit()++ agent_id = await register(svc, "all", owner, overwrite=True)++ assert agent_id == agent.iddiff --git a/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.pynew file mode 100644index 000000000..2ba7ac778--- /dev/null+++ b/core/tests/switch_core/test_room_wide_mention_wakes_no_agent.py@@ -0,0 +1,324 @@+"""A room-wide mention pages the room's people and wakes no agent.++This is the promise the feature exists to keep, so it is tested end to end+against a real database rather than stubbed stores: the message is produced by+`ProtocolService.send_targeted_message`, carried in the content the transport+would store, and judged by `AddressingResolver.addresses` — the one decision+the agent client turns into `MessagePayload.addressed`, which is what the event+buffer's `is_notifiable` delivers on. Every way an agent can be addressed is+live in the room: a plain name, a room alias and a live-held role.++The control case matters as much as the claim. It sends through the same+harness to the same agents by name, alias and role and watches them wake, so a+harness that could never see a wake cannot pass the claim by accident.+"""++from __future__ import annotations++from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.types import (+ AgentStatus,+ RoomWideMentionStatus,+)+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+from switch_core.db.models import Agent, ApiKey, Client, Room, RoomRole, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.delivery.addressing import AddressingResolver, IncomingMessage+from switch_core.room_wide_mention import ROOM_WIDE_MENTION_MARKER+from switch_core.transport.content import message_content+++async def _make_agent(session: AsyncSession, name: str) -> Agent:+ user = User(+ name=f"owner-{name}", email=f"{name}@test", role="user", password_hash="x"+ )+ session.add(user)+ await session.flush()+ api_key = ApiKey(+ user_id=user.id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")+ session.add_all([api_key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description=f"{name} desc",+ agent_type="always_on",+ connector_type="claude_code",+ integration_profile={"connection_model": "always_on"},+ client_id=client.id,+ api_key_id=api_key.id,+ )+ session.add(agent)+ await session.flush()+ return agent+++@dataclass+class _Room:+ """A room holding one agent reachable each way addressing allows."""++ id: str+ sender: Agent+ # Addressed by its name.+ scout: Agent+ # Addressed by its room alias, `bob`.+ builder: Agent+ # Addressed by the role it live-holds, `lead`.+ reviewer: Agent++ @property+ def listeners(self) -> list[Agent]:+ return [self.scout, self.builder, self.reviewer]+++async def room(session_factory: async_sessionmaker[AsyncSession]) -> _Room:+ room_store, role_store = RoomStore(), RoomRoleStore()+ async with session_factory() as session:+ row = Room(matrix_room_id="!wide:test", name="wide", description="wide")+ session.add(row)+ await session.flush()+ agents = [+ await _make_agent(session, name)+ for name in ("sender", "scout", "builder", "reviewer")+ ]+ await room_store.add_agents(session, row.id, [a.id for a in agents])+ sender, scout, builder, reviewer = agents+ await room_store.set_alias(session, row.id, builder.id, "bob")+ lead = await role_store.define_role(session, row.id, "lead", "lead", True)+ await role_store.acquire_lease(session, lead, reviewer.id, None, None, ())+ await session.commit()+ return _Room(row.id, sender, scout, builder, reviewer)+++@dataclass+class _Sent:+ body: str+ extra_content: dict[str, object] | None+++def _service(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> tuple[ProtocolService, list[_Sent]]:+ """The real `send_targeted_message`, over real stores.++ Only the two edges that leave the process are replaced: the participant+ roster (a projection of the same rows) and the send itself, which records+ what would have gone onto the bus.+ """+ sent: list[_Sent] = []+ svc = object.__new__(ProtocolService)+ svc.connections = ConnectionRegistry()+ svc.session_factory = session_factory+ svc.room_store = RoomStore()+ svc.room_role_store = RoomRoleStore()+ svc.agent_store = AgentStore()+ svc.collab_lifecycle = SimpleNamespace(get=lambda _bridge_id: None) # type: ignore[assignment]++ async def _participants(_room_id: str) -> list[Any]:+ return [+ SimpleNamespace(id=a.id, name=a.name, type="agent", status=AgentStatus.LIVE)+ for a in [room.sender, *room.listeners]+ ]++ async def _send_message(+ _agent_id: str,+ _room_id: str,+ body: str,+ thread_id: str | None = None,+ *,+ extra_content: dict[str, object] | None = None,+ ) -> str:+ sent.append(_Sent(body, extra_content))+ return f"evt-{len(sent)}"++ svc.list_participants = _participants # type: ignore[assignment]+ svc.send_message = _send_message # type: ignore[assignment]+ return svc, sent+++def _as_received(sent: _Sent, sender: Agent) -> IncomingMessage:+ """The message as an agent client reads it off the bus."""+ content = message_content(+ sent.body, sender_name=sender.name, extra_content=sent.extra_content+ )+ return IncomingMessage(+ sender=f"@{sender.name}:test", body=sent.body, content=content+ )+++async def _woken(+ session_factory: async_sessionmaker[AsyncSession],+ room: _Room,+ message: IncomingMessage,+) -> set[str]:+ resolver = AddressingResolver(+ room_store=RoomStore(),+ room_role_store=RoomRoleStore(),+ client_store=ClientStore(),+ agent_store=AgentStore(),+ external_user_store=ExternalUserStore(),+ live_connection_ids=set,+ )+ woken: set[str] = set()+ async with session_factory() as session:+ for agent in room.listeners:+ if await resolver.addresses(+ session,+ agent=agent,+ agent_matrix_id=f"@{agent.name}:test",+ room_id=room.id,+ channel_type="channel_public",+ message=message,+ ):+ woken.add(agent.name)+ return woken+++async def test_a_room_wide_mention_wakes_no_agent(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> None:+ svc, sent = _service(session_factory, room)++ result = await svc.send_targeted_message(+ room.sender.id, room.id, ["everyone"], "the deploy is at five"+ )++ assert [s.body for s in sent] == ["@everyone the deploy is at five"]+ assert sent[0].extra_content == {ROOM_WIDE_MENTION_MARKER: {}}+ assert (+ await _woken(session_factory, room, _as_received(sent[0], room.sender)) == set()+ )+ # An unbridged room has nobody on a platform to page, and says so.+ assert result.target_statuses == {"everyone": RoomWideMentionStatus.NO_BRIDGE}+++async def test_the_same_harness_sees_agents_it_addresses_wake(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> None:+ svc, sent = _service(session_factory, room)++ await svc.send_targeted_message(+ room.sender.id, room.id, ["scout", "bob"], "over to you", target_roles=["lead"]+ )++ assert await _woken(session_factory, room, _as_received(sent[0], room.sender)) == {+ "scout",+ "builder",+ "reviewer",+ }+++async def test_a_room_wide_mention_still_addresses_who_it_names(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> None:+ svc, sent = _service(session_factory, room)++ await svc.send_targeted_message(+ room.sender.id, room.id, ["scout", "everyone"], "scout, take this"+ )++ assert sent[0].body == "@everyone @scout scout, take this"+ assert await _woken(session_factory, room, _as_received(sent[0], room.sender)) == {+ "scout"+ }+++def _from_a_person(body: str) -> IncomingMessage:+ """A person's message from Slack, as the bridge puts it on the bus."""+ text = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test", app_token="xapp-test", workspace_id="T123"+ )+ ).translate_inbound(body)+ return IncomingMessage(+ sender="@person:test",+ body=text,+ content=message_content(text, sender_name="person", extra_content=None),+ )+++async def test_a_persons_own_page_wakes_no_agent(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> None:+ message = _from_a_person("<!channel> <!here> <!everyone> deploy at five")++ assert message.body == "@channel @here @everyone deploy at five"+ assert await _woken(session_factory, room, message) == set()+++async def test_the_same_harness_sees_a_person_wake_an_agent(+ session_factory: async_sessionmaker[AsyncSession], room: _Room+) -> None:+ message = _from_a_person("@scout <!channel> over to you")++ assert await _woken(session_factory, room, message) == {"scout"}+++class TestSomethingAlreadyAnswersToEveryone:+ """A row made before the name was reserved would be woken, so the send is+ refused and nothing reaches the room."""++ async def test_an_alias(+ self, session_factory: async_sessionmaker[AsyncSession], room: _Room+ ) -> None:+ async with session_factory() as session:+ # Straight to the store, the way a row from before the+ # reservation got there: `validate_alias_format` now refuses it.+ await RoomStore().set_alias(session, room.id, room.scout.id, "Everyone")+ await session.commit()+ svc, sent = _service(session_factory, room)++ with pytest.raises(ValueError, match="alias 'Everyone'"):+ await svc.send_targeted_message(room.sender.id, room.id, ["everyone"], "hi")+ assert sent == []++ async def test_a_role(+ self, session_factory: async_sessionmaker[AsyncSession], room: _Room+ ) -> None:+ async with session_factory() as session:+ session.add(+ RoomRole(+ room_id=room.id, name="everyone", instructions="x", exclusive=False+ )+ )+ await session.commit()+ svc, sent = _service(session_factory, room)++ with pytest.raises(ValueError, match="role 'everyone'"):+ await svc.send_targeted_message(room.sender.id, room.id, ["everyone"], "hi")+ assert sent == []++ async def test_an_agent(+ self, session_factory: async_sessionmaker[AsyncSession], room: _Room+ ) -> None:+ async with session_factory() as session:+ legacy = await _make_agent(session, "everyone")+ await RoomStore().add_agents(session, room.id, [legacy.id])+ await session.commit()+ room.scout = legacy+ svc, sent = _service(session_factory, room)++ with pytest.raises(ValueError, match="agent 'everyone'"):+ await svc.send_targeted_message(room.sender.id, room.id, ["everyone"], "hi")+ assert sent == []