Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(chats): name people in a message without waking agents

raullopez-sandbox24126a97c023
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 1122990bf..ac0d44b27 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -88,7 +88,7 @@ from switch_core.db.stores.session_activity_store import (
)
from switch_core.db.stores.usage_store import UsageStore
from switch_core.db.stores.user_store import UserStore
-from switch_core.delivery.addressing import AddressingResolver
+from switch_core.delivery.addressing import MENTIONS_KEY, AddressingResolver
from switch_core.messages.notify import MessageListener
from switch_core.messages.row import attachments_in, message_row, new_event_id
from switch_core.observability.catalogue import MESSAGES_SENT
@@ -1383,6 +1383,7 @@ class ChatService:
upload_ids: list[str],
mention_agent_id: str | None,
mention_agent_ids: list[str],
+ mention_user_ids: list[str],
) -> tuple[Room, list[Message]]:
"""Post the user's message, every part of it in one transaction.
@@ -1392,9 +1393,11 @@ class ChatService:
posts it once; one after the commit answers the parts already posted.
The agents the message is for are `mention_agent_ids` together with
- `mention_agent_id`, the one earlier clients send, as a set.
+ `mention_agent_id`, the one earlier clients send, as a set. The people
+ it names, `mention_user_ids`, address no agent (`MENTIONS_KEY`).
"""
mentions = sorted(set(mention_agent_ids))
+ people = sorted(set(mention_user_ids))
request: dict[str, object] = {
"roomId": room_id,
"body": body,
@@ -1404,6 +1407,8 @@ class ChatService:
}
if mentions:
request["mentionAgentIds"] = mentions
+ if people:
+ request["mentionUserIds"] = people
payload_hash = _hash(request)
if mention_agent_id is not None:
mentions = sorted({*mentions, mention_agent_id})
@@ -1423,6 +1428,7 @@ class ChatService:
root = await self._thread_root(session, room, thread_root_id)
if mentions:
body = await self._with_mentions(session, room, mentions, body)
+ named_people = await self._named_people(session, room, people, mentions)
if not await self._claim(
session,
@@ -1451,6 +1457,8 @@ class ChatService:
)
),
)
+ if named_people is not None:
+ contents[0][MENTIONS_KEY] = named_people
posted: list[Message] = []
routed: list[Routed] = []
for index, content in enumerate(contents):
@@ -1676,6 +1684,50 @@ class ChatService:
)
return found[0].thread_root_event_id or found[0].transport_event_id
+ async def _named_people(
+ self,
+ session: AsyncSession,
+ room: Room,
+ user_ids: list[str],
+ agent_ids: list[str],
+ ) -> dict[str, list[str]] | None:
+ """What a send records of the people it names (`MENTIONS_KEY`): their
+ ids, and the names whose `@` spans address no agent. A name an agent
+ named in the same send also answers to stays the agent's."""
+ if not user_ids:
+ return None
+ names: dict[str, str] = {
+ user_id: name
+ for user_id, name in (
+ await session.execute(
+ select(User.id, User.name)
+ .join(Client, Client.user_id == User.id)
+ .join(ClientRoom, ClientRoom.client_id == Client.id)
+ .where(
+ ClientRoom.room_id == room.id,
+ Client.type == MEMBER_CLIENT_TYPE,
+ User.id.in_(user_ids),
+ )
+ )
+ ).all()
+ }
+ if len(names) != len(user_ids):
+ raise ChatError(422, "USER_NOT_IN_CHAT", "That person is not in this chat.")
+ aliases = await self._room_store.list_aliases(session, room.id)
+ spoken: set[str] = set()
+ for agent_id in agent_ids:
+ agent = await self._agent_store.get(session, agent_id)
+ assert agent is not None
+ spoken.add(agent.name.lower())
+ if agent_id in aliases:
+ spoken.add(aliases[agent_id].lower())
+ return {
+ "user_ids": user_ids,
+ "person_names": sorted(
+ {name for name in names.values() if name.lower() not in spoken}
+ ),
+ }
+
async def _with_mentions(
self, session: AsyncSession, room: Room, agent_ids: list[str], body: str
) -> str:
diff --git a/core/switch_core/chats/views.py b/core/switch_core/chats/views.py
index 555821783..d00a0dbe4 100644
--- a/core/switch_core/chats/views.py
+++ b/core/switch_core/chats/views.py
@@ -28,7 +28,11 @@ from switch_core.db.models import (
room_agents,
)
from switch_core.db.stores.message_store import MessageStore
-from switch_core.delivery.addressing import named_agents
+from switch_core.delivery.addressing import (
+ MENTIONS_KEY,
+ addressable_text,
+ named_agents,
+)
MESSAGE_EVENT_TYPE = "m.room.message"
COMMAND_EVENT_TYPE = "com.switch.command"
@@ -128,6 +132,8 @@ class ChatMessage(CamelModel):
# The room's agents the body names by @name or @alias. Display only: who
# a message addresses is each agent's own decision.
named_agent_ids: list[str]
+ # The people the sender named (`mentionUserIds`); they address no agent.
+ named_user_ids: list[str]
# Of a thread's root; 0 and None on a reply and on a message with none.
thread_reply_count: int
thread_last_reply_seq: int | None
@@ -354,9 +360,21 @@ async def chat_messages(
for attachment in attachments.get(message.id, [])
],
client_txn=message.client_txn_id,
- named_agent_ids=named_agents(names, aliases, message.body or ""),
+ named_agent_ids=named_agents(
+ names,
+ aliases,
+ addressable_text(message.body or "", message.content),
+ ),
+ named_user_ids=_named_user_ids(message),
thread_reply_count=thread[0] if thread is not None else 0,
thread_last_reply_seq=thread[1] if thread is not None else None,
)
)
return out
+
+
+def _named_user_ids(message: Message) -> list[str]:
+ mentions = message.content.get(MENTIONS_KEY)
+ if not isinstance(mentions, dict):
+ return []
+ return [each for each in mentions.get("user_ids") or [] if isinstance(each, str)]
diff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.py
index 4214e0501..1eaf2946c 100644
--- a/core/switch_core/delivery/addressing.py
+++ b/core/switch_core/delivery/addressing.py
@@ -115,6 +115,29 @@ class IncomingMessage:
formatted_body: str | None = None
content: dict = field(default_factory=dict)
+ @property
+ def addressable_body(self) -> str:
+ return addressable_text(self.body, self.content)
+
+
+# Written by a Switch Console send: the people it names (`user_ids`), and the
+# `@name` spans that name them (`person_names`), which no agent's name, alias
+# or role may then match. A person sharing an agent's name would otherwise
+# wake the agent; the content can only take addressing away, never add it.
+MENTIONS_KEY = "com.switch.mentions"
+
+
+def addressable_text(body: str, content: Mapping[str, object]) -> str:
+ """`body` less the `@name` spans that name people (`MENTIONS_KEY`)."""
+ text = strip_emphasis(body)
+ mentions = content.get(MENTIONS_KEY)
+ if not isinstance(mentions, dict):
+ return text
+ for name in mentions.get("person_names") or []:
+ if isinstance(name, str) and name:
+ text = mention_regex(name).sub("", text)
+ return text
+
class AddressingDecision(NamedTuple):
"""Whether a sender may address an agent, and what to say if not."""
@@ -189,7 +212,7 @@ class AddressingResolver:
return True
if channel_type == "direct":
return None
- if "@" not in message.body:
+ if "@" not in message.addressable_body:
return False
return None
@@ -260,9 +283,7 @@ class AddressingResolver:
"""
if message.formatted_body and agent_user_id in message.formatted_body:
return True
- return (
- mention_regex(agent.name).search(strip_emphasis(message.body)) is not None
- )
+ return mention_regex(agent.name).search(message.addressable_body) is not None
async def mentions_alias(
self,
@@ -278,12 +299,12 @@ class AddressingResolver:
live, so a change takes effect on the next message with no per-client
cache to invalidate.
"""
- if "@" not in message.body:
+ if "@" not in message.addressable_body:
return False
alias = await self.alias_of(session, room_id, agent.id)
if not alias:
return False
- return mention_regex(alias).search(message.body) is not None
+ return mention_regex(alias).search(message.addressable_body) is not None
async def mentions_role(
self,
@@ -303,12 +324,12 @@ class AddressingResolver:
room still matches, because liveness follows the holder rather than
the room it is attending.
"""
- if "@" not in message.body:
+ if "@" not in message.addressable_body:
return False
role_name = await self.role_of(session, room_id, agent.id)
if not role_name:
return False
- return mention_regex(role_name).search(strip_emphasis(message.body)) is not None
+ return mention_regex(role_name).search(message.addressable_body) is not None
# ── What the rules read ───────────────────────────────────────────────────
#
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index f3dfe12e5..ffc2bf2e7 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -132,6 +132,7 @@ class SendRequest(CamelModel):
upload_ids: list[str] = []
mention_agent_id: str | None = None
mention_agent_ids: list[str] = []
+ mention_user_ids: list[str] = []
class ControlRequest(CamelModel):
@@ -439,6 +440,7 @@ async def send_message(
upload_ids=req.upload_ids,
mention_agent_id=req.mention_agent_id,
mention_agent_ids=req.mention_agent_ids,
+ mention_user_ids=req.mention_user_ids,
)
async with tenant_session(service.session_factory, tenant_id) as session:
return SentMessages(messages=await chat_messages(session, room, posted))
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index abb7ef909..835cf5360 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -824,3 +824,64 @@ async def test_reading_re_sends_the_readers_summary(chats: _Harness) -> None:
name, summary = await events.next()
assert (name, summary["unreadCount"]) == ("chat", 0)
await events.stream.aclose() # type: ignore[attr-defined]
+
+
+# ── People mentions and leaving ──────────────────────────────────────────────
+
+
+async def test_naming_a_person_wakes_no_agent_even_one_of_the_same_name(
+ chats: _Harness,
+) -> None:
+ namesake = await chats.agent("bob", owner=chats.alice)
+ created = await chats.client.post(
+ "/chats",
+ json={
+ "agentIds": [namesake.id],
+ "memberUserIds": [chats.bob.id],
+ "requestId": "c1",
+ },
+ headers=chats.as_user(chats.alice),
+ )
+ room_id = created.json()["chat"]["roomId"]
+
+ person = await chats.send(
+ chats.alice, room_id, "s1", "@bob can you look?", mentionUserIds=[chats.bob.id]
+ )
+ assert person.status_code == 200, person.text
+ [message] = person.json()["messages"]
+ assert message["namedUserIds"] == [chats.bob.id]
+ assert message["namedAgentIds"] == []
+ assert (room_id, message["seq"]) not in await _events_of(chats, namesake)
+
+ both = await chats.send(
+ chats.alice,
+ room_id,
+ "s2",
+ "@bob and you too",
+ mentionUserIds=[chats.bob.id],
+ mentionAgentIds=[namesake.id],
+ )
+ [message] = both.json()["messages"]
+ assert message["namedAgentIds"] == [namesake.id]
+ assert (room_id, message["seq"]) in await _events_of(chats, namesake)
+
+ typed = (await chats.send(chats.alice, room_id, "s3", "@bob typed")).json()
+ assert (room_id, typed["messages"][0]["seq"]) in await _events_of(chats, namesake)
+
+ stranger = await chats.send(
+ chats.alice, room_id, "s4", "@admin hi", mentionUserIds=[chats.admin.id]
+ )
+ assert stranger.status_code == 422
+ assert _code(stranger) == "USER_NOT_IN_CHAT"
+
+
+async def test_an_ordinary_member_leaves_without_managing(chats: _Harness) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+
+ left = await chats.client.delete(
+ f"/chats/{room_id}/members/{chats.bob.id}", headers=chats.as_user(chats.bob)
+ )
+ assert left.status_code == 204
+ assert await _reads(chats, chats.bob, room_id) == 403