Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions gateway/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,50 @@ def _scan_bundled_plugin_platforms(cls) -> set:
_BUILTIN_PLATFORM_VALUES = frozenset(m.value for m in Platform.__members__.values())


# Platforms that bind a host TCP port (HTTP/webhook listeners). In a profile
# multiplexer the default profile owns the single shared listener and serves
# every profile through the /p/<profile>/ URL prefix, so a SECONDARY profile
# enabling one of these is always a misconfiguration: it would try to bind a
# port already held by the default's listener. Single source of truth for
# both the gateway's fail-fast startup validation (gateway/run.py) and the
# dashboard's pre-write mutation validation (hermes_cli/web_server.py) so
# the two policies cannot drift. Stored as platform .value strings.
PORT_BINDING_PLATFORM_VALUES = frozenset({
"webhook",
"api_server",
"msgraph_webhook",
"feishu",
"wecom_callback",
"bluebubbles",
"sms",
"whatsapp_cloud",
"line",
})

# Platforms whose port-binding status depends on connection mode. Feishu in
# websocket mode (its default) uses an outbound long connection — no listener.
# Only webhook/callback mode binds a port. Maps platform value → the mode
# value that actually binds (#52563).
PORT_BINDING_CONDITIONAL_MODES: dict[str, str] = {
"feishu": "webhook",
}


def platform_binds_port(platform_value: str, extra: Optional[dict] = None) -> bool:
"""Return True when *platform_value* actually binds a port for *extra* config.

Mode-conditional platforms (Feishu) only bind in their listener mode;
everything else in ``PORT_BINDING_PLATFORM_VALUES`` always binds.
"""
if platform_value not in PORT_BINDING_PLATFORM_VALUES:
return False
expected_mode = PORT_BINDING_CONDITIONAL_MODES.get(platform_value)
if expected_mode is not None:
actual = str((extra or {}).get("connection_mode", "websocket")).strip().lower()
return actual == expected_mode
return True


@dataclass
class HomeChannel:
"""
Expand Down
21 changes: 20 additions & 1 deletion gateway/platforms/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1284,8 +1284,27 @@ def _resolve_request_profile(self, request: "web.Request"):

@staticmethod
def _profile_scope(profile: Optional[str]):
"""Enter the multiplex profile runtime scope, or a no-op when unset."""
"""Enter the multiplex profile runtime scope, or a no-op when unset.

