The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): route a credentialless satellite's cron delivery through the primary adapter for exact profile_routes targets (#101113)
Tekniuma6351a71e593
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex d9c72663cc7..68a1a790411 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3353,7 +3353,14 @@ def _deliver_result(job: dict, content: str, adapters=None, loop=None) -> Optionfrom gateway.delivery import resolve_delivery_transport- transport = resolve_delivery_transport(platform, config, adapters)+ target_adapters = adapters+ if isinstance(adapters, SharedRouteAdapters):+ # Credentialless satellite: the primary adapter is a valid+ # transport for THIS target only when an exact primary route maps+ # it to this profile (#101113). Miss → fail closed below.+ shared = adapters.get(platform, target)+ target_adapters = {platform: shared} if shared is not None else {}+ transport = resolve_delivery_transport(platform, config, target_adapters)if transport is not None:pconfig = transport.configruntime_adapter = transport.adapter@@ -3644,7 +3651,7 @@ def _deliver_result(job: dict, content: str, adapters=None, loop=None) -> Optionelif text_to_send:from agent.async_utils import safe_schedule_threadsafe- router = DeliveryRouter(config, adapters)+ router = DeliveryRouter(config, target_adapters)route_target = DeliveryTarget(platform=platform,chat_id=str(chat_id),@@ -5303,21 +5310,20 @@ def _preflight_check_provider_key(job: dict, cfg: dict) -> Optional[str]:return None-def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool:- """True when the primary gateway routes this platform to the profile the- scheduler is currently serving.+def _primary_profile_routes_for_current_home() -> list:+ """Primary gateway ``profile_routes`` that target the profile currently+ being served, or ``[]`` (also when this IS the primary home).Under ``gateway.multiplex_profiles`` a satellite profile's cron jobs areticked by the primary gateway's in-process ticker (#69377) and deliveredthrough the primary gateway's live adapters — the satellite home neverholds the platform credentials itself (giving it a token of its own is a- ``duplicate_credential`` fatal). ``_preflight_check_delivery`` loads the- gateway config of the job's OWN home, where such a platform correctly- reads as unconnected; consulting the primary home's ``profile_routes``- keeps routed satellite jobs from being permanently false-blocked (#97476).- Reads the primary config.yaml directly (both the top-level and nested- ``gateway.`` forms) instead of ``load_gateway_config()`` so no primary- platform config leaks into this process's environment.+ ``duplicate_credential`` fatal). Reads the primary config.yaml directly+ (both the top-level and nested ``gateway.`` forms) instead of+ ``load_gateway_config()`` so no primary platform config leaks into this+ process's environment. Shared by the preflight rescue (#97476) and the+ delivery-time shared-transport resolver (#101113) so route semantics+ cannot drift between the two halves."""try:from hermes_constants import get_default_hermes_root, get_hermes_home@@ -5328,10 +5334,10 @@ def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool:primary_home.expanduser().resolve(strict=False)== current_home.expanduser().resolve(strict=False)):- return False # this IS the primary home — nothing to consult+ return [] # this IS the primary home — nothing to consultconfig_path = primary_home.expanduser() / "config.yaml"if not config_path.exists():- return False+ return []import yaml@@ -5341,25 +5347,75 @@ def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool:if routes_raw is None and isinstance(raw.get("gateway"), dict):routes_raw = raw["gateway"].get("profile_routes")if not isinstance(routes_raw, list):- return False+ return []from gateway.profile_routing import parse_profile_routesfrom hermes_cli.profiles import profile_matches_home- platform_key = platform_name.lower()- for route in parse_profile_routes(routes_raw):- if (- route.enabled- and str(route.platform).lower() == platform_key- and profile_matches_home(route.profile)- ):- return True- return False+ return [+ route+ for route in parse_profile_routes(routes_raw)+ if route.enabled and profile_matches_home(route.profile)+ ]except Exception:logger.debug(- "preflight: primary-gateway profile-route lookup unavailable",+ "primary-gateway profile-route lookup unavailable",exc_info=True,)+ return []+++def _delivery_platform_routed_from_primary_gateway(platform_name: str) -> bool:+ """True when the primary gateway routes this platform to the profile the+ scheduler is currently serving (preflight rescue, #97476)."""+ platform_key = platform_name.lower()+ return any(+ str(route.platform).lower() == platform_key+ for route in _primary_profile_routes_for_current_home()+ )+++class SharedRouteAdapters:+ """Read-only adapter map for a credentialless satellite profile (#101113).++ A satellite under ``gateway.profile_routes`` owns no bot credential and so+ has no adapter map of its own; its inbound traffic arrives on the PRIMARY+ adapter and is routed to it by an exact route. Its cron output must go+ back out the same transport — but ONLY for targets an enabled primary+ route maps to this profile. ``get(platform, target)`` resolves the primary+ adapter iff the route matcher used by inbound routing+ (``ProfileRoute.matches``) accepts the target's ``chat_id``/``thread_id``;+ every other lookup is a miss, so an unmatched target, a disabled route, or+ a route naming another profile still fails closed (never the default bot).+ A plain ``get(platform)`` (no target) is always a miss: routing is+ per-target, not per-platform.+ """++ def __init__(self, primary_adapters, routes) -> None:+ self._primary = dict(primary_adapters or {})+ self._routes = list(routes or [])++ def __bool__(self) -> bool:+ return bool(self._primary) and bool(self._routes)++ def get(self, platform, target=None, default=None):+ if not target:+ return default+ adapter = self._primary.get(platform)+ if adapter is None:+ return default+ platform_key = str(getattr(platform, "value", platform)).lower()+ chat_id = str(target.get("chat_id") or "") or None+ thread_id = target.get("thread_id")+ thread_id = str(thread_id) if thread_id else None+ for route in self._routes:+ if str(route.platform).lower() != platform_key:+ continue+ if not (route.chat_id or route.thread_id):+ continue # guild-only routes are not target-exact+ if route.matches(str(route.platform), chat_id=chat_id, thread_id=thread_id):+ return adapter+ return defaultreturn Falsediff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex 84e51e9824c..563cba345b2 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -689,7 +689,12 @@ class InProcessCronScheduler(CronScheduler):"""import loggingfrom cron.scheduler import tick as cron_tick- from cron.scheduler import CronTickYielded, _is_fd_exhaustion+ from cron.scheduler import (+ CronTickYielded,+ SharedRouteAdapters,+ _is_fd_exhaustion,+ _primary_profile_routes_for_current_home,+ )from cron.jobs import (clear_ticker_error,record_ticker_error,@@ -775,6 +780,20 @@ class InProcessCronScheduler(CronScheduler):_tick_adapters = adapterselse:_tick_adapters = (profile_adapters or {}).get(_pname) or {}+ if not _tick_adapters and adapters:+ # Credentialless satellite under+ # gateway.profile_routes: no bot of its+ # own, so its output may ride the+ # PRIMARY adapter — but only for+ # targets an exact enabled primary+ # route maps to this profile+ # (#101113). Unmatched targets still+ # fail closed; this is not a default+ # fallback.+ _tick_adapters = SharedRouteAdapters(+ adapters,+ _primary_profile_routes_for_current_home(),+ )cron_tick(verbose=False,adapters=_tick_adapters,diff --git a/tests/cron/test_cron_multiplex_shared_route_delivery.py b/tests/cron/test_cron_multiplex_shared_route_delivery.pynew file mode 100644index 00000000000..92aa6b4f7b2--- /dev/null+++ b/tests/cron/test_cron_multiplex_shared_route_delivery.py@@ -0,0 +1,112 @@+"""Regression tests for #101113 — a credentialless satellite profile under+``gateway.profile_routes`` delivers cron output through the PRIMARY adapter+for exactly the targets the primary routes to it, and fails closed otherwise.++The multiplex ticker hands such a profile a ``SharedRouteAdapters`` view over+the primary adapter map; ``_deliver_result`` resolves a transport from it per+target using the same ``ProfileRoute.matches`` predicate as inbound routing.+"""+import asyncio+from concurrent.futures import Future+from unittest.mock import MagicMock, patch++import yaml++from cron.scheduler import (+ SharedRouteAdapters,+ _deliver_result,+ _primary_profile_routes_for_current_home,+)+from gateway.config import Platform, PlatformConfig+from hermes_constants import reset_hermes_home_override, set_hermes_home_override++PRIMARY_YAML = {+ "gateway": {+ "multiplex_profiles": True,+ "profile_routes": [+ {"name": "fit", "platform": "discord", "chat_id": "1543065293755256852", "profile": "fitness"},+ {"name": "off", "platform": "discord", "chat_id": "999", "profile": "fitness", "enabled": False},+ {"name": "other", "platform": "discord", "chat_id": "777", "profile": "other"},+ ],+ }+}+++def _job(chat_id: str) -> dict:+ return {"id": "a7ae1520356c", "name": "brief", "deliver": f"discord:{chat_id}"}+++def _run(job, adapters):+ """Drive ``_deliver_result`` with a live loop and a real DeliveryRouter."""+ loop = MagicMock()+ loop.is_running.return_value = True++ def fake_run_coro(coro, _loop):+ future = Future()+ future.set_result(asyncio.run(coro))+ return future++ standalone = []++ async def _fake_send_to_platform(platform, pconfig, chat_id, text, **kwargs):+ standalone.append(chat_id)+ return {"success": False, "error": "DISCORD_BOT_TOKEN is not set"}++ config = MagicMock()+ config.platforms = {Platform.DISCORD: PlatformConfig(enabled=True)}+ config.get_home_channel = lambda p: None+ with patch("gateway.config.load_gateway_config", return_value=config), \+ patch("cron.scheduler.load_config", return_value={"cron": {"wrap_response": False}}), \+ patch("tools.send_message_tool._send_to_platform", _fake_send_to_platform), \+ patch("asyncio.run_coroutine_threadsafe", side_effect=fake_run_coro):+ error = _deliver_result(job, "hello", adapters=adapters, loop=loop)+ return error, standalone+++def _primary_adapter():+ adapter = MagicMock()+ adapter.sent = []++ async def send(chat_id, content, metadata=None):+ adapter.sent.append(chat_id)+ return {"success": True, "message_id": "m1"}++ adapter.send = send+ return adapter+++def test_satellite_routes_exact_target_through_primary_adapter(tmp_path, monkeypatch):+ root = tmp_path / "root"+ fitness_home = root / "profiles" / "fitness"+ fitness_home.mkdir(parents=True)+ (root / "config.yaml").write_text(yaml.safe_dump(PRIMARY_YAML), encoding="utf-8")+ monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)+ primary = _primary_adapter()++ token = set_hermes_home_override(str(fitness_home))+ try:+ shared = SharedRouteAdapters(+ {Platform.DISCORD: primary}, _primary_profile_routes_for_current_home()+ )+ # exact enabled route → primary adapter sends, no standalone attempt+ error, standalone = _run(_job("1543065293755256852"), shared)+ assert error is None, error+ assert primary.sent == ["1543065293755256852"]+ assert standalone == []++ # unmatched chat, disabled route, route for another profile → the+ # primary bot is NEVER used; delivery stays on the satellite's own+ # (credentialless) standalone path and reports its failure.+ for chat in ("424242", "999", "777"):+ primary.sent.clear()+ error, standalone = _run(_job(chat), shared)+ assert error is not None and "DISCORD_BOT_TOKEN" in error+ assert primary.sent == []+ assert standalone == [chat]+ finally:+ reset_hermes_home_override(token)+++def test_shared_view_is_falsy_without_routes_or_primary_adapters():+ assert not SharedRouteAdapters({}, [])+ assert SharedRouteAdapters({Platform.DISCORD: object()}, []).get(Platform.DISCORD) is None