Skip to content

The agent that grows with you

fix(gateway): egress adapter and channel directory no longer follow the per-turn active profile

Tekniumbbb087f3d115
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index e80435d9827..22ec0ad8207 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -209,14 +209,21 @@ class GatewayAuthorizationMixin:
return None
profile_name = (profile or "").strip() or None
if profile_name and profile_name != "default":
- active_profile = None
- active_profile_fn = getattr(self, "_active_profile_name", None)
- if callable(active_profile_fn):
- try:
- active_profile = active_profile_fn()
- except Exception:
- active_profile = None
- if profile_name == active_profile:
+ # Adapter ownership is process-wide: only the profile the gateway
+ # was LAUNCHED as owns ``self.adapters``. ``_active_profile_name()``
+ # reads the per-turn HERMES_HOME override, so inside a secondary
+ # profile's ``_profile_runtime_scope`` it reports that secondary
+ # and would hand it the default bot. Compare against the identity
+ # captured at construction instead.
+ primary_profile = getattr(self, "_primary_profile_name", None)
+ if not primary_profile:
+ active_profile_fn = getattr(self, "_active_profile_name", None)
+ if callable(active_profile_fn):
+ try:
+ primary_profile = active_profile_fn()
+ except Exception:
+ primary_profile = None
+ if profile_name == primary_profile:
adapters = getattr(self, "adapters", None) or {}
return adapters.get(platform)
profile_adapters = getattr(self, "_profile_adapters", None) or {}
diff --git a/gateway/channel_directory.py b/gateway/channel_directory.py
index 619c0f05b7a..d07a7160762 100644
--- a/gateway/channel_directory.py
+++ b/gateway/channel_directory.py
@@ -11,6 +11,7 @@ import json
import logging
import time
from datetime import datetime
+from pathlib import Path
from typing import Any, Dict, List, Optional
from hermes_cli.config import get_hermes_home
@@ -18,7 +19,12 @@ from utils import atomic_json_write
logger = logging.getLogger(__name__)
-DIRECTORY_PATH = get_hermes_home() / "channel_directory.json"
+# Resolved lazily (see ``_directory_path``): a multiplexed gateway serves
+# several profile homes from one process, so an import-time constant would pin
+# every profile's directory to whichever home imported this module first.
+# ``DIRECTORY_PATH`` / ``CHANNEL_ALIASES_PATH`` stay as explicit overrides
+# (tests patch them); ``None`` means "resolve from the current home".
+DIRECTORY_PATH: Optional[Path] = None
# Throttle window for repeated Slack channel-directory refresh failures.
# The directory rebuilds on a timer, so a persistent workspace error (e.g.
# missing scope, revoked token) would otherwise re-log the same warning on
@@ -33,14 +39,23 @@ _slack_directory_warning_last: Dict[tuple[str, str], float] = {}
# on every build AND every load, giving durable human-friendly names (and
# letting you pre-name a chat before it has produced any traffic).
# Format: {"<platform>": {"<chat_id>": "<friendly name>", ...}, ...}
-CHANNEL_ALIASES_PATH = get_hermes_home() / "channel_aliases.json"
+CHANNEL_ALIASES_PATH: Optional[Path] = None
+
+
+def _directory_path() -> Path:
+ return DIRECTORY_PATH or get_hermes_home() / "channel_directory.json"
+
+
+def _aliases_path() -> Path:
+ return CHANNEL_ALIASES_PATH or get_hermes_home() / "channel_aliases.json"
def _load_channel_aliases() -> Dict[str, Dict[str, str]]:
- if not CHANNEL_ALIASES_PATH.exists():
+ aliases_path = _aliases_path()
+ if not aliases_path.exists():
return {}
try:
- with open(CHANNEL_ALIASES_PATH, encoding="utf-8") as f:
+ with open(aliases_path, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
@@ -143,7 +158,8 @@ async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
"""
Build a channel directory from connected platform adapters and session data.
- Returns the directory dict and writes it to DIRECTORY_PATH.
+ Returns the directory dict and writes it to the current home's
+ ``channel_directory.json``.
"""
from gateway.config import Platform
@@ -206,7 +222,7 @@ async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
}
try:
- await asyncio.to_thread(atomic_json_write, DIRECTORY_PATH, directory)
+ await asyncio.to_thread(atomic_json_write, _directory_path(), directory)
except Exception as e:
logger.warning("Channel directory: failed to write: %s", e)
@@ -525,12 +541,13 @@ def _build_from_sessions_json(platform_name: str) -> List[Dict[str, str]]:
def load_directory() -> Dict[str, Any]:
"""Load the cached channel directory from disk."""
- if not DIRECTORY_PATH.exists():
+ directory_path = _directory_path()
+ if not directory_path.exists():
base = {"updated_at": None, "platforms": {}}
_apply_channel_aliases(base["platforms"])
return base
try:
- with open(DIRECTORY_PATH, encoding="utf-8") as f:
+ with open(directory_path, encoding="utf-8") as f:
data = json.load(f)
# Re-apply aliases on read so friendly names take effect immediately,
# even between timed rebuilds and for brand-new alias entries.
diff --git a/gateway/run.py b/gateway/run.py
index b45b1a6fc27..7f0fdfed9ec 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -7721,6 +7721,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# context pin; last-delivered voice-channel context) lives on
# SessionState.conversation — see gateway/session_state.py.
self._kanban_notifier_profile = self._active_profile_name()
+ # Launch-time identity of the profile that owns ``self.adapters``;
+ # ``_authorization_adapter`` compares against this rather than the
+ # per-turn ``_active_profile_name()`` (see gateway/authz_mixin.py).
+ self._primary_profile_name = self._kanban_notifier_profile
# Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
self._teams_pipeline_runtime = None
self._teams_pipeline_runtime_error: Optional[str] = None
diff --git a/tests/gateway/test_multiplex_interactive_auth.py b/tests/gateway/test_multiplex_interactive_auth.py
index 798d179b73b..26a03b59558 100644
--- a/tests/gateway/test_multiplex_interactive_auth.py
+++ b/tests/gateway/test_multiplex_interactive_auth.py
@@ -108,3 +108,30 @@ def test_bot_sender_reaches_allow_bots_policy_through_callback(mux_home):
with _profile_runtime_scope(mux_home):
assert tg._is_user_authorized_from_message(msg(4242, True)) is True
assert tg._is_user_authorized_from_message(msg(4343, False)) is False
+
+
+def test_authorization_adapter_ignores_per_turn_active_profile(mux_home):
+ """#87240 egress half: inside a secondary profile's runtime scope the
+ default bot must not be handed to that profile (fail-closed None); the
+ launch profile still resolves ``self.adapters``."""
+ from gateway.run import _profile_runtime_scope
+
+ runner = _runner(mux_home)
+ default_bot = object()
+ runner.adapters = {Platform.TELEGRAM: default_bot}
+
+ with _profile_runtime_scope(mux_home / "profiles" / "secondary"):
+ assert runner._authorization_adapter(Platform.TELEGRAM, profile="secondary") is None
+ assert runner._authorization_adapter(Platform.TELEGRAM, profile="default") is default_bot
+
+
+def test_channel_directory_path_follows_current_home(mux_home):
+ """#87240: the directory file resolves against the CURRENT profile home,
+ not the home that happened to import the module."""
+ import gateway.channel_directory as cd
+ from gateway.run import _profile_runtime_scope
+
+ assert cd.DIRECTORY_PATH is None
+ with _profile_runtime_scope(mux_home / "profiles" / "secondary"):
+ assert cd._directory_path() == Path(mux_home / "profiles" / "secondary" / "channel_directory.json")
+ assert cd._directory_path() == Path(mux_home / "channel_directory.json")