Skip to content

The agent that grows with you

feat(gateway): route inbound messages to profiles by sender user_id

Italo Fernandesd6f3285b81ad
diff --git a/gateway/kanban_watchers_notifier.py b/gateway/kanban_watchers_notifier.py
index 8a72fa8a499..caa1a917803 100644
--- a/gateway/kanban_watchers_notifier.py
+++ b/gateway/kanban_watchers_notifier.py
@@ -153,6 +153,7 @@ def _adapter_for_subscription(runner: Any, platform: Any, sub: dict, owner_profi
guild = metadata.get("scope_id") or metadata.get("guild_id")
parent = metadata.get("parent_chat_id")
chat, thread = sub.get("chat_id"), sub.get("thread_id") or None
+ user_id = sub.get("user_id") or None
thread_like = bool(thread) or (sub.get("chat_type") or metadata.get("chat_type")) in {
"thread", "forum", "forum_post", "forum-post", "topic",
}
@@ -162,14 +163,15 @@ def _adapter_for_subscription(runner: Any, platform: Any, sub: dict, owner_profi
# hand-maintained equality implementation.
for route in getattr(config, "profile_routes", None) or []:
if route.matches(platform.value, guild_id=guild, chat_id=chat,
- thread_id=thread, parent_chat_id=parent):
+ thread_id=thread, parent_chat_id=parent, user_id=user_id):
if route.profile != profile:
return None
from gateway.run import _multiplex_profile_homes
served = {name for name, _home in _multiplex_profile_homes(config)}
return primary if profile in served else None
if route.matches(platform.value, guild_id=guild or route.guild_id, chat_id=chat,
- thread_id=thread, parent_chat_id=parent or (route.chat_id if thread_like else None)):
+ thread_id=thread, parent_chat_id=parent or (route.chat_id if thread_like else None),
+ user_id=user_id or route.user_id):
return None
# A stateless (api_server) subscription carries a RAW session id, not a routable chat, so no
# profile_routes entry can anchor it — and a platform-wide api_server route would deny the
diff --git a/gateway/profile_routing.py b/gateway/profile_routing.py
index 683a952f013..ecae7453fae 100644
--- a/gateway/profile_routing.py
+++ b/gateway/profile_routing.py
@@ -1,9 +1,9 @@
-"""Profile-based routing: route guilds/channels/threads to different profiles.
+"""Profile-based routing: route senders/locations to different profiles.
-Matching priority, most specific first (``gateway.profile_routes`` in config.yaml):
-platform + chat_id + thread_id (14) → platform + chat_id (6) → platform + guild_id (2)
-→ default profile. For Discord threads/forum posts ``parent_chat_id`` carries the
-direct parent, so a channel route also matches any thread/post under it.
+Matching is conjunctive; the highest additive specificity wins (``gateway.profile_routes``
+in config.yaml): user_id 16, thread_id 8, chat_id 4, guild_id 2, else the default profile.
+For Discord threads/forum posts ``parent_chat_id`` carries the direct parent, so a
+channel route also matches any thread/post under it.
A route applies only to messages received by the bot of its ``bot_profile`` (default: the
default profile's shared bot). Telegram DM ``chat_id == user_id`` for EVERY bot, so without
@@ -64,16 +64,17 @@ class ProfileRoute:
thread_id: Optional[str] = None
enabled: bool = True
bot_profile: Optional[str] = None # None = the default profile's bot
+ user_id: Optional[str] = None
@property
def specificity(self) -> int:
"""Higher value = more specific match."""
- return 2 * bool(self.guild_id) + 4 * bool(self.chat_id) + 8 * bool(self.thread_id)
+ return 2 * bool(self.guild_id) + 4 * bool(self.chat_id) + 8 * bool(self.thread_id) + 16 * bool(self.user_id)
def matches(
self, platform: str, guild_id: Optional[str] = None, chat_id: Optional[str] = None,
thread_id: Optional[str] = None, parent_chat_id: Optional[str] = None,
- adapter_profile: Optional[str] = None,
+ adapter_profile: Optional[str] = None, user_id: Optional[str] = None,
) -> bool:
"""True if every discriminator the route declares holds (AND).
@@ -86,6 +87,8 @@ class ProfileRoute:
return False
if _bot_profile_key(self.bot_profile) != _bot_profile_key(adapter_profile):
return False
+ if self.user_id is not None and (not str(self.user_id).strip() or self.user_id != user_id):
+ return False
if self.thread_id and self.thread_id != thread_id:
return False
if (
@@ -155,6 +158,7 @@ def parse_profile_routes(raw: Optional[List[Dict[str, Any]]]) -> List[ProfileRou
guild_id=_coerce_route_id(entry.get("guild_id")),
chat_id=_coerce_route_id(entry.get("chat_id")),
thread_id=_coerce_route_id(entry.get("thread_id")),
+ user_id=_coerce_route_id(entry.get("user_id")),
enabled=entry.get("enabled", True),
bot_profile=_bot_profile_key(entry.get("bot_profile")),
))
@@ -166,11 +170,12 @@ def parse_profile_routes(raw: Optional[List[Dict[str, Any]]]) -> List[ProfileRou
def match_profile_route(
routes: List[ProfileRoute], platform: str, guild_id: Optional[str] = None, chat_id: Optional[str] = None,
thread_id: Optional[str] = None, parent_chat_id: Optional[str] = None,
- adapter_profile: Optional[str] = None,
+ adapter_profile: Optional[str] = None, user_id: Optional[str] = None,
) -> Optional[ProfileRoute]:
"""Return the first (most specific) matching route, or None."""
for route in routes:
if route.matches(platform, guild_id=guild_id, chat_id=chat_id, thread_id=thread_id,
- parent_chat_id=parent_chat_id, adapter_profile=adapter_profile):
+ parent_chat_id=parent_chat_id, adapter_profile=adapter_profile,
+ user_id=user_id):
return route
return None
diff --git a/gateway/run.py b/gateway/run.py
index 080420bb5dd..c54ad476027 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4309,7 +4309,8 @@ class GatewayRunner(
matched = match_profile_route(
routes, platform=source.platform.value, guild_id=getattr(source, "guild_id", None),
chat_id=source.chat_id, thread_id=getattr(source, "thread_id", None),
- parent_chat_id=getattr(source, "parent_chat_id", None), adapter_profile=adapter_profile)
+ parent_chat_id=getattr(source, "parent_chat_id", None),
+ adapter_profile=adapter_profile, user_id=source.user_id)
except Exception:
logger.warning(
"Profile route matching failed for %s/%s, falling back to default",
@@ -4330,9 +4331,9 @@ class GatewayRunner(
raise ProfileRouteRejected(matched.name)
return matched.profile
logger.debug(
- "No profile route matched: platform=%s chat_id=%s thread_id=%s parent_chat_id=%s",
+ "No profile route matched: platform=%s chat_id=%s thread_id=%s parent_chat_id=%s user_id=%s",
source.platform.value, source.chat_id,
- getattr(source, "thread_id", None), getattr(source, "parent_chat_id", None))
+ getattr(source, "thread_id", None), getattr(source, "parent_chat_id", None), source.user_id)
return None
def _resolve_profile_home_for_source(self, source: SessionSource) -> "Path":
diff --git a/tests/gateway/test_kanban_routed_transport.py b/tests/gateway/test_kanban_routed_transport.py
index d80403480c4..b1ac43d5851 100644
--- a/tests/gateway/test_kanban_routed_transport.py
+++ b/tests/gateway/test_kanban_routed_transport.py
@@ -45,11 +45,12 @@ def setup_runner(tmp_path, monkeypatch):
return runner
-def completion(*, profile="yuki", metadata=None, chat="post", thread="post", mode="notify+wake"):
+def completion(*, profile="yuki", metadata=None, chat="post", thread="post",
+ user="creator", mode="notify+wake"):
with kbc.connect() as conn:
task = kb.create_task(conn, title="route completion", assignee="worker")
kbn.add_notify_sub(conn, task_id=task, platform="discord", chat_id=chat,
- thread_id=thread, chat_type="thread", user_id="creator",
+ thread_id=thread, chat_type="thread", user_id=user,
notifier_profile=profile, delivery_mode=mode,
delivery_metadata=metadata if metadata is not None else
{"guild_id": "guild", "scope_id": "guild", "parent_chat_id": "parent"})
@@ -99,6 +100,27 @@ def test_exact_routed_profile_delivers_once_on_its_authorized_transport(tmp_path
assert not unseen(task)
+def test_user_routed_subscription_uses_only_its_authorized_profile(tmp_path, monkeypatch):
+ runner = setup_runner(tmp_path, monkeypatch)
+ primary = runner.adapters[Platform.DISCORD]
+ runner.config.profile_routes = parse_profile_routes([
+ dict(platform="discord", user_id="creator", profile="yuki"),
+ ])
+
+ routed = completion(profile="yuki", chat="shared", thread="")
+ rows = collect(runner)
+ assert [row["task"].id for row in rows] == [routed]
+ asyncio.run(deliver(runner, rows))
+ assert len(primary.sent) == len(primary.handled) == 1
+ assert primary.handled[0].source.user_id == "creator"
+
+ # Same sender cannot fall through to the primary profile, and a legacy row
+ # without sender identity cannot skip a potentially winning user route.
+ completion(profile="default", chat="shared", thread="")
+ completion(profile="default", chat="shared", thread="", user=None)
+ assert not collect(runner)
+
+
def test_route_denials_leave_events_retryable_at_claim_and_send(tmp_path, monkeypatch):
runner = setup_runner(tmp_path, monkeypatch)
primary = runner.adapters[Platform.DISCORD]
diff --git a/tests/gateway/test_profile_routing.py b/tests/gateway/test_profile_routing.py
index 37ebb8f69ae..bb612ac761e 100644
--- a/tests/gateway/test_profile_routing.py
+++ b/tests/gateway/test_profile_routing.py
@@ -46,6 +46,38 @@ class TestProfileRouteMatching:
# guild matches but chat differs -> NO match
assert not r.matches("discord", guild_id="111", chat_id="333")
+ def test_user_id_matches_exactly_and_is_conjunctive_with_chat_id(self):
+ sender = ProfileRoute(
+ name="sender", platform="teams", profile="owner", user_id="aad-456",
+ )
+ assert sender.matches("teams", user_id="aad-456")
+ assert not sender.matches("teams", user_id="AAD-456")
+ assert not sender.matches("teams")
+
+ sender_chat = ProfileRoute(
+ name="sender-chat", platform="teams", profile="owner",
+ user_id="aad-456", chat_id="conversation-1",
+ )
+ assert sender_chat.matches(
+ "teams", user_id="aad-456", chat_id="conversation-1",
+ )
+ assert not sender_chat.matches(
+ "teams", user_id="aad-456", chat_id="conversation-2",
+ )
+
+ def test_sender_routes_split_one_chat_and_outrank_its_location_route(self):
+ routes = parse_profile_routes([
+ {"name": "shared", "platform": "teams", "profile": "shared",
+ "chat_id": "shared-chat"},
+ {"name": "alice", "platform": "teams", "profile": "alice",
+ "chat_id": "shared-chat", "user_id": "user-a"},
+ {"name": "bob", "platform": "teams", "profile": "bob", "user_id": "user-b"},
+ ])
+ for user, profile in (("user-a", "alice"), ("user-b", "bob"), ("user-c", "shared")):
+ assert match_profile_route(
+ routes, "teams", chat_id="shared-chat", user_id=user,
+ ).profile == profile
+
class TestParseProfileRoutes:
def test_empty(self):
@@ -57,16 +89,19 @@ class TestParseProfileRoutes:
# inbound SessionSource ids are str, so un-coerced routes never match.
routes = parse_profile_routes([
{"name": "server", "platform": "discord", "profile": "p",
- "guild_id": 111, "chat_id": 222, "thread_id": 333},
+ "guild_id": 111, "chat_id": 222, "thread_id": 333, "user_id": 444},
{"name": "tg", "platform": "telegram", "profile": "p",
"chat_id": -1001234567890},
{"name": "platform-only", "platform": "discord", "profile": "p"},
])
by_name = {r.name: r for r in routes}
assert (by_name["server"].guild_id, by_name["server"].chat_id,
- by_name["server"].thread_id) == ("111", "222", "333")
+ by_name["server"].thread_id, by_name["server"].user_id) == (
+ "111", "222", "333", "444",
+ )
assert match_profile_route(
routes, "discord", guild_id="111", chat_id="222", thread_id="333",
+ user_id="444",
).name == "server"
assert match_profile_route(
routes, "telegram", chat_id="-1001234567890",
@@ -74,6 +109,16 @@ class TestParseProfileRoutes:
assert (by_name["platform-only"].guild_id, by_name["platform-only"].chat_id,
by_name["platform-only"].thread_id) == (None, None, None)
+ @pytest.mark.parametrize("blank", ["", " "])
+ def test_blank_user_id_is_inert_never_a_broader_route(self, blank):
+ # Unlike the location fields, a blank sender does not fall back to "unconstrained".
+ routes = parse_profile_routes([
+ {"name": "blank", "platform": "teams", "profile": "owner", "user_id": blank},
+ {"name": "legacy", "platform": "teams", "profile": "shared"},
+ ])
+ assert match_profile_route(routes, "teams", user_id=blank).name == "legacy"
+ assert match_profile_route(routes, "teams", user_id="anyone").name == "legacy"
+
def test_non_int_numeric_ids_warn_instead_of_silently_coercing(self, caplog):
# #86470 nuance: float/bool stringify to values that can never match
# an inbound id, so surface the misconfiguration at load time.
@@ -187,3 +232,21 @@ class TestWhatsAppChatIdIdentityMatching:
tg = ProfileRoute(name="tg", platform="telegram", profile="owner", chat_id="640466638")
assert tg.matches("telegram", chat_id="640466638")
assert not tg.matches("telegram", chat_id="[email protected]")
+
+
+class TestGatewayConfigRoundtrip:
+ def test_routes_survive_to_dict_from_dict_with_user_id_and_enabled(self):
+ # GatewayConfig serializes routes with asdict(); a field added to ProfileRoute but not
+ # re-read by parse_profile_routes would silently widen or disable routes on reload.
+ from gateway.config import GatewayConfig
+
+ config = GatewayConfig(profile_routes=parse_profile_routes([
+ {"name": "sender", "platform": "teams", "profile": "owner", "user_id": "aad-456"},
+ {"name": "off", "platform": "teams", "profile": "owner",
+ "chat_id": "conversation-1", "enabled": False},
+ ]))
+ restored = GatewayConfig.from_dict(config.to_dict()).profile_routes
+
+ assert [(r.name, r.user_id, r.enabled, r.specificity) for r in restored] == [
+ ("sender", "aad-456", True, 16), ("off", None, False, 4),
+ ]
diff --git a/tests/gateway/test_teams.py b/tests/gateway/test_teams.py
index c309731a02b..10088f78eda 100644
--- a/tests/gateway/test_teams.py
+++ b/tests/gateway/test_teams.py
@@ -528,6 +528,50 @@ class TestTeamsMessageHandling:
event = adapter.handle_message.call_args[0][0]
assert event.source.chat_type == "group"
+ @pytest.mark.anyio
+ async def test_aad_user_route_survives_conversation_changes(self, monkeypatch):
+ from gateway.profile_routing import parse_profile_routes
+ from gateway.run import GatewayRunner
+
+ routes = parse_profile_routes([
+ {"name": "owner", "platform": "teams", "user_id": "aad-456", "profile": "owner"},
+ {"name": "other", "platform": "teams", "user_id": "aad-789", "profile": "other"},
+ ])
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner.config = SimpleNamespace(multiplex_profiles=True, profile_routes=routes)
+ monkeypatch.setattr(
+ "gateway.run._multiplex_profile_homes",
+ lambda _config: [("owner", None), ("other", None)],
+ )
+
+ adapter = TeamsAdapter(_make_config(
+ client_id="bot-id", client_secret="secret", tenant_id="tenant",
+ ))
+ adapter.gateway_runner = runner
+ adapter._app = MagicMock()
+ adapter._app.id = "bot-id"
+ adapter.handle_message = AsyncMock()
+
+ for activity_id, conversation_id, conversation_type, user_id in (
+ ("activity-group", "19:[email protected]", "groupChat", "aad-456"),
+ ("activity-channel", "19:[email protected]", "channel", "aad-456"),
+ ("activity-dm", "19:[email protected]", "personal", "aad-456"),
+ ("activity-other", "19:[email protected]", "groupChat", "aad-789"),
+ ):
+ await adapter._on_message(self._make_ctx(self._make_activity(
+ activity_id=activity_id,
+ conversation_id=conversation_id,
+ conversation_type=conversation_type,
+ from_aad_id=user_id,
+ )))
+
+ sources = [call.args[0].source for call in adapter.handle_message.await_args_list]
+ assert [source.profile for source in sources] == ["owner", "owner", "owner", "other"]
+ assert [source.chat_type for source in sources] == ["group", "channel", "dm", "group"]
+ assert [runner._session_key_for_source(source).split(":", 2)[1] for source in sources] == [
+ "owner", "owner", "owner", "other",
+ ]
+
class TestTeamsAttachmentClassification:
"""Document attachments must set MessageType.DOCUMENT so run.py's
diff --git a/website/docs/developer-guide/multiplexing-gateway.md b/website/docs/developer-guide/multiplexing-gateway.md
index 2d6c91e74e2..a16a05fde46 100644
--- a/website/docs/developer-guide/multiplexing-gateway.md
+++ b/website/docs/developer-guide/multiplexing-gateway.md
@@ -140,7 +140,7 @@ profile-scoped code runs without the override where one is expected.
## Inbound routing
-`gateway.profile_routes` maps `(platform, guild_id, chat_id, thread_id)` to a
+`gateway.profile_routes` maps `(platform, user_id, guild_id, chat_id, thread_id)` to a
profile; matching is conjunctive, most-specific-first, with parent-chain chat
matching for threads. Routing only runs when multiplexing is active, and a
matched route whose target is outside the served set is rejected (the event is
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 43902bbcb31..cba2364e576 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -517,7 +517,7 @@ hot-added profile that reuses another profile's token is parked with a
Multiplexing selects a profile per **credential** (each profile's own bot
token) or per **URL prefix** (`/p/<profile>/` for HTTP platforms). When several
communities share **one** bot token — for example one Discord bot serving many
-guilds — you can additionally route specific guilds/channels/threads to
+guilds — you can additionally route specific users/guilds/channels/threads to
different profiles with `gateway.profile_routes`:
```yaml
@@ -548,9 +548,15 @@ gateway:
platform: whatsapp
chat_id: "15551234567"
profile: owner
+
+ # One Teams user across DMs, groups, and channels (exact sender id)
+ - name: teams-owner
+ platform: teams
+ user_id: "00000000-0000-0000-0000-000000000000"
+ profile: owner
```
-Routes are matched most-specific-first (`thread_id` > `chat_id` > `guild_id`),
+Routes are matched most-specific-first (`user_id` > `thread_id` > `chat_id` > `guild_id`),
all declared fields must hold (AND), and a route keyed on a channel also
matches threads/forum posts whose parent is that channel. Messages that match
no route stay on the default/active profile. The routed profile gets the full
@@ -603,9 +609,11 @@ only to targets an enabled route with a `chat_id`/`thread_id` maps to that
profile (a `guild_id + chat_id` route qualifies its channel) — a routed
profile's job targeting an unrouted chat (or a chat routed to another profile)
is never sent through the shared bot. Guild-only routes do not qualify a cron
-target; add a `chat_id` route for the delivery channel. The routed profile does
-not need its own `platforms.<platform>` block for this: the shared bot's
-authorization comes from the route, not from the satellite's config.
+target; add a `chat_id` route for the delivery channel. Routes declaring
+`user_id` do not qualify either: cron has no authenticated inbound sender, so
+they need a separate location-only route. The routed profile does not need its
+own `platforms.<platform>` block for this: the shared bot's authorization comes
+from the route, not from the satellite's config.
## Start, stop, or restart all gateways at once