The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): tell the sender when a bot message routes to a parked profile
unsupportedpastels2cd44dcf268f
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.mdindex b8225a2d63a..2ffdec619bd 100644--- a/gateway/AGENTS.md+++ b/gateway/AGENTS.md@@ -99,8 +99,10 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki(`run_adapters.py::_canonicalize` — the per-profile / default message, busy and platform-eventhandlers, the adapter auth-check callback, `run_inbound.py::_hm_admit_event`). No key derivationbefore it; an unresolved identity under multiplexing (route to an unserved profile) is dropped- with one WARNING at the first seam it reaches, never keyed into `agent:main`. `_transport_owner`,- `_authorization_home_for_source`, `_resolve_profile_home_for_source`, `_session_key_profile` and+ with one WARNING at the first seam it reaches, never keyed into `agent:main`+ (`parked_route_refusal.drop_rejected_route`; a route to a *parked* profile also tells the sender+ in-channel to resend, since a direct bot's update is already confirmed and never redelivered).+ `_transport_owner`, `_authorization_home_for_source`, `_resolve_profile_home_for_source`, `_session_key_profile` and`_resolve_profile_for_key` read the identity when present and fall back to their old chain onlyfor sources nothing resolved (restored rows, hand-built sources). Never derive a second answernext to the identity; extend the object. `transport_profile` ≠ `runtime_profile` is normaldiff --git a/gateway/parked_route_refusal.py b/gateway/parked_route_refusal.pynew file mode 100644index 00000000000..cff36fed4de--- /dev/null+++ b/gateway/parked_route_refusal.py@@ -0,0 +1,53 @@+"""A message a direct platform bot routes to a parked profile is refused out loud, never dropped.++A parked profile comes back on a rescan, so its traffic is temporarily unavailable. Relay frames and+webhooks are left unacknowledged for the platform to redeliver (``webhook_ingress``). A direct bot+(Telegram's PTB ``Updater``, Slack Socket Mode, Discord's gateway, Google Chat Pub/Sub) has already+confirmed the update to its platform before the gateway sees it, so nothing redelivers it. Holding it+here would be a second inbound queue outside the one durable queue, kept for a profile whose store is+the one that cannot be trusted. So the sender is told, in-channel, to resend, and nothing is admitted.+"""+import asyncio+import logging++logger = logging.getLogger(__name__)++# Generic on purpose: the chat is not told which profile the route targets or why it is parked.+PARKED_ROUTE_NOTICE = 'This assistant is temporarily unavailable; please resend your message in a moment.'+++def drop_rejected_route(adapter, source):+ """Log an inbound event dropped because its explicit profile route targets a profile this+ gateway does not serve; when that profile is parked, also refuse it to the sender in-channel."""+ from gateway.run_runtime import profile_parked+ name = getattr(adapter, 'name', None) or getattr(getattr(source, 'platform', None), 'value', '?')+ chat_id = getattr(source, 'chat_id', '?')+ profile = getattr(source, '_rejected_route_profile', None)+ if adapter is None or not profile_parked(getattr(adapter, 'gateway_runner', None), profile):+ logger.warning(+ '[%s] Dropping inbound event for %s: explicit profile route targets an unserved profile', name, chat_id)+ return+ platform = getattr(getattr(source, 'platform', None), 'value', None) or '?'+ logger.warning(+ '[%s] Refusing inbound event for %s: routed profile %r on %s is parked (reason=profile_parked); '+ 'nothing was admitted, the sender was asked to resend', name, chat_id, profile, platform)+ try:+ task = asyncio.get_running_loop().create_task(_send_refusal(adapter, source))+ except RuntimeError:+ logger.warning('[%s] Could not refuse the parked-profile event for %s: no running loop', name, chat_id)+ return+ tasks = getattr(adapter, '_background_tasks', None)+ if isinstance(tasks, set):+ tasks.add(task)+ task.add_done_callback(tasks.discard)+++async def _send_refusal(adapter, source):+ """Reply in the sender's chat and thread, as the runner's own notices do."""+ try:+ metadata = adapter.gateway_runner._thread_metadata_for_source(source)+ await adapter.send(source.chat_id, PARKED_ROUTE_NOTICE, reply_to=getattr(source, 'message_id', None),+ metadata=metadata)+ except Exception:+ logger.warning('[%s] Could not send the parked-profile refusal to %s',+ getattr(adapter, 'name', '?'), getattr(source, 'chat_id', '?'), exc_info=True)diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex db7f944435e..a8350f8da59 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2435,9 +2435,8 @@ class BasePlatformAdapter(ABC):return Falseif getattr(source, "profile_route_rejected", False) is not True:return False- logger.warning(- "[%s] Dropping inbound event for %s: explicit profile route targets an unserved profile",- self.name, getattr(source, "chat_id", "?"))+ from gateway.parked_route_refusal import drop_rejected_route+ drop_rejected_route(self, source) # one WARNING; a parked target is also refused to the senderreturn Truedef _session_key_profile(self, source: Optional[Any] = None) -> Optional[str]:@@ -4807,14 +4806,14 @@ class BasePlatformAdapter(ABC):# Profile from configured routes, else the owning profile of a dedicated secondary bot (so no# later ``source.profile``-less fallback can re-route the message through the default bot's routes).owner_profile = getattr(self, "_owner_profile", None)- profile, profile_route_rejected = owner_profile, False+ profile, profile_route_rejected, rejected_profile = owner_profile, False, Noneif self.gateway_runner is not None:from gateway.profile_routing import ProfileRouteRejectedtry:profile = self.gateway_runner._profile_name_for_source(SessionSource(**fields), adapter_profile=owner_profile) or owner_profile- except ProfileRouteRejected:- profile_route_rejected = True+ except ProfileRouteRejected as exc:+ profile_route_rejected, rejected_profile = True, exc.profileexcept Exception:logger.warning("Profile resolution failed for %s/%s, defaulting to active profile",self.platform, chat_id, exc_info=True)@@ -4824,7 +4823,7 @@ class BasePlatformAdapter(ABC):# Transport-only, kept out of to_dict(): the receiving adapter is authoritative this turn# even if profile_routes picks another runtime; the reject flag is consumed before auth.source._transport_adapter_ref = weakref.ref(self)- source.profile_route_rejected = profile_route_rejected+ source.profile_route_rejected, source._rejected_route_profile = profile_route_rejected, rejected_profilereturn source@abstractmethoddiff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 7e5fae02db0..8f54c9f8e09 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -166,10 +166,11 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)if getattr(_config, "multiplex_profiles", False):self._canonicalize(source)if getattr(source, "profile_route_rejected", False) is True:- logger.warning(- "Dropping inbound message because its explicit profile route "- "targets an unserved profile"- )+ from gateway.parked_route_refusal import drop_rejected_route+ _intake = None+ with suppress(Exception):+ _intake = self._intake_adapter_for(source)+ drop_rejected_route(_intake, source) # a parked target is also refused to the senderreturn Noneis_internal = bool(getattr(event, "internal", False)) # e.g. background-process notificationsdiff --git a/gateway/run_voice.py b/gateway/run_voice.pyindex f54654bac33..f16cbdcb1df 100644--- a/gateway/run_voice.py+++ b/gateway/run_voice.py@@ -318,7 +318,8 @@ class GatewayVoiceMixin:from gateway.session_identity import clear_identityclear_identity(source)if self._canonicalize(source, transport_profile=getattr(adapter, "_owner_profile", None)) is None:- logger.warning("Dropping voice input: its profile route targets an unserved profile")+ from gateway.parked_route_refusal import drop_rejected_route+ drop_rejected_route(adapter, source) # a parked target is refused in the voice text channelreturn# Validate the session owner against the current allowlist before auto-resuming. A session created# before TELEGRAM_ALLOWED_USERS (or equivalent) was configured, or before the owner was removed fromdiff --git a/tests/gateway/test_parked_profile_platform_refusal.py b/tests/gateway/test_parked_profile_platform_refusal.pynew file mode 100644index 00000000000..54ef9372ace--- /dev/null+++ b/tests/gateway/test_parked_profile_platform_refusal.py@@ -0,0 +1,97 @@+"""A message a direct platform bot routes to a parked profile is refused out loud, never dropped.++A parked profile comes back on a rescan, so its traffic is temporarily unavailable. Relay and webhook+ingress are redelivered (no ACK, a retryable 503). A direct bot (Telegram, Discord, Slack, ...) has+already confirmed the update to its platform before the gateway sees it, so there is nothing to+withhold: the sender is told in-channel to resend, and nothing is admitted.+"""+import asyncio+import logging+import weakref++import pytest++from gateway.config import Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult+from gateway.profile_routing import ProfileRoute+from gateway.session import SessionSource+from tests.gateway.test_parked_profile_ingress import _admissions, _close, _homes, _runner_with_beta_parked+++class _Bot(BasePlatformAdapter):+ """The default profile's shared bot; ``sent`` records what went back to the chat."""++ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token='t'), Platform.TELEGRAM)+ self.sent = []++ async def connect(self, *, is_reconnect=False):+ return True++ async def disconnect(self):+ pass++ async def send(self, chat_id, content='', reply_to=None, metadata=None):+ self.sent.append((chat_id, content, reply_to))+ return SendResult(success=True, message_id='r1')++ async def get_chat_info(self, chat_id):+ return {}+++async def _shared_bot_with_beta_parked(tmp_path, monkeypatch):+ homes = _homes(tmp_path, monkeypatch)+ runner = await _runner_with_beta_parked(+ tmp_path, monkeypatch, homes,+ profile_routes=[ProfileRoute(name='to-beta', platform='telegram', profile='beta', chat_id='C')])+ bot = _Bot()+ bot.gateway_runner = runner+ runner.adapters[Platform.TELEGRAM] = bot+ runner._wire_adapter_handlers(bot)+ return homes, runner, bot+++async def _settle(bot):+ await asyncio.gather(*list(bot._background_tasks), return_exceptions=True)+++def _assert_refused(bot, homes, event, caplog):+ assert [(chat, reply_to) for chat, _text, reply_to in bot.sent] == [('C', 'm1')], (+ f'the sender of a message routed to a parked profile was not told: {bot.sent}')+ assert 'temporarily unavailable' in bot.sent[0][1] and 'resend' in bot.sent[0][1], bot.sent+ assert 'beta' not in bot.sent[0][1], 'the refusal names the routed profile to the chat'+ assert event._gateway_accepted is False+ assert _admissions(homes[0][1]) == 0 and _admissions(homes[1][1]) == 0+ warned = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert any('beta' in m and 'telegram' in m and 'profile_parked' in m for m in warned), warned+++async def test_a_shared_bot_message_routed_to_a_parked_profile_is_refused_in_channel(tmp_path, monkeypatch, caplog):+ homes, runner, bot = await _shared_bot_with_beta_parked(tmp_path, monkeypatch)+ source = bot.build_source('C', chat_type='group', user_id='U', message_id='m1')+ event = MessageEvent(text='please do this', message_type=MessageType.TEXT, source=source, message_id='m1')+ try:+ with caplog.at_level(logging.WARNING):+ await bot.handle_message(event)+ await _settle(bot)+ _assert_refused(bot, homes, event, caplog)+ finally:+ _close(runner, homes)+++async def test_a_hand_built_source_routed_to_a_parked_profile_is_refused_at_the_runner_gate(+ tmp_path, monkeypatch, caplog):+ """Internal and voice paths build the source themselves and reach the runner's ingress gate."""+ homes, runner, bot = await _shared_bot_with_beta_parked(tmp_path, monkeypatch)+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='C', chat_type='group', user_id='U', message_id='m1')+ source._transport_adapter_ref = weakref.ref(bot)+ event = MessageEvent(text='please do this', message_type=MessageType.TEXT, source=source, message_id='m1')+ try:+ with caplog.at_level(logging.WARNING):+ assert await runner._hm_admit_event(event) is None+ await _settle(bot)+ _assert_refused(bot, homes, event, caplog)+ finally:+ _close(runner, homes)