When no ``/p/<profile>/`` prefix was given AND multiplexing is active,
enter the DEFAULT profile's scope instead of a no-op: api_server is a
port-binding platform that lives on the default profile, and with
multiplex fail-closed ``get_secret`` active, an unscoped agent run
raises ``UnscopedSecretError`` on its first credential read (#61276).
Single-profile gateways keep the no-op — ``get_secret`` falls through
to ``os.environ`` there, unchanged.
"""
if not profile:
try:
from agent.secret_scope import is_multiplex_active

if is_multiplex_active():
from gateway.run import _profile_runtime_scope
from hermes_constants import get_hermes_home

return _profile_runtime_scope(get_hermes_home())
except Exception:
pass
return nullcontext()
from gateway.run import _profile_runtime_scope
from hermes_cli.profiles import get_profile_dir
Expand Down
86 changes: 48 additions & 38 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1411,32 +1411,29 @@ def _current_max_iterations() -> int:
# Platforms that bind a host TCP port (HTTP/webhook listeners). In a profile
# multiplexer the default profile owns the single shared listener and serves
# every profile through the /p/<profile>/ URL prefix, so a SECONDARY profile
# enabling one of these is always a misconfiguration: it would try to bind a
# port already held by the default's listener. We hard-error on it rather than
# silently dropping the adapter (see _start_one_profile_adapters).
# Stored as platform .value strings since the Platform enum is imported below.
_PORT_BINDING_PLATFORM_VALUES = frozenset({
"webhook",
"api_server",
"msgraph_webhook",
"feishu",
"wecom_callback",
"bluebubbles",
"sms",
"whatsapp_cloud",
"line",
})
# enabling one of these is always a misconfiguration. We skip that secondary
# profile (SecondaryPortBindingConfigError) so a single bad profile cannot
# take down the whole multiplexer. The set lives in gateway.config so the
# dashboard's pre-write validation enforces the same policy.
from gateway.config import (
PORT_BINDING_PLATFORM_VALUES as _PORT_BINDING_PLATFORM_VALUES,
platform_binds_port as _platform_binds_port,
)


class MultiplexConfigError(RuntimeError):
"""A profile multiplexer config is invalid (fail-fast at startup).
"""A profile multiplexer config is invalid.

Distinct from a transient adapter-connect failure: a transient error is
logged and the gateway stays alive to retry, but a config error means the
operator must fix config.yaml, so it aborts startup cleanly.
Distinct from a transient adapter-connect failure: a config error means the
operator must fix config.yaml. Fatal configuration errors propagate to the
startup guard instead of being treated as retryable adapter noise.
"""


class SecondaryPortBindingConfigError(MultiplexConfigError):
"""A secondary profile conflicts with the multiplexer's shared listener."""


@_contextmanager
def _profile_runtime_scope(profile_home: "Path"):
"""Scope config/skills/memory AND credentials to a profile for one turn.
Expand Down Expand Up @@ -8754,10 +8751,13 @@ async def _start_secondary_profile_adapters(self) -> int:
connected += await self._start_one_profile_adapters(
profile_name, profile_home, claimed
)
except SecondaryPortBindingConfigError as e:
logger.warning(
"Skipping secondary profile '%s' due to port-binding config error: %s",
profile_name,
e,
)
except MultiplexConfigError:
# Config error (e.g. a secondary profile binding a port) is not
# transient — propagate so startup aborts cleanly instead of
# limping along with a half-configured multiplexer.
raise
except Exception as e:
logger.error(
Expand Down Expand Up @@ -8800,6 +8800,23 @@ async def _start_one_profile_adapters(
"'open'."
)

port_binding_platforms = sorted(
platform.value
for platform, platform_config in profile_cfg.platforms.items()
if platform_config.enabled
and _platform_binds_port(platform.value, platform_config.extra)
)
if port_binding_platforms:
joined = ", ".join(port_binding_platforms)
raise SecondaryPortBindingConfigError(
f"Profile '{profile_name}' enables port-binding platform(s) "
f"{joined}, but gateway.multiplex_profiles is on. The default "
f"profile owns the single shared HTTP listener and serves every "
f"profile through the /p/{profile_name}/ URL prefix. Remove "
f"these platform entries from profile '{profile_name}'s config.yaml "
f"or configure them only on the default profile."
)

profile_map = self._profile_adapters.setdefault(profile_name, {})
connected = 0
for platform, platform_config in profile_cfg.platforms.items():
Expand All @@ -8813,21 +8830,6 @@ async def _start_one_profile_adapters(
and platform is Platform.RELAY
):
continue
# A secondary profile must NOT enable a port-binding platform: the
# default profile's listener already serves every profile via the
# /p/<profile>/ prefix, so a second bind can only collide. This is a
# config error, not a transient failure — fail fast and loud.
if platform.value in _PORT_BINDING_PLATFORM_VALUES:
raise MultiplexConfigError(
f"Profile '{profile_name}' enables the port-binding platform "
f"'{platform.value}', but gateway.multiplex_profiles is on. The "
f"default profile owns the single shared HTTP listener and "
f"serves every profile through the /p/{profile_name}/ URL "
f"prefix — a secondary profile cannot bind its own port. "
f"Remove platforms.{platform.value} from profile "
f"'{profile_name}'s config.yaml (configure it only on the "
f"default profile)."
)
try:
with _profile_runtime_scope(profile_home):
adapter = self._create_adapter(platform, platform_config)
Expand Down Expand Up @@ -8873,7 +8875,9 @@ async def _start_one_profile_adapters(
adapter.set_session_store(self.session_store)
adapter.set_busy_session_handler(self._handle_active_session_busy_message)
adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id)
adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform))
adapter.set_authorization_check(
self._make_adapter_auth_check(adapter.platform, profile_name=profile_name)
)
adapter._busy_text_mode = self._busy_text_mode

try:
Expand Down Expand Up @@ -9090,6 +9094,7 @@ def _create_adapter(
def _make_adapter_auth_check(
self,
platform: Platform,
profile_name: Optional[str] = None,
) -> Callable[[str, Optional[str], Optional[str]], bool]:
"""Build a platform-bound auth callback for adapter use.

Expand All @@ -9102,6 +9107,10 @@ def _make_adapter_auth_check(
The returned callback delegates to :meth:`_is_user_authorized` so the
full auth chain — platform allowlists, group allowlists, pairing
store, allow-all flags — stays the single source of truth.

``profile_name`` binds the callback to the secondary adapter's own
multiplex profile, so its ``SessionSource`` resolves that profile's
secret scope instead of falling back to the active profile.
"""
def check(
user_id: str,
Expand All @@ -9115,6 +9124,7 @@ def check(
chat_id=chat_id or "",
chat_type=chat_type or "group",
user_id=user_id,
profile=profile_name,
)
return self._is_user_authorized(source)
return check
Expand Down
70 changes: 61 additions & 9 deletions gateway/slash_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,12 +330,44 @@ async def _handle_reset_command(self, event: MessageEvent) -> Union[str, Ephemer
return EphemeralReply(f"{header}{_tip_line}")

async def _handle_profile_command(self, event: MessageEvent) -> str:
"""Handle /profile — show active profile name and home directory."""
"""Handle /profile — show the profile serving this source and its home.

On a multiplexed gateway the process-level active profile is always
the multiplexer's own (usually ``default``), so reporting it would
answer "default" in every chat regardless of which profile actually
serves the room/channel (``source.profile`` — stamped by the
``/p/<profile>/`` URL prefix, a per-credential adapter, or a room→
profile map). When ``multiplex_profiles`` is on, report the stamped
profile and, like the scoped /reset banner (#59003), resolve the
displayed home under that profile's runtime scope. When multiplexing
is off (the default) the stamp is ignored — mirroring the gating in
``_run_agent`` and ``_reset_notice_session_info`` — and the command
reports the active profile and default home, byte-identical to before.
"""
from hermes_constants import display_hermes_home
from hermes_cli.profiles import get_active_profile_name

display = display_hermes_home()
profile_name = get_active_profile_name()
multiplexed = getattr(
getattr(self, "config", None), "multiplex_profiles", False
)
source = getattr(event, "source", None)

profile_name = ""
if multiplexed:
profile_name = (getattr(source, "profile", "") or "").strip()
profile_name = profile_name or get_active_profile_name()

if multiplexed:
try:
from gateway.run import _profile_runtime_scope

profile_home = self._resolve_profile_home_for_source(source)
with _profile_runtime_scope(profile_home):
display = display_hermes_home()
except Exception:
display = display_hermes_home()
else:
display = display_hermes_home()

lines = [
t("gateway.profile.header", profile=profile_name),
Expand Down Expand Up @@ -1438,6 +1470,12 @@ async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
from hermes_cli.providers import get_label

raw_args = event.get_command_args().strip()
source = event.source
_command_profile_home = None
if getattr(getattr(self, "config", None), "multiplex_profiles", False):
_command_profile_home = getattr(
self, "_resolve_profile_home_for_source"
)(source)

# Parse --provider, --global, --session, and --refresh flags
(
Expand All @@ -1464,7 +1502,7 @@ async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
current_api_key = ""
user_provs = None
custom_provs = None
config_path = _hermes_home / "config.yaml"
config_path = (_command_profile_home or _hermes_home) / "config.yaml"
try:
cfg = _load_gateway_config()
if cfg:
Expand All @@ -1482,9 +1520,8 @@ async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
except Exception:
pass

# Check for session override
source = event.source
# Normalize the source the same way a normal message turn does
# Check for session override. Normalize the source the same way a normal
# message turn does
# (Telegram DM topic recovery) before deriving the override key, so
# the override is stored under the key the next message turn reads
# (#30479).
Expand All @@ -1500,7 +1537,7 @@ async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
# No args: show interactive picker (Telegram/Discord) or text list
if not model_input and not explicit_provider:
# Try interactive picker if the platform supports it
adapter = self.adapters.get(source.platform)
adapter = getattr(self, "_adapter_for_source")(source)
has_picker = (
adapter is not None
and getattr(type(adapter), "send_model_picker", None) is not None
Expand Down Expand Up @@ -1533,8 +1570,9 @@ async def _handle_model_command(self, event: MessageEvent) -> Optional[str]:
_cur_provider = current_provider
_cur_base_url = current_base_url
_cur_api_key = current_api_key
_picker_profile_home = _command_profile_home

async def _on_model_selected(
async def _on_model_selected_scoped(
_chat_id: str, model_id: str, provider_slug: str
) -> str:
"""Perform the model switch and return confirmation text."""
Expand Down Expand Up @@ -1733,6 +1771,20 @@ async def _on_model_selected(
lines.append(t("gateway.model.session_only_hint"))
return "\n".join(lines)

async def _on_model_selected(
_chat_id: str, model_id: str, provider_slug: str
) -> str:
if _picker_profile_home is None:
return await _on_model_selected_scoped(
_chat_id, model_id, provider_slug
)
from gateway.run import _profile_runtime_scope

with _profile_runtime_scope(_picker_profile_home):
return await _on_model_selected_scoped(
_chat_id, model_id, provider_slug
)

metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event))
result = await adapter.send_model_picker(
chat_id=source.chat_id,
Expand Down
Loading
Loading