Skip to content

The agent that grows with you

refactor(gateway): compact config/authz/pairing docs (keep WHYs), reflow env-step data rows

Tekniuma6bde733fb89
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index 82f5ce28afc..2d389006b17 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -1,11 +1,8 @@
-"""User-authorization methods for ``GatewayRunner``.
-
-Inbound-message authorization cluster: whether a user/chat may talk to the
+"""User-authorization mixin for ``GatewayRunner``: may this user/chat talk to the
agent, the per-adapter DM policy, and the unauthorized-DM behavior.
-``self.*`` calls resolve via the MRO. ``gateway.run`` is never imported at
-module import time (cycle); the one method that logs imports its ``logger``
-lazily so records keep the ``"gateway.run"`` logger name.
+``gateway.run`` is never imported at module import time (cycle); the one method
+that logs imports its ``logger`` lazily so records keep the ``"gateway.run"`` name.
"""
from __future__ import annotations
@@ -48,10 +45,9 @@ _ALLOW_BOTS_ENV = {
def _platform_gate_env(name: str, default: str = "") -> str:
"""Read an allow/deny gate env var with per-profile isolation.
- When a profile secret scope is installed AND multiplexing is active, a
- scoped miss returns ``default`` instead of falling through to
- ``os.environ``: the process env may hold ANOTHER profile's first-writer
- bridged value, so a fallthrough would leak allowlists across profiles.
+ With a profile secret scope installed AND multiplexing active, a scoped miss
+ returns ``default`` instead of falling through to ``os.environ``, which may
+ hold ANOTHER profile's first-writer bridged value (allowlist leak).
Single-profile deployments behave exactly like ``os.getenv``.
"""
if not name:
@@ -104,11 +100,8 @@ def _adapter_config_extra(adapter) -> dict:
return getattr(getattr(adapter, "config", None), "extra", None) or {}
-# ---------------------------------------------------------------------------
-# Nostr npub -> hex (Buzz). ``BUZZ_ALLOWED_USERS`` accepts hex or ``npub1…``
-# but inbound pubkeys are always hex, so npub entries must be decoded.
-# Pure stdlib; mirrors plugins/platforms/buzz/adapter.py.
-# ---------------------------------------------------------------------------
+# Nostr npub -> hex (Buzz): ``BUZZ_ALLOWED_USERS`` accepts hex or ``npub1…`` but
+# inbound pubkeys are always hex. Pure stdlib; mirrors plugins/platforms/buzz/adapter.py.
_BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
@@ -181,7 +174,7 @@ class GatewayAuthorizationMixin:
"""User/chat authorization methods for ``GatewayRunner``."""
# ``getattr(self, ...)`` throughout: test helpers build bare runners via
- # ``object.__new__`` without ``adapters`` / ``config`` (pitfalls.md #17).
+ # ``object.__new__`` without ``adapters`` / ``config``.
def _primary_adapters(self) -> dict:
return getattr(self, "adapters", None) or {}
@@ -191,14 +184,13 @@ class GatewayAuthorizationMixin:
platform: Optional[Platform],
profile: Optional[str] = None,
):
- """Resolve the live adapter whose intake policy should gate authorization.
-
- Secondary-profile adapters live in ``_profile_adapters[profile]``; the
- launched (primary) profile owns ``self.adapters``. ``_profile_adapters``
- is consulted BEFORE comparing against the active profile name: multiplex
- turns override ``HERMES_HOME`` so ``_active_profile_name()`` reports the
- secondary profile mid-turn, and treating it as primary would hand it the
- default bot (or default-deny secondary-only platforms like A2A).
+ """Live adapter whose intake policy gates authorization.
+
+ Secondary-profile adapters live in ``_profile_adapters[profile]``; the primary
+ profile owns ``self.adapters``. ``_profile_adapters`` is consulted BEFORE the
+ active profile name: multiplex turns override ``HERMES_HOME`` so
+ ``_active_profile_name()`` reports the secondary profile mid-turn, and treating
+ it as primary would hand it the default bot.
"""
if not platform:
return None
@@ -207,8 +199,7 @@ class GatewayAuthorizationMixin:
profile_adapters = getattr(self, "_profile_adapters", None) or {}
if profile_name in profile_adapters:
return profile_adapters[profile_name].get(platform)
- # Compare against the identity captured at construction, not the
- # per-turn HERMES_HOME-derived name.
+ # Identity captured at construction, not the per-turn HERMES_HOME-derived name.
primary_profile = getattr(self, "_primary_profile_name", None)
if not primary_profile:
active_profile_fn = getattr(self, "_active_profile_name", None)
@@ -219,9 +210,8 @@ class GatewayAuthorizationMixin:
primary_profile = None
if profile_name == primary_profile:
return self._primary_adapters().get(platform)
- # Fail closed: a stamped secondary profile with no registry entry
- # (adapter failed to connect) must NOT fall back to the default
- # profile's adapter -- that sends replies out the wrong bot.
+ # Fail closed: a secondary profile whose adapter failed to connect must NOT
+ # fall back to the default profile's adapter (replies out the wrong bot).
return None
return self._primary_adapters().get(platform)
@@ -232,11 +222,9 @@ class GatewayAuthorizationMixin:
transport_adapter = self._registered_transport_adapter(source)
if transport_adapter is not None:
return transport_adapter
- # Relay ingress keeps the underlying platform on the source (session
- # keys / display policy), but delivery must use the one process-level
- # RelayAdapter that owns the connector socket -- secondary profiles do
- # not register their own, so a profile-aware lookup would silently
- # disable streaming/typing/tool progress.
+ # Relay ingress keeps the underlying platform on the source, but delivery must
+ # use the one process-level RelayAdapter owning the connector socket; a
+ # profile-aware lookup would silently disable streaming/typing/tool progress.
if getattr(source, "delivered_via_upstream_relay", False) is True:
return self._primary_adapters().get(Platform.RELAY)
# ``getattr``: test fixtures build bare SimpleNamespace sources without ``profile``.
@@ -255,13 +243,12 @@ class GatewayAuthorizationMixin:
return False, None
def _registered_transport_adapter(self, source: SessionSource):
- """Return the registered adapter that created *source*, if retained.
+ """The registered adapter that created *source*, if retained.
- ``source.profile`` is the runtime/session namespace and may differ from
- the adapter profile when one shared credential serves several routed
- runtimes; ``build_source`` keeps the receiving adapter as in-process
- provenance so replies and intake-policy checks stay on that transport.
- Restored or hand-built sources fall back (fail-closed) to profile lookup.
+ ``source.profile`` may differ from the adapter profile when one shared credential
+ serves several routed runtimes; ``build_source`` keeps the receiving adapter as
+ provenance so replies stay on that transport. Restored/hand-built sources fall
+ back (fail-closed) to profile lookup.
"""
adapter_ref = getattr(source, "_transport_adapter_ref", None)
adapter = adapter_ref() if callable(adapter_ref) else None
@@ -292,13 +279,10 @@ class GatewayAuthorizationMixin:
*,
profile: Optional[str] = None,
) -> bool:
- """Whether the adapter delegates authz to a trusted authenticated upstream.
+ """Whether the adapter delegates authz to a trusted authenticated upstream (relay).
- Mirrors ``BasePlatformAdapter.authorization_is_upstream`` (True for the
- relay adapter: the connector authenticates the WS and resolves owner
- bindings before delivering). Unlike ``_adapter_enforces_own_access_policy``
- (a LOCAL policy only trusted when it is an allowlist) this UPSTREAM
- decision is honored directly. False when the adapter is unknown.
+ Unlike ``_adapter_enforces_own_access_policy`` (a LOCAL policy only trusted when
+ it is an allowlist) this UPSTREAM decision is honored directly. False when unknown.
"""
return self._adapter_flag(platform, "authorization_is_upstream", profile)
@@ -308,12 +292,10 @@ class GatewayAuthorizationMixin:
*,
profile: Optional[str] = None,
) -> bool:
- """Whether the adapter gates access at intake itself.
+ """Whether the adapter gates access at intake itself (WeCom, Weixin, Yuanbao, QQBot, WhatsApp).
- Mirrors ``BasePlatformAdapter.enforces_own_access_policy`` (WeCom, Weixin,
- Yuanbao, QQBot, WhatsApp). The flag alone is NOT "already authorized":
- these adapters default to ``open``, so ``_is_user_authorized`` only trusts
- them when the effective policy is an actual ``allowlist``.
+ The flag alone is NOT "already authorized": these adapters default to ``open``,
+ so ``_is_user_authorized`` only trusts them under an actual ``allowlist`` policy.
"""
return self._adapter_flag(platform, "enforces_own_access_policy", profile)
@@ -329,12 +311,8 @@ class GatewayAuthorizationMixin:
return extra if isinstance(extra, dict) else {}
def _adapter_setting(self, platform, attr: str, extra_key: str, profile):
- """Live adapter's resolved ``attr``, else ``config.extra[extra_key]``.
-
- The adapter value is preferred because it already folds in the
- ``<PLATFORM>_*`` env override, which is not always bridged back into
- ``config.extra``; the extra fallback serves bare runners with no adapter.
- """
+ """Live adapter's resolved ``attr`` (folds in the ``<PLATFORM>_*`` env override),
+ else ``config.extra[extra_key]`` for bare runners with no adapter."""
adapter = self._authorization_adapter(platform, profile)
value = getattr(adapter, attr, None) if adapter is not None else None
if value is None:
@@ -352,12 +330,7 @@ class GatewayAuthorizationMixin:
*,
profile: Optional[str] = None,
) -> str:
- """Lowercased effective ``dm_policy`` (open/allowlist/disabled/pairing), ``""`` if unknown.
-
- "Reached the gateway" only carries an authorization signal in the
- ``allowlist`` case; ``open`` forwards everyone and ``pairing`` forwards
- unpaired DMs for the handshake.
- """
+ """Lowercased effective ``dm_policy`` (open/allowlist/disabled/pairing), ``""`` if unknown."""
return self._adapter_policy(platform, "_dm_policy", "dm_policy", profile)
def _adapter_group_policy(
@@ -378,9 +351,8 @@ class GatewayAuthorizationMixin:
) -> bool:
"""Whether a per-group sender allowlist (WeCom ``groups.<id>.allow_from``) gated this message.
- A group may be open at the chat level while restricting senders; if such
- a message reached the gateway the adapter already checked that sender
- allowlist, so it is a trustworthy intake decision.
+ A group may be open at the chat level while restricting senders; reaching the
+ gateway then means the adapter already checked that list.
"""
if not platform or not chat_id:
return False
@@ -422,10 +394,8 @@ class GatewayAuthorizationMixin:
Trusted only when the effective policy for THIS chat type is ``allowlist``:
``open`` forwards EVERY sender (the fail-open SECURITY.md §2.6 forbids),
- ``disabled`` never forwards, ``pairing`` forwards unpaired DMs for the
- handshake (already denied by the pairing-store check). Anything else falls
- through to default-deny; GATEWAY_ALLOW_ALL_USERS, the per-platform
- ALLOW_ALL flag and pairing stay the explicit opt-ins.
+ ``disabled`` never forwards, ``pairing`` forwards unpaired DMs for the handshake
+ (already denied by the pairing-store check). Anything else → default-deny.
"""
if is_group:
if self._adapter_group_has_sender_allowlist(source.platform, source.chat_id, profile=adapter_profile):
@@ -435,11 +405,9 @@ class GatewayAuthorizationMixin:
effective_policy = self._adapter_dm_policy(source.platform, profile=adapter_profile)
if effective_policy != "allowlist":
return None
- # Re-check DMs against the live adapter when it exposes ``_is_dm_allowed``:
- # pairing revoke can clear WHATSAPP_ALLOWED_USERS while a construction-time
- # ``_allow_from`` snapshot would keep authorizing until restart. Adapters
- # without the helper keep the historical "reached the gateway under
- # allowlist policy" rubber-stamp.
+ # Re-check DMs via the live adapter's ``_is_dm_allowed`` when present: pairing
+ # revoke can clear WHATSAPP_ALLOWED_USERS while a construction-time snapshot
+ # would keep authorizing until restart. Others keep the historical rubber-stamp.
if not is_group:
adapter = self._authorization_adapter(source.platform, profile=adapter_profile)
dm_check = getattr(adapter, "_is_dm_allowed", None) if adapter is not None else None
@@ -456,10 +424,9 @@ class GatewayAuthorizationMixin:
extra = _adapter_config_extra(adapter)
adapter_allow = extra.get("group_allow_from" if is_group else "allow_from")
if not adapter_allow:
- # Plugin platforms (Buzz, DingTalk, ...) document ``extra.allowed_users`` as
- # the config-file spelling of their env allowlist. Under multiplex the
- # YAML->env bridge is first-writer-wins, so only the default profile's list
- # reaches the env read; consult the live profile-routed adapter instead.
+ # Plugin platforms (Buzz, DingTalk) spell their env allowlist as
+ # ``extra.allowed_users``; under multiplex only the default profile's list
+ # reaches the env (first-writer-wins bridge), so read the live adapter's.
entry = _registry_entry(source.platform)
if entry and entry.allowed_users_env:
adapter_allow = extra.get("allowed_users")
@@ -478,16 +445,14 @@ class GatewayAuthorizationMixin:
*,
allow_adapter_delegation: bool = True,
) -> bool:
- """Check if a user is authorized to use the bot.
+ """Whether a user may use the bot.
Order: trusted-upstream delegation, chat-scoped group allowlists,
- ``{PLATFORM}_ALLOW_BOTS``, per-platform allow-all, adapter role auth,
- pairing store, env/config allowlists, ``GATEWAY_ALLOW_ALL_USERS``,
- default deny.
+ ``{PLATFORM}_ALLOW_BOTS``, per-platform allow-all, adapter role auth, pairing
+ store, env/config allowlists, ``GATEWAY_ALLOW_ALL_USERS``, default deny.
"""
from gateway.run import logger
- # HA events are system-generated (HASS_TOKEN authenticates the
- # connection); webhook events are HMAC-verified in the adapter.
+ # HA events are system-generated (HASS_TOKEN); webhook events are HMAC-verified.
if source.platform in {Platform.HOMEASSISTANT, Platform.WEBHOOK}:
return True
@@ -495,16 +460,12 @@ class GatewayAuthorizationMixin:
is_group = source.chat_type in _GROUP_CHAT_TYPES
is_group_or_forum = source.chat_type in _GROUP_FORUM_TYPES
- # Trusted-upstream delegation (relay): the Team Gateway connector
- # authenticates this gateway's WS and resolves owner-only author
- # bindings BEFORE delivering, so the event is already authorized and
- # there is no local RELAY_ALLOWED_USERS to consult. Not a fail-open: it
- # fires only for events actually delivered over the authenticated relay
- # WS (transport stamps ``delivered_via_upstream_relay``) or whose
- # adapter declares ``authorization_is_upstream=True``. The delivery
- # marker is PRIMARY because a relayed message carries the UNDERLYING
- # platform (discord/...), not ``Platform.RELAY``; the adapter-flag check
- # covers events whose platform IS RELAY (interaction passthrough).
+ # Trusted-upstream delegation (relay): the connector authenticates this
+ # gateway's WS and resolves owner bindings BEFORE delivering, so there is no
+ # local RELAY_ALLOWED_USERS. Not a fail-open: fires only for events actually
+ # delivered over the relay WS (``delivered_via_upstream_relay``) or whose adapter
+ # declares ``authorization_is_upstream``. The delivery marker is PRIMARY because
+ # a relayed message carries the UNDERLYING platform, not ``Platform.RELAY``.
# ``is True``: a MagicMock stand-in must not auto-truthy into authz.
if allow_adapter_delegation and (
source.delivered_via_upstream_relay is True
@@ -514,19 +475,16 @@ class GatewayAuthorizationMixin:
user_id = source.user_id
- # Chat-scoped group allowlists (TELEGRAM_GROUP_ALLOWED_CHATS /
- # QQ_GROUP_ALLOWED_USERS) must work with ``user_id is None`` (anonymous
- # admins, sender_chat posts, channel broadcasts), so they run before
- # the no-user-id guard.
+ # Chat-scoped group allowlists must work with ``user_id is None`` (anonymous
+ # admins, sender_chat posts, channel broadcasts): run before the no-user-id guard.
if is_group and source.chat_id:
chat_allowlist_env = _GROUP_CHAT_ENV.get(source.platform, "")
if chat_allowlist_env and _allows(
_coerce_allow_set(_platform_gate_env(chat_allowlist_env)), source.chat_id
):
return True
- # config.yaml fallback (``extra.group_allowed_chats``): Telegram
- # observe-unmentioned mode strips user_id from triggered group
- # messages, so the env-only check above misses config allowlists.
+ # config.yaml fallback (``extra.group_allowed_chats``): Telegram observe-
+ # unmentioned mode strips user_id, so the env-only check above misses it.
try:
adapter_group_allowed = self._adapter_extra_for_source(source).get("group_allowed_chats")
if adapter_group_allowed and _allows(_coerce_allow_set(adapter_group_allowed), source.chat_id):
@@ -534,9 +492,8 @@ class GatewayAuthorizationMixin:
except Exception:
pass
- # Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist.
- # Also before the no-user-id guard: Slack Workflow Builder posts arrive
- # as bot_message with user=None.
+ # Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist. Also before
+ # the no-user-id guard: Slack Workflow Builder posts arrive with user=None.
if getattr(source, "is_bot", False):
allow_bots_var = _ALLOW_BOTS_ENV.get(source.platform)
if allow_bots_var and _platform_gate_env(allow_bots_var, "none").lower().strip() in {"mentions", "all"}:
@@ -558,15 +515,12 @@ class GatewayAuthorizationMixin:
if platform_allow_all_var and _env_truthy(platform_allow_all_var):
return True
- # Adapter-verified role auth (Discord confirmed DISCORD_ALLOWED_ROLES
- # before dispatch). ``is True`` so a MagicMock source cannot pass.
+ # Adapter-verified role auth (Discord DISCORD_ALLOWED_ROLES). ``is True``: no MagicMock pass.
if allow_adapter_delegation and getattr(source, "role_authorized", False) is True:
return True
- # Pairing store: a first-class grant created only by a trusted operator
- # approving a code (inbound senders can never reach approve_code).
- # Honored as a UNION with the allowlist; approval also mirrors the user
- # into a configured allowlist (PairingStore._approve_user).
+ # Pairing store: a first-class grant created only by an operator approving a
+ # code. Honored as a UNION with the allowlist (approval also mirrors into it).
platform_name = source.platform.value if source.platform else ""
pairing_store = self._pairing_store_for(source)
if pairing_store is not None and pairing_store.is_approved(platform_name, user_id):
@@ -600,9 +554,8 @@ class GatewayAuthorizationMixin:
):
return True
- # Backward-compat: TELEGRAM_GROUP_ALLOWED_USERS was once (mis)used as a
- # chat-ID allowlist. "-"-prefixed values are chat IDs, so honor them as
- # such and warn once; the correct var is TELEGRAM_GROUP_ALLOWED_CHATS.
+ # Backward-compat: TELEGRAM_GROUP_ALLOWED_USERS was once (mis)used as a chat-ID
+ # allowlist; "-"-prefixed values are chat IDs, honor them and warn once.
if source.platform == Platform.TELEGRAM and group_user_allowlist and is_group_or_forum and source.chat_id:
legacy_chat_ids = {
v.strip() for v in group_user_allowlist.split(",") if v.strip().startswith("-")
@@ -620,24 +573,19 @@ class GatewayAuthorizationMixin:
if source.chat_id in legacy_chat_ids:
return True
- # In group/forum chats TELEGRAM_GROUP_ALLOWED_USERS is the scoped
- # allowlist and does not imply DM access; TELEGRAM_ALLOWED_USERS is
- # platform-wide and works everywhere.
+ # TELEGRAM_GROUP_ALLOWED_USERS is group-scoped (no DM access); TELEGRAM_ALLOWED_USERS is platform-wide.
allowed_ids = (
_coerce_allow_set(platform_allowlist)
| _coerce_allow_set(group_user_allowlist)
| _coerce_allow_set(global_allowlist)
)
- # Adapters that resolve username-shaped entries to numeric IDs at
- # connect time (Discord) keep the resolved set in memory; the per-turn
- # .env hot-reload restores the RAW usernames into the env, so from the
- # second turn on ``platform_allowlist`` holds usernames while user_id is
- # numeric. Union in the adapter's resolved IDs. Never a widening: the
- # empty-allowlist branch already returned and adapters only resolve
- # operator-written entries. Guarded on ``platform_allowlist`` so
- # group/global-only configs never consult adapter memory; duck-typed +
- # type-checked so mock adapters cannot auto-truthy in.
+ # Adapters resolving username entries to numeric IDs at connect time (Discord)
+ # keep the set in memory; the per-turn .env hot-reload restores RAW usernames,
+ # so union in the adapter's resolved IDs. Never a widening: the empty-allowlist
+ # branch already returned and adapters only resolve operator-written entries.
+ # Guarded on ``platform_allowlist`` so group/global-only configs never consult
+ # adapter memory; type-checked so mock adapters cannot auto-truthy in.
if platform_allowlist:
try:
adapter = self._adapter_for_source(source)
@@ -663,8 +611,7 @@ class GatewayAuthorizationMixin:
if "@" in user_id:
check_ids.add(user_id.split("@")[0])
- # WhatsApp (Baileys + Cloud): resolve phone<->LID / JID aliases so
- # device-suffix and bare-phone entries match the same principal.
+ # WhatsApp (Baileys + Cloud): phone<->LID / JID aliases match the same principal.
if source.platform in {Platform.WHATSAPP, Platform.WHATSAPP_CLOUD}:
normalized_allowed_ids = set()
for allowed_id in allowed_ids:
@@ -679,9 +626,7 @@ class GatewayAuthorizationMixin:
platform_value = source.platform.value if source.platform is not None else None
- # SimpleX: user_id is the numeric contactId (stable across renames) but
- # the UI only surfaces display names, so match both. Plugin platform:
- # compare by value.
+ # SimpleX: user_id is the numeric contactId but the UI only shows display names.
if platform_value == "simplex" and source.user_name:
check_ids.add(source.user_name)
@@ -701,18 +646,12 @@ class GatewayAuthorizationMixin:
*,
profile: Optional[str] = None,
) -> str:
- """Return how unauthorized DMs should be handled for a platform.
-
- Resolution order:
- 1. Explicit per-platform ``unauthorized_dm_behavior`` in config.
- 2. Email -> ``"ignore"`` (inboxes hold arbitrary human mail; pairing
- codes are not a safe default; matches GatewayConfig).
- 3. Explicit (non-default) global ``unauthorized_dm_behavior``.
- 4. Adapter dm_policy: ``pairing`` -> ``"pair"``; ``allowlist`` /
- ``disabled`` -> ``"ignore"``.
- 5. Any configured allowlist -> ``"ignore"`` (the operator restricted
- access; spamming unknown contacts with codes is noisy and leaks).
- 6. Otherwise ``"pair"`` (open-gateway default).
+ """How unauthorized DMs are handled ("pair" / "ignore") for a platform.
+
+ Order: explicit per-platform config; Email → "ignore" (inboxes hold arbitrary
+ mail); explicit non-default global; adapter dm_policy (pairing → "pair",
+ allowlist/disabled → "ignore"); any configured allowlist → "ignore" (spamming
+ unknown contacts with codes is noisy and leaks); else "pair".
"""
config = getattr(self, "config", None)
diff --git a/gateway/config.py b/gateway/config.py
index 9923ccba4fe..8af098d5bd9 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -40,12 +40,8 @@ def _coerce_bool(value: Any, default: bool = True) -> bool:
def _normalize_multiplex_profile_allowlist(value: Any) -> Optional[List[str]]:
- """Normalize the optional named-profile allowlist.
-
- ``None`` preserves the historical serve-all behavior. A malformed outer
- value fails safe to an empty list (default profile only); malformed list
- entries are skipped with a warning.
- """
+ """Normalize the optional named-profile allowlist: ``None`` = serve all; a malformed
+ outer value fails safe to ``[]`` (default profile only); bad entries are skipped."""
if value is None:
return None
if not isinstance(value, list):
@@ -96,20 +92,15 @@ def _env_multiplex_profiles_override() -> "bool | None":
logger.warning(
"Ignoring unrecognized GATEWAY_MULTIPLEX_PROFILES=%r "
"(expected one of %s or %s); falling back to config.yaml.",
- raw,
- sorted(_TRUTHY_STRINGS),
- sorted(_FALSY_STRINGS),
+ raw, sorted(_TRUTHY_STRINGS), sorted(_FALSY_STRINGS),
)
return None
def _normalize_transport_token(value: Any) -> str:
- """Canonical streaming transport token.
-
- YAML 1.1 parses bare ``on``/``off`` as booleans, so ``mode: off`` arrives as
- ``False``; stringifying would yield ``"false"`` and enable streaming. Booleans
- map to ``"auto"`` / ``"off"``; anything else lower-cases, default ``"auto"``.
- """
+ """Canonical streaming transport token. YAML 1.1 parses bare ``on``/``off`` as
+ booleans (``mode: off`` → ``False`` → ``"false"`` would ENABLE streaming), so
+ booleans map to ``"auto"``/``"off"``; anything else lower-cases, default ``"auto"``."""
if value is None:
return "auto"
if isinstance(value, bool):
@@ -158,11 +149,8 @@ _SYSTEMD_WATCHDOG_MAX_SECONDS = 2_147_483_647
def coerce_systemd_watchdog_seconds(
value: Any, key: str = "gateway.systemd_watchdog_seconds"
) -> int:
- """Bounded positive watchdog interval, or zero when disabled/invalid.
-
- Runtime and service generation share this normalization so a value can
- never enable ``Type=notify`` while disabling application heartbeats.
- """
+ """Bounded positive watchdog interval, or zero when disabled/invalid. Shared by runtime
+ and service generation so a value can never enable ``Type=notify`` without heartbeats."""
if value is None:
return 0
parsed: Optional[int] = None
@@ -181,11 +169,7 @@ def coerce_systemd_watchdog_seconds(
if parsed == 0:
return 0
if not 0 < parsed <= _SYSTEMD_WATCHDOG_MAX_SECONDS:
- logger.warning(
- "Ignoring invalid %s (expected an integer from 1 to %d)",
- key,
- _SYSTEMD_WATCHDOG_MAX_SECONDS,
- )
+ logger.warning("Ignoring invalid %s (expected an integer from 1 to %d)", key, _SYSTEMD_WATCHDOG_MAX_SECONDS)
return 0
return parsed
@@ -213,11 +197,8 @@ def _dict_slot(container: dict, key: str) -> dict:
def _getenv(name: str, default: Optional[str] = None) -> Optional[str]:
- """Read env vars through the active profile secret scope when present.
-
- Multiplexed profile startup installs per-profile secrets, which must win;
- outside a scope keep legacy ``os.getenv`` behavior.
- """
+ """Env read through the active profile secret scope when present (multiplexed
+ per-profile secrets must win); otherwise legacy ``os.getenv``."""
if current_secret_scope() is not None:
scope_val = _get_secret(name, None)
return scope_val if scope_val is not None else default
@@ -234,12 +215,8 @@ _Platform__bundled_plugin_names: Optional[set] = None
class Platform(Enum):
- """Supported messaging platforms.
-
- Built-ins are explicit members. Plugin platforms are dynamic members created
- on demand by ``_missing_`` and cached in ``_value2member_map_`` so
- ``Platform("irc") is Platform("irc")`` holds.
- """
+ """Supported messaging platforms. Plugin platforms are dynamic members created on
+ demand by ``_missing_`` and cached so ``Platform("irc") is Platform("irc")`` holds."""
LOCAL = "local"
TELEGRAM = "telegram"
DISCORD = "discord"
@@ -299,36 +276,31 @@ class Platform(Enum):
@classmethod
def _scan_bundled_plugin_platforms(cls) -> set:
"""Names of bundled platform plugins under ``plugins/platforms/``."""
- names: set = set()
try:
platforms_dir = Path(__file__).parent.parent / "plugins" / "platforms"
- if platforms_dir.is_dir():
- for child in platforms_dir.iterdir():
- if child.is_dir() and (child / "__init__.py").exists() and (
- (child / "plugin.yaml").exists() or (child / "plugin.yml").exists()
- ):
- names.add(child.name.lower())
+ return {
+ child.name.lower()
+ for child in (platforms_dir.iterdir() if platforms_dir.is_dir() else ())
+ if child.is_dir() and (child / "__init__.py").exists()
+ and ((child / "plugin.yaml").exists() or (child / "plugin.yml").exists())
+ }
except Exception:
- pass
- return names
+ return set()
# Built-in values snapshotted before any dynamic _missing_ lookup.
_BUILTIN_PLATFORM_VALUES = frozenset(m.value for m in Platform.__members__.values())
-# Platforms that bind a host TCP port. In a profile multiplexer only the default
-# profile owns the shared listener (served via /p/<profile>/), so a SECONDARY
-# profile enabling one of these is always a misconfiguration. Single source of
-# truth for gateway/run.py startup validation and the dashboard's pre-write
-# validation (hermes_cli/web_server.py). Platform .value strings.
+# Platforms that bind a host TCP port. In a multiplexer only the default profile owns
+# the shared listener, so a SECONDARY profile enabling one is a misconfiguration.
+# Single source of truth for gateway/run.py and hermes_cli/web_server.py validation.
PORT_BINDING_PLATFORM_VALUES = frozenset({
"webhook", "api_server", "msgraph_webhook", "feishu", "wecom_callback",
"bluebubbles", "sms", "whatsapp_cloud", "line", "teams",
})
-# Platforms that only bind in one connection mode: Feishu's default websocket
-# mode is an outbound long connection. platform value → the mode that binds.
+# Platforms that only bind in one connection mode (Feishu's default websocket mode is outbound).
PORT_BINDING_CONDITIONAL_MODES: dict[str, str] = {
"feishu": "webhook",
}
@@ -347,41 +319,26 @@ def platform_binds_port(platform_value: str, extra: Optional[dict] = None) -> bo
@dataclass
class HomeChannel:
- """Default destination for a platform (``deliver="telegram"`` without a chat ID).
-
- Thread-aware platforms may store a thread/topic ID so the bare platform
- target routes to the conversation where /sethome was run.
- """
+ """Default destination for a platform (``deliver="telegram"`` without a chat ID);
+ ``thread_id`` routes the bare target to the topic where /sethome was run."""
platform: Platform
chat_id: str
name: str
thread_id: Optional[str] = None
- # Authenticated logical-target provenance observed by a platform adapter.
- # Relay egress re-attaches these; the connector remains the authorization
- # boundary and resolves them against its authoritative stores.
+ # Authenticated logical-target provenance; relay egress re-attaches these but the
+ # connector remains the authorization boundary.
user_id: Optional[str] = None
scope_id: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
- result = {
- "platform": self.platform.value,
- "chat_id": self.chat_id,
- "name": self.name,
- }
- for key in ("thread_id", "user_id", "scope_id"):
- if getattr(self, key):
- result[key] = getattr(self, key)
+ result = {"platform": self.platform.value, "chat_id": self.chat_id, "name": self.name}
+ result.update({k: v for k in ("thread_id", "user_id", "scope_id") if (v := getattr(self, k))})
return result
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "HomeChannel":
optional = {k: str(data[k]) if data.get(k) else None for k in ("thread_id", "user_id", "scope_id")}
- return cls(
- platform=Platform(data["platform"]),
- chat_id=str(data["chat_id"]),
- name=data.get("name", "Home"),
- **optional,
- )
+ return cls(platform=Platform(data["platform"]), chat_id=str(data["chat_id"]), name=data.get("name", "Home"), **optional)
def persist_home_channel(home: HomeChannel, *, enabled_if_new: bool = False) -> None:
@@ -398,21 +355,15 @@ def persist_home_channel(home: HomeChannel, *, enabled_if_new: bool = False) ->
@dataclass
class SessionResetPolicy:
- """Controls when sessions reset (lose context).
-
- Modes: "daily" (at ``at_hour``), "idle" (after ``idle_minutes``), "both"
- (whichever first), "none" (never; context managed only by compression).
- Default "none": sessions never auto-reset unless the user opts in via
- ``session_reset`` in config.yaml (or gateway.json).
- """
+ """When sessions reset: "daily" (at ``at_hour``), "idle" (after ``idle_minutes``),
+ "both" (whichever first), "none" (default: only compression manages context)."""
mode: str = "none"
at_hour: int = 4 # 0-23, local time
idle_minutes: int = 1440
notify: bool = True # Notify the user when auto-reset occurs
notify_exclude_platforms: tuple = ("api_server", "webhook")
- # A background process this many hours old no longer blocks idle/daily reset
- # (a forgotten preview server must not pin a session forever). The process
- # is NOT killed — only ignored by the reset guard.
+ # A background process this old no longer blocks reset (a forgotten preview server
+ # must not pin a session forever); it is NOT killed, only ignored by the guard.
bg_process_max_age_hours: int = 24
def to_dict(self) -> Dict[str, Any]:
@@ -452,18 +403,12 @@ class ChannelOverride:
def from_dict(cls, data: Dict[str, Any]) -> "ChannelOverride":
if not data:
return cls()
- return cls(
- model=data.get("model"),
- provider=data.get("provider"),
- system_prompt=data.get("system_prompt"),
- )
+ return cls(model=data.get("model"), provider=data.get("provider"), system_prompt=data.get("system_prompt"))
-# Platforms whose primary credential is ``PlatformConfig.token`` and the env var it
-# loads from: drives empty-token warnings at validation and the multiplex
-# primary-startup credential gate in ``gateway.run``. Platforms absent here
-# authenticate another way (session files, webhooks, api_key) and must never be
-# skipped for a missing token.
+# Platforms whose primary credential is ``PlatformConfig.token`` → its env var (empty-token
+# warnings; multiplex primary-startup gate in ``gateway.run``). Platforms absent here
+# authenticate another way and must never be skipped for a missing token.
PLATFORM_TOKEN_ENV_NAMES: dict["Platform", str] = {
Platform.TELEGRAM: "TELEGRAM_BOT_TOKEN",
Platform.DISCORD: "DISCORD_BOT_TOKEN",
@@ -483,16 +428,13 @@ class PlatformConfig:
home_channel: Optional[HomeChannel] = None
# Reply threading: "off" never threads, "first" threads only the first chunk, "all" every chunk.
reply_to_mode: str = "first"
- # "♻️ Gateway online/restarted" lifecycle pings. Set False on end-user
- # platforms (e.g. Slack) where operator-flavored notices are noise.
+ # "♻️ Gateway online/restarted" pings; False on end-user platforms where they are noise.
gateway_restart_notification: bool = True
- # "typing…" / "is thinking…" indicator while the agent works (drives the
- # _keep_typing loop in gateway/platforms/base.py). Set False where it is
- # unwanted, e.g. Slack's setStatus disables the compose box.
+ # "typing…" indicator (drives _keep_typing in platforms/base.py); False where unwanted
+ # (Slack's setStatus disables the compose box).
typing_indicator: bool = True
- # Custom working-state text for platforms whose indicator renders text (Slack
- # assistant status — needs assistant:write; Google Chat marker message). None
- # keeps each platform's built-in default; textless indicators ignore it.
+ # Working-state text for text-rendering indicators (Slack assistant status, Google
+ # Chat marker); None = platform default; textless indicators ignore it.
typing_status_text: Optional[str] = None
channel_overrides: Dict[str, ChannelOverride] = field(default_factory=dict)
extra: Dict[str, Any] = field(default_factory=dict) # Platform-specific settings
@@ -514,9 +456,7 @@ class PlatformConfig:
if self.home_channel:
result["home_channel"] = self.home_channel.to_dict()
if self.channel_overrides:
- result["channel_overrides"] = {
- cid: ov.to_dict() for cid, ov in self.channel_overrides.items()
- }
+ result["channel_overrides"] = {cid: ov.to_dict() for cid, ov in self.channel_overrides.items()}
return result
@classmethod
@@ -526,8 +466,7 @@ class PlatformConfig:
if isinstance(data.get("home_channel"), dict):
home_channel = HomeChannel.from_dict(data["home_channel"])
- # gateway_restart_notification / typing_indicator / typing_status_text may be
- # top-level or bridged into ``extra`` by the shared-key loop; top-level wins.
+ # The typing/restart-notification keys may be top-level or bridged into ``extra``; top-level wins.
extra = _coerce_dict(data.get("extra", {}))
def toplevel_or_extra(key: str) -> Any:
@@ -555,9 +494,8 @@ class PlatformConfig:
)
-# Streaming defaults shared by StreamingConfig and StreamConsumerConfig. Tuned for
-# Telegram's ~1 edit/s flood envelope: a touch under 1s breathes without hitting
-# rate limits; the small buffer threshold makes short DM replies feel instant.
+# Shared by StreamingConfig and StreamConsumerConfig. Tuned for Telegram's ~1 edit/s
+# flood envelope; the small buffer threshold makes short DM replies feel instant.
DEFAULT_STREAMING_EDIT_INTERVAL: float = 0.8
DEFAULT_STREAMING_BUFFER_THRESHOLD: int = 24
DEFAULT_STREAMING_CURSOR: str = " ▉"
@@ -567,18 +505,15 @@ DEFAULT_STREAMING_CURSOR: str = " ▉"
class StreamingConfig:
"""Real-time token streaming to messaging platforms."""
enabled: bool = False
- # Transport: "auto" prefers native draft updates (Telegram sendMessageDraft,
- # Bot API 9.5+) and falls back to edit-based; "draft" requests drafts with
- # edit fallback; "edit" is progressive editMessageText only; "off" disables.
- # "auto" is safe globally: adapters without draft support report
- # supports_draft_streaming() == False and use the edit path unchanged.
+ # "auto" prefers native drafts (Telegram sendMessageDraft) with edit fallback — safe
+ # globally since adapters without draft support use the edit path unchanged;
+ # "draft" / "edit" force one; "off" disables.
transport: str = "auto"
edit_interval: float = DEFAULT_STREAMING_EDIT_INTERVAL
buffer_threshold: int = DEFAULT_STREAMING_BUFFER_THRESHOLD
cursor: str = DEFAULT_STREAMING_CURSOR
- # When >0, the final edit of a long stream is delivered as a fresh message if
- # the preview has been visible at least this many seconds, so the visible
- # timestamp reflects completion. Telegram only; 0 disables.
+ # >0: deliver the final edit as a fresh message when the preview has been visible
+ # this long, so the timestamp reflects completion. Telegram only; 0 disables.
fresh_final_after_seconds: float = 0.0
def to_dict(self) -> Dict[str, Any]:
@@ -589,10 +524,9 @@ class StreamingConfig:
if not isinstance(data, dict) or not data:
return cls()
- # ``mode`` is a transport alias that ALSO implies ``enabled`` (``mode: off``
- # disables); an explicit ``enabled`` key always wins. A bare ``transport``
- # does NOT imply enabled: ``streaming.enabled`` is the documented master
- # switch, so ``transport`` only selects HOW to stream once it is on.
+ # ``mode`` is a transport alias that ALSO implies ``enabled`` (``mode: off`` disables;
+ # explicit ``enabled`` wins). A bare ``transport`` does NOT imply enabled:
+ # ``streaming.enabled`` is the documented master switch.
raw_transport = data.get("transport")
raw_mode = data.get("mode")
transport = _normalize_transport_token(raw_transport if raw_transport is not None else raw_mode)
@@ -615,11 +549,8 @@ class StreamingConfig:
def _has_usable_api_server_key(key: object) -> bool:
- """True when API_SERVER_KEY is strong enough for the adapter to start.
-
- Mirrors the startup guard in ``gateway/platforms/api_server.py``
- (``has_usable_secret`` with ``min_length=16``).
- """
+ """True when API_SERVER_KEY is strong enough for the adapter to start (mirrors the
+ ``has_usable_secret(min_length=16)`` guard in ``gateway/platforms/api_server.py``)."""
if not key:
return False
try:
@@ -633,9 +564,8 @@ def _needs_extra(*keys: str) -> Callable[[PlatformConfig], bool]:
return lambda cfg: all(cfg.extra.get(k) for k in keys)
-# Built-in "is this platform sufficiently configured?" checks by PlatformConfig.
-# Platforms covered by the generic ``token or api_key`` check (Telegram, Discord,
-# Slack, Matrix, Mattermost, HomeAssistant) need no entry.
+# Built-in "sufficiently configured?" checks; platforms covered by the generic
+# ``token or api_key`` check (Telegram, Discord, Slack, Matrix, ...) need no entry.
_PLATFORM_CONNECTED_CHECKERS: dict[Platform, Callable[[PlatformConfig], bool]] = {
Platform.WEIXIN: lambda cfg: bool(cfg.extra.get("account_id") and (cfg.token or cfg.extra.get("token"))),
Platform.WHATSAPP_CLOUD: _needs_extra("phone_number_id", "access_token"),
@@ -646,8 +576,7 @@ _PLATFORM_CONNECTED_CHECKERS: dict[Platform, Callable[[PlatformConfig], bool]] =
Platform.BLUEBUBBLES: _needs_extra("server_url", "password"),
Platform.QQBOT: _needs_extra("app_id", "client_secret"),
Platform.YUANBAO: _needs_extra("app_id", "app_secret"),
- # Relay dials OUT to a connector: "connected" once an endpoint URL is configured
- # (capabilities are negotiated at handshake). EXPERIMENTAL.
+ # Relay dials OUT: "connected" once an endpoint URL is configured. EXPERIMENTAL.
Platform.RELAY: lambda cfg: bool(cfg.extra.get("relay_url") or cfg.extra.get("url")),
}
@@ -663,48 +592,41 @@ class GatewayConfig:
# Slash commands that bypass the agent loop.
quick_commands: Dict[str, Any] = field(default_factory=dict)
sessions_dir: Path = field(default_factory=lambda: get_hermes_home() / "sessions")
- # Keep writing the legacy sessions.json mirror of the routing index (primary
- # copy: state.db gateway_routing). Default True for external tooling and
- # downgrade safety.
+ # Keep the legacy sessions.json mirror of the routing index (primary: state.db)
+ # for external tooling and downgrade safety.
write_sessions_json: bool = True
always_log_local: bool = True # Always save cron outputs to local files
- # Drop outbound "silence narration" (*(silent)*, 🔇, a bare ".") pre-send:
- # model hallucinations that ping-pong in bot-to-bot channels. Substrate-level
- # guard that survives SOUL.md/prompt drift; False = raw passthrough.
+ # Drop outbound "silence narration" (*(silent)*, 🔇, a bare ".") that ping-pongs in
+ # bot-to-bot channels; a substrate guard that survives prompt drift.
filter_silence_narration: bool = True
stt_enabled: bool = True # Auto-transcribe inbound voice messages
stt_echo_transcripts: bool = True # Echo raw STT transcripts back to the user
group_sessions_per_user: bool = True # Isolate group sessions per participant when user IDs exist
thread_sessions_per_user: bool = False # False = threads shared across participants
max_concurrent_sessions: Optional[int] = None # Positive int caps simultaneous active sessions
- # Opt-in: the default profile's gateway serves inbound messages for every
- # profile on the host (profiles stamped into session keys, per-profile
- # adapters/credentials). False = single HERMES_HOME, no profile stamping.
+ # Opt-in: the default profile's gateway serves every profile on the host
+ # (profiles stamped into session keys, per-profile adapters/credentials).
multiplex_profiles: bool = False
# None = historical serve-all; [] = default profile only.
multiplex_profile_allowlist: Optional[List[str]] = None
- # Public HTTPS endpoint for scoped RoomLink calls. Disabled by default: an API
- # key alone must never advertise a route. HERMES_ROOM_LINK_URL overrides.
+ # Public HTTPS endpoint for scoped RoomLink calls; an API key alone must never
+ # advertise a route. HERMES_ROOM_LINK_URL overrides.
room_link_url: Optional[str] = None
# Opt-in systemd event-loop watchdog; zero keeps Type=simple and disables sd_notify.
systemd_watchdog_seconds: int = 0
- # In-process event-loop liveness watchdog: a daemon thread probes the loop
- # with call_soon_threadsafe; after consecutive misses it dumps all-thread
- # stacks and hard-exits with the service-restart code. The knobs (seconds)
- # tolerate transient self-recovering stalls (adapter reconnect doing sync
- # socket I/O) so a short block does not force exit code 75 and restart
- # churn that stalls cron; a genuine wedge still escalates.
+ # In-process loop liveness watchdog: after consecutive missed probes it dumps
+ # all-thread stacks and hard-exits with the service-restart code. The knobs
+ # tolerate transient self-recovering stalls (adapter reconnect doing sync socket
+ # I/O) so a short block does not cause restart churn; a genuine wedge still escalates.
loop_watchdog: bool = True
loop_watchdog_probe_interval_s: float = DEFAULT_LOOP_WATCHDOG_INTERVAL_S
loop_watchdog_probe_timeout_s: float = DEFAULT_LOOP_WATCHDOG_TIMEOUT_S
- # Default 3 (~90-120s sustained block): the false-positive class (the
- # watchdog's own on-loop heartbeat fsync) is fixed at the root by the off-loop
- # write + two-witness probe, so raising this would only delay recovery.
+ # ~90-120s sustained block. The heartbeat-fsync false positive is fixed at the root
+ # (off-loop write + two-witness probe), so raising this would only delay recovery.
loop_watchdog_max_strikes: int = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES
unauthorized_dm_behavior: str = "pair" # "pair" or "ignore"
streaming: StreamingConfig = field(default_factory=StreamingConfig)
- # Drop SessionEntry records older than this from the store and sessions.json.
- # Invisible to users (a resumed chat gets a fresh session). 0 = disabled.
+ # Prune SessionEntry records older than this (a resumed chat gets a fresh session). 0 = off.
session_store_max_age_days: int = 90
# Route guilds/channels/threads to profiles (gateway/profile_routing.py).
profile_routes: list = field(default_factory=list)
@@ -720,19 +642,12 @@ class GatewayConfig:
)
def __post_init__(self) -> None:
- self.multiplex_profile_allowlist = _normalize_multiplex_profile_allowlist(
- self.multiplex_profile_allowlist
- )
- self.systemd_watchdog_seconds = coerce_systemd_watchdog_seconds(
- self.systemd_watchdog_seconds
- )
+ self.multiplex_profile_allowlist = _normalize_multiplex_profile_allowlist(self.multiplex_profile_allowlist)
+ self.systemd_watchdog_seconds = coerce_systemd_watchdog_seconds(self.systemd_watchdog_seconds)
def get_connected_platforms(self) -> List[Platform]:
- """Enabled + configured platforms, sorted by value.
-
- Sorted so the rendered "Connected Platforms" list is byte-stable across
- restarts and mid-process registration: a reorder busts the prompt cache.
- """
+ """Enabled + configured platforms, sorted by value so the rendered "Connected
+ Platforms" prompt block is byte-stable (a reorder busts the prompt cache)."""
connected = [
platform
for platform, config in self.platforms.items()
@@ -750,8 +665,7 @@ class GatewayConfig:
if checker is not None:
return checker(config)
- # Plugin-registered platforms. Force (idempotent) plugin discovery so this
- # works when GatewayConfig is constructed directly, bypassing load_gateway_config().
+ # Plugin platforms; force (idempotent) discovery for directly-constructed configs.
try:
from gateway.platform_registry import platform_registry
try:
@@ -774,11 +688,7 @@ class GatewayConfig:
config = self.platforms.get(platform)
return config.home_channel if config else None
- def get_reset_policy(
- self,
- platform: Optional[Platform] = None,
- session_type: Optional[str] = None
- ) -> SessionResetPolicy:
+ def get_reset_policy(self, platform: Optional[Platform] = None, session_type: Optional[str] = None) -> SessionResetPolicy:
"""Priority: platform override > type override > default."""
if platform and platform in self.reset_by_platform:
return self.reset_by_platform[platform]
@@ -819,41 +729,28 @@ class GatewayConfig:
"""Warning key prefix: "gateway." when the nested form was the one consulted."""
return key if key in data else f"gateway.{key}"
- platforms = {}
- for platform_name, platform_data in _coerce_dict(data.get("platforms", {})).items():
- if not isinstance(platform_data, dict):
- continue
- try:
- platforms[Platform(platform_name)] = PlatformConfig.from_dict(platform_data)
- except ValueError:
- pass # Skip unknown platforms
-
- reset_by_platform = {}
- for platform_name, policy_data in _coerce_dict(data.get("reset_by_platform", {})).items():
- try:
- reset_by_platform[Platform(platform_name)] = SessionResetPolicy.from_dict(policy_data)
- except ValueError:
- pass
-
- stt = _coerce_dict(data.get("stt"))
- stt_enabled = data.get("stt_enabled")
- if stt_enabled is None:
- stt_enabled = stt.get("enabled")
- stt_echo_transcripts = data.get("stt_echo_transcripts")
- if stt_echo_transcripts is None:
- stt_echo_transcripts = stt.get("echo_transcripts")
+ def by_platform(key: str, parse, *, dicts_only: bool = False) -> dict:
+ """``{Platform(name): parse(block)}`` for a platform-keyed mapping; unknown platforms skipped."""
+ out = {}
+ for platform_name, block in _coerce_dict(data.get(key, {})).items():
+ if dicts_only and not isinstance(block, dict):
+ continue
+ try:
+ out[Platform(platform_name)] = parse(block)
+ except ValueError:
+ pass
+ return out
+
+ def stt_setting(flat_key: str, nested_key: str) -> Any:
+ value = data.get(flat_key)
+ return _coerce_dict(data.get("stt")).get(nested_key) if value is None else value
+
+ def bounded_float(key: str, default: float, lo: float, hi: float) -> float:
+ # Out-of-range / non-finite watchdog knobs fall back to the shipped defaults.
+ value = _coerce_float(pick(key), default)
+ return value if math.isfinite(value) and lo <= value <= hi else default
room_link_url = data.get("room_link_url")
- if not isinstance(room_link_url, str):
- room_link_url = None
-
- # Watchdog knobs: out-of-range / non-finite values fall back to the shipped defaults.
- probe_interval = _coerce_float(pick("loop_watchdog_probe_interval_s"), DEFAULT_LOOP_WATCHDOG_INTERVAL_S)
- if not math.isfinite(probe_interval) or not 1.0 <= probe_interval <= 3600.0:
- probe_interval = DEFAULT_LOOP_WATCHDOG_INTERVAL_S
- probe_timeout = _coerce_float(pick("loop_watchdog_probe_timeout_s"), DEFAULT_LOOP_WATCHDOG_TIMEOUT_S)
- if not math.isfinite(probe_timeout) or not 1.0 <= probe_timeout <= 600.0:
- probe_timeout = DEFAULT_LOOP_WATCHDOG_TIMEOUT_S
max_strikes = _coerce_int(pick("loop_watchdog_max_strikes"), DEFAULT_LOOP_WATCHDOG_MAX_STRIKES)
if not 1 <= max_strikes <= 1000:
max_strikes = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES
@@ -862,10 +759,9 @@ class GatewayConfig:
pick("systemd_watchdog_seconds"), key_label("systemd_watchdog_seconds")
)
- # Multiplexing is env > config.yaml > default False. The GATEWAY_MULTIPLEX_PROFILES
- # operator override wins when set to a recognized value (hosted deployments stamp
- # it on the container); blank/unrecognized falls through to config. Config side:
- # the top-level VALUE wins when not None, else ``gateway.multiplex_profiles``.
+ # env > config.yaml > False: a recognized GATEWAY_MULTIPLEX_PROFILES wins (hosted
+ # deployments stamp it on the container); blank/unrecognized falls through to the
+ # top-level VALUE when not None, else ``gateway.multiplex_profiles``.
multiplex_profiles = data.get("multiplex_profiles")
if multiplex_profiles is None:
multiplex_profiles = nested_gateway.get("multiplex_profiles")
@@ -885,7 +781,7 @@ class GatewayConfig:
from gateway.profile_routing import parse_profile_routes
return cls(
- platforms=platforms,
+ platforms=by_platform("platforms", PlatformConfig.from_dict, dicts_only=True),
default_reset_policy=SessionResetPolicy.from_dict(data["default_reset_policy"])
if "default_reset_policy" in data
else SessionResetPolicy(),
@@ -893,24 +789,24 @@ class GatewayConfig:
type_name: SessionResetPolicy.from_dict(policy_data)
for type_name, policy_data in _coerce_dict(data.get("reset_by_type", {})).items()
},
- reset_by_platform=reset_by_platform,
+ reset_by_platform=by_platform("reset_by_platform", SessionResetPolicy.from_dict),
reset_triggers=data.get("reset_triggers", ["/new", "/reset"]),
quick_commands=_coerce_dict(data.get("quick_commands", {})),
sessions_dir=Path(data["sessions_dir"]) if "sessions_dir" in data else get_hermes_home() / "sessions",
write_sessions_json=_coerce_bool(data.get("write_sessions_json"), True),
always_log_local=_coerce_bool(data.get("always_log_local"), True),
filter_silence_narration=_coerce_bool(data.get("filter_silence_narration"), True),
- stt_enabled=_coerce_bool(stt_enabled, True),
- stt_echo_transcripts=_coerce_bool(stt_echo_transcripts, True),
+ stt_enabled=_coerce_bool(stt_setting("stt_enabled", "enabled"), True),
+ stt_echo_transcripts=_coerce_bool(stt_setting("stt_echo_transcripts", "echo_transcripts"), True),
group_sessions_per_user=_coerce_bool(data.get("group_sessions_per_user"), True),
thread_sessions_per_user=_coerce_bool(data.get("thread_sessions_per_user"), False),
multiplex_profiles=_coerce_bool(multiplex_profiles, False),
multiplex_profile_allowlist=pick("multiplex_profile_allowlist"),
- room_link_url=room_link_url,
+ room_link_url=room_link_url if isinstance(room_link_url, str) else None,
systemd_watchdog_seconds=systemd_watchdog_seconds,
loop_watchdog=_coerce_bool(pick("loop_watchdog"), True),
- loop_watchdog_probe_interval_s=probe_interval,
- loop_watchdog_probe_timeout_s=probe_timeout,
+ loop_watchdog_probe_interval_s=bounded_float("loop_watchdog_probe_interval_s", DEFAULT_LOOP_WATCHDOG_INTERVAL_S, 1.0, 3600.0),
+ loop_watchdog_probe_timeout_s=bounded_float("loop_watchdog_probe_timeout_s", DEFAULT_LOOP_WATCHDOG_TIMEOUT_S, 1.0, 600.0),
loop_watchdog_max_strikes=max_strikes,
max_concurrent_sessions=max_concurrent_sessions,
unauthorized_dm_behavior=_normalize_choice(
@@ -922,12 +818,9 @@ class GatewayConfig:
)
def get_unauthorized_dm_behavior(self, platform: Optional[Platform] = None) -> str:
- """Effective unauthorized-DM behavior for a platform.
-
- Email is inbox-shaped, not chat-shaped, so it defaults to ``"ignore"``
- unless ``platforms.email.unauthorized_dm_behavior`` explicitly opts in;
- a global default does not opt email into pairing.
- """
+ """Effective unauthorized-DM behavior. Email is inbox-shaped so it defaults to
+ ``"ignore"`` unless its own ``unauthorized_dm_behavior`` opts in (a global
+ default does not)."""
if platform:
platform_cfg = self.platforms.get(platform)
if platform_cfg and "unauthorized_dm_behavior" in platform_cfg.extra:
@@ -963,8 +856,7 @@ def load_gateway_config() -> GatewayConfig:
logger.warning(
"Failed to process config.yaml — falling back to .env / gateway.json values. "
"Check %s for syntax errors. Error: %s",
- _home / "config.yaml",
- e,
+ _home / "config.yaml", e,
)
config = GatewayConfig.from_dict(gw_data)
@@ -978,32 +870,22 @@ def _validate_gateway_config(config: "GatewayConfig") -> None:
policy = config.default_reset_policy
if not (0 <= policy.at_hour <= 23):
- logger.warning(
- "Invalid at_hour=%s (must be 0-23). Using default 4.", policy.at_hour
- )
+ logger.warning("Invalid at_hour=%s (must be 0-23). Using default 4.", policy.at_hour)
policy.at_hour = 4
if policy.idle_minutes is None or policy.idle_minutes <= 0:
- logger.warning(
- "Invalid idle_minutes=%s (must be positive). Using default 1440.",
- policy.idle_minutes,
- )
+ logger.warning("Invalid idle_minutes=%s (must be positive). Using default 1440.", policy.idle_minutes)
policy.idle_minutes = 1440
- # An empty token won't connect and the cause is confusing without a log line.
+ # An empty token won't connect; say so.
for platform, pconfig in config.platforms.items():
if not pconfig.enabled:
continue
env_name = PLATFORM_TOKEN_ENV_NAMES.get(platform)
if env_name and pconfig.token is not None and not pconfig.token.strip():
- logger.warning(
- "%s is enabled but %s is empty. "
- "The adapter will likely fail to connect.",
- platform.value, env_name,
- )
+ logger.warning("%s is enabled but %s is empty. The adapter will likely fail to connect.", platform.value, env_name)
- # Reject known-weak placeholder tokens (copied .env.example) with a clear
- # startup error instead of a confusing "auth failed" from the platform API.
+ # Reject placeholder tokens (copied .env.example) with a clear startup error.
try:
from hermes_cli.auth import has_usable_secret
except ImportError:
diff --git a/gateway/config_env.py b/gateway/config_env.py
index 0b90e0980c9..74ba70146bd 100644
--- a/gateway/config_env.py
+++ b/gateway/config_env.py
@@ -61,12 +61,8 @@ _ENV_ENABLE_CREDENTIALS: dict = {
def _warn_explicit_disable_beats_env(platform: Platform) -> None:
- """One-time WARNING: ``platforms.<x>.enabled: false`` wins over env creds.
-
- Credential presence used to force-enable platforms regardless of an explicit
- ``enabled: false``; users relying on "creds in .env = platform on" must be
- told why it went dark.
- """
+ """One-time WARNING: ``platforms.<x>.enabled: false`` wins over env creds (which
+ used to force-enable), so users relying on "creds in .env = on" learn why it went dark."""
if platform in _EXPLICIT_DISABLE_WARNED:
return
_EXPLICIT_DISABLE_WARNED.add(platform)
@@ -103,6 +99,10 @@ def _strip_slash(value: str) -> str:
return value.rstrip("/")
+def _strip_lower(value: str) -> str:
+ return value.strip().lower()
+
+
def _truthy_token(value: str) -> bool:
return value.lower() in {"true", "1", "yes", "on"}
@@ -152,10 +152,8 @@ def _env_home_channel(config: GatewayConfig, platform: Platform, env_base: str,
chat_id = chat_id.strip()
if chat_id and platform in config.platforms:
config.platforms[platform].home_channel = HomeChannel(
- platform=platform,
- chat_id=chat_id,
- name=getenv(f"{env_base}_NAME", "Home"),
- thread_id=getenv(f"{env_base}_THREAD_ID") or None,
+ platform=platform, chat_id=chat_id,
+ name=getenv(f"{env_base}_NAME", "Home"), thread_id=getenv(f"{env_base}_THREAD_ID") or None,
)
@@ -166,11 +164,8 @@ def _env_reply_mode(config: GatewayConfig, platform: Platform, env: str) -> None
def _enable_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfig:
- """Enable *platform* because its env credentials are present — unless config.yaml explicitly disabled it.
-
- READS (does not pop) the ``_enabled_explicit`` marker: the registry-driven
- plugin-enable pass also needs it; ``_scrub_explicit_markers`` removes it last.
- """
+ """Enable *platform* on env credentials unless config.yaml explicitly disabled it.
+ READS (does not pop) ``_enabled_explicit``: the plugin-enable pass also needs it."""
if platform not in config.platforms:
config.platforms[platform] = PlatformConfig(enabled=True)
return config.platforms[platform]
@@ -184,12 +179,11 @@ def _enable_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfi
def _enable_port_bound_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfig:
- """Enable a port-binding platform (api_server/webhook) unless config.yaml explicitly disabled it.
+ """Enable a port-binding platform unless config.yaml explicitly disabled it.
- In multiplex mode a secondary profile pins ``platforms.<x>.enabled: false`` so
- it shares the default profile's listener yet still inherits the process env;
- without this guard env presence would force-enable the listener and trip
- MultiplexConfigError. POPs the marker: these branches are terminal.
+ A multiplex secondary profile pins ``enabled: false`` to share the default profile's
+ listener yet inherits the process env; without this guard env presence would
+ force-enable it and trip MultiplexConfigError. POPs the marker (terminal branch).
"""
platform_config = config.platforms.setdefault(platform, PlatformConfig())
explicit = platform_config.extra.pop("_enabled_explicit", False)
@@ -202,14 +196,12 @@ def _enable_port_bound_from_env(config: GatewayConfig, platform: Platform) -> Pl
class _Cred:
"""Credential-gated platform enable, applied as ``step(config)``.
- ``creds``: env names that must ALL be truthy; an inner tuple lists alternatives (ANY).
- ``token``: env whose truthy value becomes ``PlatformConfig.token`` (stored even when
- yaml disables the adapter, so sending skills can use it).
- ``fixed``: ``(extra_key, env[, default[, fn]])`` always written once enabled (``env`` may
- be a tuple of alternatives). ``optional`` / ``optional_stripped``: ``_env_extras`` specs.
- ``warn_missing``: ``(env, msg)`` logged BEFORE enabling when *env* is blank.
- ``then``: unique tail ``fn(config, platform_config)``. ``home``: ``_env_home_channel`` env
- base applied only when the gate passed.
+ ``creds``: env names that must ALL be truthy (inner tuple = ANY of). ``token``: env
+ stored as ``PlatformConfig.token`` even when yaml disables the adapter (sending skills
+ use it). ``fixed``: ``(extra_key, env[, default[, fn]])`` always written once enabled.
+ ``optional*``: ``_env_extras`` specs. ``warn_missing``: ``(env, msg)`` logged BEFORE
+ enabling when blank. ``then``: tail ``fn(config, platform_config)``. ``home``:
+ ``_env_home_channel`` env base applied only when the gate passed.
"""
platform: Platform
creds: tuple
@@ -285,10 +277,8 @@ def _slack_home(config: GatewayConfig) -> None:
existing_home = slack_config.home_channel
same_home = existing_home is not None and existing_home.chat_id == slack_home
slack_config.home_channel = HomeChannel(
- platform=Platform.SLACK,
- chat_id=slack_home,
- name=getenv("SLACK_HOME_CHANNEL_NAME"),
- thread_id=getenv("SLACK_HOME_CHANNEL_THREAD_ID") or None,
+ platform=Platform.SLACK, chat_id=slack_home,
+ name=getenv("SLACK_HOME_CHANNEL_NAME"), thread_id=getenv("SLACK_HOME_CHANNEL_THREAD_ID") or None,
user_id=existing_home.user_id if same_home else None,
scope_id=existing_home.scope_id if same_home else None,
)
@@ -310,8 +300,7 @@ def _sms_api_key(config: GatewayConfig, sms_config: PlatformConfig) -> None:
def _api_server(config: GatewayConfig) -> None:
- """Require a usable key: API_SERVER_ENABLED alone would load an unauthenticated
- platform whose adapter refuses to start, leaving the reconnect watcher spinning."""
+ """Require a usable key: an unauthenticated adapter refuses to start and the reconnect watcher would spin."""
key = getenv("API_SERVER_KEY")
if not _has_usable_api_server_key(key):
return
@@ -334,18 +323,11 @@ def _msgraph_webhook(config: GatewayConfig) -> None:
client_state = getenv("MSGRAPH_WEBHOOK_CLIENT_STATE")
resources = getenv("MSGRAPH_WEBHOOK_ACCEPTED_RESOURCES")
allowed_cidrs = getenv("MSGRAPH_WEBHOOK_ALLOWED_SOURCE_CIDRS")
- if not (
- enabled
- or Platform.MSGRAPH_WEBHOOK in config.platforms
- or getenv("MSGRAPH_WEBHOOK_PORT")
- or client_state
- or resources
- or allowed_cidrs
- ):
+ if not (enabled or Platform.MSGRAPH_WEBHOOK in config.platforms or getenv("MSGRAPH_WEBHOOK_PORT")
+ or client_state or resources or allowed_cidrs):
return
msgraph_cfg = config.platforms.setdefault(Platform.MSGRAPH_WEBHOOK, PlatformConfig())
- # Same explicit-disable guard as webhook, but READ (don't pop) the marker: the
- # relay-exclusive pass still consults it; the end scrub removes it.
+ # Same guard as webhook, but READ (don't pop) the marker: the relay pass still consults it.
if enabled and (not msgraph_cfg.extra.get("_enabled_explicit", False) or msgraph_cfg.enabled):
msgraph_cfg.enabled = True
_env_extras(msgraph_cfg.extra, (("port", "MSGRAPH_WEBHOOK_PORT", _INT),))
@@ -371,8 +353,7 @@ def _qq_home(config: GatewayConfig, qq_config: PlatformConfig) -> None:
)
if qq_home:
qq_config.home_channel = HomeChannel(
- platform=Platform.QQBOT,
- chat_id=qq_home,
+ platform=Platform.QQBOT, chat_id=qq_home,
name=getenv("QQBOT_HOME_CHANNEL_NAME") or getenv(name_env, "Home"),
thread_id=getenv("QQBOT_HOME_CHANNEL_THREAD_ID") or getenv("QQ_HOME_CHANNEL_THREAD_ID") or None,
)
@@ -387,14 +368,12 @@ def _session_settings(config: GatewayConfig) -> None:
def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:
- """Registry-driven enable for plugin platforms (built-ins have explicit rows in ``_ENV_STEPS``).
-
- A plugin platform is enabled when its credentials are configured (``is_connected``)
- and its deps are present (passive ``check_fn``) or installable on demand
- (``ensure_deps_fn`` — run later by ``create_adapter()``, never here: an active
- installer in this sweep pip-installed SDKs on every load and boot-looped the
- desktop app). ``is_connected`` MUST gate enablement: ``check_fn`` alone would
- enable unconfigured platforms that then retry-connect forever with no token.
+ """Registry-driven enable for plugin platforms (built-ins have rows in ``_ENV_STEPS``).
+
+ Enabled when credentials are configured (``is_connected`` MUST gate: ``check_fn``
+ alone would enable unconfigured platforms that retry-connect forever) and deps are
+ present (``check_fn``) or installable later by ``create_adapter()`` — never here:
+ installing in this sweep pip-installed SDKs on every load and boot-looped the app.
"""
try:
from hermes_cli.plugins import discover_plugins
@@ -412,8 +391,7 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:
# Never re-enable a platform the user explicitly disabled (marker set by the YAML loader).
if existing_cfg is not None and not already_enabled and existing_extra.get("_enabled_explicit", False):
continue
- # Seed candidate extras so plugins whose ``is_connected`` reads ``config.extra``
- # (Google Chat) see the same state they will after enablement.
+ # Seed extras so ``is_connected`` implementations reading ``config.extra`` see post-enable state.
seed_for_probe = None
if entry.env_enablement_fn is not None:
try:
@@ -425,8 +403,7 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:
# Only consult is_connected for platforms not already enabled by YAML/env.
if not already_enabled and entry.is_connected is not None:
try:
- # Probe a transient ``enabled=True`` view (some ``is_connected``
- # short-circuit on ``config.enabled``); never mutate ``existing_cfg``.
+ # Probe a transient ``enabled=True`` view; never mutate ``existing_cfg``.
if has_seed:
for k, v in seed_for_probe.items():
if k != "home_channel":
@@ -459,9 +436,7 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:
platform_config.extra.update(seed)
if isinstance(home, dict) and home.get("chat_id"):
platform_config.home_channel = HomeChannel(
- platform=platform,
- chat_id=str(home["chat_id"]),
- name=str(home.get("name") or "Home"),
+ platform=platform, chat_id=str(home["chat_id"]), name=str(home.get("name") or "Home"),
thread_id=str(home["thread_id"]) if home.get("thread_id") else None,
)
except Exception as e:
@@ -469,18 +444,16 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:
def _relay(config: GatewayConfig) -> None:
- """Relay (connector-fronted platform, EXPERIMENTAL): enabled by GATEWAY_RELAY_URL or
- gateway.relay_url. The adapter dials OUT (no inbound port); the connected-checker
- keys on extra["relay_url"], so the URL is mirrored into extra.
-
- Relay-exclusive: the GATEWAY_RELAY_URL env stamp marks a deployment where the
- connector owns every platform connection; a directly-connected adapter in the same
- process would be a second unmanaged ingress (duplicate deliveries, split sessions,
- a socket that disarms scale-to-zero). So the env stamp disables all other messaging
- platforms — even ones explicitly enabled in config.yaml. Non-messaging surfaces
- (local, api_server, webhook — same set as the scale-to-zero arm gate) are untouched;
- relay via gateway.relay_url only keeps the old additive behavior. Opt out with
- GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true (also read through the scoped getenv).
+ """Relay (connector-fronted, EXPERIMENTAL): enabled by GATEWAY_RELAY_URL or
+ gateway.relay_url; the URL is mirrored into extra["relay_url"] for the connected-checker.
+
+ Relay-exclusive: the GATEWAY_RELAY_URL env stamp means the connector owns every
+ platform connection; a directly-connected adapter would be a second unmanaged ingress
+ (duplicate deliveries, split sessions, a socket disarming scale-to-zero). So the env
+ stamp disables all other messaging platforms — even ones explicitly enabled — except
+ non-messaging surfaces (local, api_server, webhook; same set as the scale-to-zero arm
+ gate). relay_url from YAML only keeps the additive behavior. Opt out with
+ GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true.
"""
relay_url_env = getenv("GATEWAY_RELAY_URL").strip()
existing_relay = config.platforms.get(Platform.RELAY)
@@ -519,10 +492,9 @@ def _scrub_explicit_markers(config: GatewayConfig) -> None:
platform_config.extra.pop("_enabled_explicit", None)
-# Application order is significant: e.g. Telegram's reply mode may create the (disabled)
-# platform entry BEFORE its home channel is read, while Discord reads home first; a home
-# channel is only attached to a platform that already exists. Relay-exclusive disabling
-# runs after the plugin pass and before the marker scrub, which must be last.
+# Order is significant: a home channel only attaches to a platform that already exists
+# (Telegram's reply mode may create the entry first; Discord reads home first). Relay
+# disabling runs after the plugin pass; the marker scrub must be last.
_ENV_STEPS: tuple = (
_Cred(Platform.TELEGRAM, ("TELEGRAM_BOT_TOKEN",), token="TELEGRAM_BOT_TOKEN"),
_ReplyMode(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"),
@@ -539,14 +511,10 @@ _ENV_STEPS: tuple = (
Platform.WHATSAPP_CLOUD, ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"),
fixed=(("phone_number_id", "WHATSAPP_CLOUD_PHONE_NUMBER_ID"), ("access_token", "WHATSAPP_CLOUD_ACCESS_TOKEN")),
optional=(
- ("app_id", "WHATSAPP_CLOUD_APP_ID"),
- ("app_secret", "WHATSAPP_CLOUD_APP_SECRET"),
- ("waba_id", "WHATSAPP_CLOUD_WABA_ID"),
- ("verify_token", "WHATSAPP_CLOUD_VERIFY_TOKEN"), # Meta hub.verify_token shared secret
- ("webhook_host", "WHATSAPP_CLOUD_WEBHOOK_HOST"),
- ("webhook_port", "WHATSAPP_CLOUD_WEBHOOK_PORT", _INT),
- ("webhook_path", "WHATSAPP_CLOUD_WEBHOOK_PATH"),
- ("api_version", "WHATSAPP_CLOUD_API_VERSION"),
+ ("app_id", "WHATSAPP_CLOUD_APP_ID"), ("app_secret", "WHATSAPP_CLOUD_APP_SECRET"),
+ ("waba_id", "WHATSAPP_CLOUD_WABA_ID"), ("verify_token", "WHATSAPP_CLOUD_VERIFY_TOKEN"),
+ ("webhook_host", "WHATSAPP_CLOUD_WEBHOOK_HOST"), ("webhook_port", "WHATSAPP_CLOUD_WEBHOOK_PORT", _INT),
+ ("webhook_path", "WHATSAPP_CLOUD_WEBHOOK_PATH"), ("api_version", "WHATSAPP_CLOUD_API_VERSION"),
),
),
_Home(Platform.WHATSAPP_CLOUD, "WHATSAPP_CLOUD_HOME_CHANNEL"),
@@ -555,8 +523,7 @@ _ENV_STEPS: tuple = (
_Cred(
Platform.SIGNAL, ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"),
fixed=(
- ("http_url", "SIGNAL_HTTP_URL"),
- ("account", "SIGNAL_ACCOUNT"),
+ ("http_url", "SIGNAL_HTTP_URL"), ("account", "SIGNAL_ACCOUNT"),
("ignore_stories", "SIGNAL_IGNORE_STORIES", "true", is_truthy_value),
),
),
@@ -594,10 +561,8 @@ _ENV_STEPS: tuple = (
_Cred(
Platform.FEISHU, ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),
fixed=(
- ("app_id", "FEISHU_APP_ID"),
- ("app_secret", "FEISHU_APP_SECRET"),
- ("domain", "FEISHU_DOMAIN", "feishu"),
- ("connection_mode", "FEISHU_CONNECTION_MODE", "websocket"),
+ ("app_id", "FEISHU_APP_ID"), ("app_secret", "FEISHU_APP_SECRET"),
+ ("domain", "FEISHU_DOMAIN", "feishu"), ("connection_mode", "FEISHU_CONNECTION_MODE", "websocket"),
),
optional=(("encrypt_key", "FEISHU_ENCRYPT_KEY"), ("verification_token", "FEISHU_VERIFICATION_TOKEN")),
home="FEISHU_HOME_CHANNEL",
@@ -611,15 +576,12 @@ _ENV_STEPS: tuple = (
_Cred(
Platform.WECOM_CALLBACK, ("WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"),
fixed=(
- ("corp_id", "WECOM_CALLBACK_CORP_ID"),
- ("corp_secret", "WECOM_CALLBACK_CORP_SECRET"),
- ("agent_id", "WECOM_CALLBACK_AGENT_ID"),
- ("token", "WECOM_CALLBACK_TOKEN"),
+ ("corp_id", "WECOM_CALLBACK_CORP_ID"), ("corp_secret", "WECOM_CALLBACK_CORP_SECRET"),
+ ("agent_id", "WECOM_CALLBACK_AGENT_ID"), ("token", "WECOM_CALLBACK_TOKEN"),
("encoding_aes_key", "WECOM_CALLBACK_ENCODING_AES_KEY"),
- # No default: an unset WECOM_CALLBACK_HOST leaves extra.host falsy so the adapter's
- # dual-stack DEFAULT_HOST=None applies (binds IPv4 + IPv6; "0.0.0.0" was IPv4-only).
- ("host", "WECOM_CALLBACK_HOST"),
- ("port", "WECOM_CALLBACK_PORT", "", _int_or(8645)),
+ # No host default: a falsy extra.host lets the adapter's dual-stack DEFAULT_HOST=None
+ # apply (binds IPv4 + IPv6; "0.0.0.0" was IPv4-only).
+ ("host", "WECOM_CALLBACK_HOST"), ("port", "WECOM_CALLBACK_PORT", "", _int_or(8645)),
),
),
# Weixin (personal WeChat via iLink Bot API)
@@ -627,12 +589,9 @@ _ENV_STEPS: tuple = (
Platform.WEIXIN, (("WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"),), token="WEIXIN_TOKEN",
optional=(("account_id", "WEIXIN_ACCOUNT_ID"),),
optional_stripped=(
- ("base_url", "WEIXIN_BASE_URL", _strip_slash),
- ("cdn_base_url", "WEIXIN_CDN_BASE_URL", _strip_slash),
- ("dm_policy", "WEIXIN_DM_POLICY", str.lower),
- ("group_policy", "WEIXIN_GROUP_POLICY", str.lower),
- ("allow_from", "WEIXIN_ALLOWED_USERS"),
- ("group_allow_from", "WEIXIN_GROUP_ALLOWED_USERS"),
+ ("base_url", "WEIXIN_BASE_URL", _strip_slash), ("cdn_base_url", "WEIXIN_CDN_BASE_URL", _strip_slash),
+ ("dm_policy", "WEIXIN_DM_POLICY", str.lower), ("group_policy", "WEIXIN_GROUP_POLICY", str.lower),
+ ("allow_from", "WEIXIN_ALLOWED_USERS"), ("group_allow_from", "WEIXIN_GROUP_ALLOWED_USERS"),
("split_multiline_messages", "WEIXIN_SPLIT_MULTILINE_MESSAGES"),
),
home="WEIXIN_HOME_CHANNEL", home_strip=True,
@@ -641,8 +600,7 @@ _ENV_STEPS: tuple = (
_Cred(
Platform.BLUEBUBBLES, ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),
fixed=(
- ("server_url", "BLUEBUBBLES_SERVER_URL", "", _strip_slash),
- ("password", "BLUEBUBBLES_PASSWORD"),
+ ("server_url", "BLUEBUBBLES_SERVER_URL", "", _strip_slash), ("password", "BLUEBUBBLES_PASSWORD"),
("webhook_host", "BLUEBUBBLES_WEBHOOK_HOST", "127.0.0.1"),
("webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", "", _int_or(8645)),
("webhook_path", "BLUEBUBBLES_WEBHOOK_PATH", "/bluebubbles-webhook"),
@@ -664,14 +622,10 @@ _ENV_STEPS: tuple = (
Platform.YUANBAO, (("YUANBAO_APP_ID", "YUANBAO_APP_KEY"), "YUANBAO_APP_SECRET"),
fixed=(("app_id", ("YUANBAO_APP_ID", "YUANBAO_APP_KEY")), ("app_secret", "YUANBAO_APP_SECRET")),
optional=(
- ("bot_id", "YUANBAO_BOT_ID"),
- ("ws_url", "YUANBAO_WS_URL"),
- ("api_domain", "YUANBAO_API_DOMAIN"),
- ("route_env", "YUANBAO_ROUTE_ENV"),
- ("dm_policy", "YUANBAO_DM_POLICY", lambda v: v.strip().lower()),
- ("dm_allow_from", "YUANBAO_DM_ALLOW_FROM"),
- ("group_policy", "YUANBAO_GROUP_POLICY", lambda v: v.strip().lower()),
- ("group_allow_from", "YUANBAO_GROUP_ALLOW_FROM"),
+ ("bot_id", "YUANBAO_BOT_ID"), ("ws_url", "YUANBAO_WS_URL"),
+ ("api_domain", "YUANBAO_API_DOMAIN"), ("route_env", "YUANBAO_ROUTE_ENV"),
+ ("dm_policy", "YUANBAO_DM_POLICY", _strip_lower), ("dm_allow_from", "YUANBAO_DM_ALLOW_FROM"),
+ ("group_policy", "YUANBAO_GROUP_POLICY", _strip_lower), ("group_allow_from", "YUANBAO_GROUP_ALLOW_FROM"),
),
home="YUANBAO_HOME_CHANNEL",
),
diff --git a/gateway/pairing.py b/gateway/pairing.py
index 6f9d752cfd9..d1d4b52dc96 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -45,13 +45,10 @@ LOCKOUT_SECONDS = 3600 # Lockout duration after too many failures
MAX_PENDING_PER_PLATFORM = 3 # Max pending codes per platform
MAX_FAILED_ATTEMPTS = 5 # Failed approvals before lockout
-# Default (non-profile-scoped) pairing directory. Deliberately ``None``: the
-# long-lived gateway imports this module at boot, and an eagerly computed path
-# would freeze whatever HERMES_HOME/profile context existed then, ignoring later
-# context-local overrides -- so the gateway and the short-lived ``hermes pairing``
-# CLI ended up writing different directories. ``_default_pairing_dir()`` resolves
-# fresh on every call; tests patch this attribute to a concrete path
-# (``patch("gateway.pairing.PAIRING_DIR", tmp)``) and a non-``None`` value wins.
+# Default pairing directory override. Deliberately ``None``: an eagerly computed
+# path would freeze the HERMES_HOME/profile context at gateway boot, ignoring later
+# context-local overrides, so the gateway and ``hermes pairing`` CLI wrote different
+# directories. ``_default_pairing_dir()`` resolves fresh per call; tests patch this.
PAIRING_DIR = None
@@ -61,12 +58,10 @@ def _default_pairing_dir() -> Path:
return get_hermes_dir("platforms/pairing", "pairing")
-# Platform value -> per-platform allowlist env var. When an operator already runs
-# an allowlist for a platform, approving a pairing code also writes the user into
-# it (and revoking removes them), so the operator's list stays the single visible
-# source of truth instead of drifting from an opaque approved.json. Platforms
-# absent here (or with no allowlist configured) keep the pairing store as the
-# sole grant record, honored by the authz union.
+# Platform value -> allowlist env var. Approving a code also writes the user into
+# an already-configured allowlist (revoke removes them) so the operator's list stays
+# the visible source of truth. Platforms absent here (or with no allowlist
+# configured) keep the pairing store as the sole grant record (authz union).
_PLATFORM_ALLOWLIST_ENV = {
"telegram": "TELEGRAM_ALLOWED_USERS",
"discord": "DISCORD_ALLOWED_USERS",
@@ -148,13 +143,10 @@ def _matching_ids(platform: str, approved: dict, user_id: str) -> list:
def _read_allowlist_env(env_var: str) -> str:
"""Read a platform allowlist env var through the profile secret scope.
- Under multiplexing the process env may hold ANOTHER profile's allowlist
- (first-writer-wins YAML→env bridges), so a scoped miss must return empty
- rather than borrow the process value. Unscoped callers (single-profile
- CLI / admin endpoints) keep the legacy ``os.getenv`` read. Writes go through
- ``hermes_cli.config.save_env_value`` / ``remove_env_value``, which target the
- active profile's ``.env`` and, under multiplexing, publish into the installed
- scope mapping rather than the shared ``os.environ``.
+ Under multiplexing the process env may hold ANOTHER profile's allowlist, so a
+ scoped miss must return empty rather than borrow it. Unscoped callers keep the
+ legacy ``os.getenv`` read. Writes go through ``save_env_value``/``remove_env_value``,
+ which target the active profile's ``.env`` / installed scope, not ``os.environ``.
"""
try:
from agent.secret_scope import UnscopedSecretError, get_secret
@@ -242,12 +234,8 @@ def _purge_allowlist_entries(entries, platform: str, user_id: str):
def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:
- """Clear revoked principals from in-process adapter allowlist snapshots.
-
- Adapters snapshot ``_allow_from`` at construction; when the revoked
- principal was the sole entry the env key is removed entirely, so intake
- must not keep authorizing from the stale snapshot until restart.
- """
+ """Clear revoked principals from in-process adapter ``_allow_from`` snapshots,
+ so intake does not keep authorizing from a stale snapshot until restart."""
platform_name = (platform or "").strip().lower()
if not platform_name or not str(user_id or "").strip():
return
@@ -270,10 +258,8 @@ def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:
def _sync_allowlist_remove(platform: str, user_id: str) -> None:
"""Remove ``user_id`` (and WhatsApp alias equivalents) from the allowlist.
- Approve mirrors a normalized phone while revoke is often given a JID or
- device-suffix form, so matching uses alias rules -- exact-string delete
- would leave the sender authorized. Also clears in-process adapter
- snapshots so sole-entry revocation works without a gateway restart.
+ Approve mirrors a normalized phone while revoke is often given a JID/device
+ form, so matching uses alias rules -- exact delete would leave the sender authorized.
"""
configured = _configured_allowlist(platform)
if configured is None:
@@ -382,21 +368,15 @@ def _is_hashed_entry(entry) -> bool:
class PairingStore:
- """Manages pairing codes and approved user lists.
-
- Data files per platform: ``{platform}-pending.json``,
- ``{platform}-approved.json``, plus shared ``_rate_limits.json``.
+ """Pairing codes and approved user lists.
- With ``profile="<name>"`` storage resolves from that profile's own
- HERMES_HOME with the same legacy/consolidated layout rules as
- ``hermes -p <name> pairing ...``, so multiplex gateways and profile-scoped
- CLI approvals share one whitelist. Without a profile, storage is the global
- pairing directory for the current HERMES_HOME.
+ Files per platform: ``{platform}-pending.json``, ``{platform}-approved.json``,
+ plus shared ``_rate_limits.json``. With ``profile="<name>"`` storage resolves from
+ that profile's HERMES_HOME exactly as ``hermes -p <name> pairing ...`` does, so
+ multiplex gateways and profile-scoped CLI approvals share one whitelist.
"""
def __init__(self, profile: Optional[str] = None):
- # Resolved lazily: tests use a temp HERMES_HOME and may construct the
- # store before the env is set.
if profile:
root = get_default_hermes_root()
profile_home = root if profile == "default" else root / "profiles" / profile
@@ -405,11 +385,9 @@ class PairingStore:
profile_home = None
self._dir = _default_pairing_dir()
self._dir.mkdir(parents=True, exist_ok=True)
- # Merge the alternate old/new layout so upgrades cannot split approvals;
- # a profile store must resolve exactly as ``hermes -p <profile>`` does.
+ # Merge the alternate old/new layout so upgrades cannot split approvals.
_migrate_split_pairing_dirs(home=profile_home, active=self._dir)
- # Protects all read-modify-write cycles: platform adapters run
- # concurrently in threads sharing one PairingStore.
+ # Adapters run concurrently in threads sharing one store.
self._lock = threading.RLock()
self._profile = profile # for diagnostics / log lines
@@ -486,10 +464,8 @@ class PairingStore:
del pending[matched_key]
self._save_json(self._pending_path(platform), pending)
- # A successful approval proves the requester is legitimate, so the
- # brute-force streak must not carry over: the counter persists in
- # _rate_limits.json and would otherwise accumulate isolated typos
- # until a single fresh typo trips a spurious lockout.
+ # A successful approval proves legitimacy, so the persisted brute-force streak
+ # must not carry over (isolated typos would accumulate into a spurious lockout).
self._reset_failed_attempts(platform)
self._approve_user(
@@ -535,28 +511,22 @@ class PairingStore:
return code
def approve_code(self, platform: str, code: str) -> Optional[dict]:
- """Approve a pairing code. Adds the user to the approved list.
-
- Returns ``{user_id, user_name}`` on success, ``None`` if the code is
- invalid/expired OR the platform is locked out after
- ``MAX_FAILED_ATTEMPTS`` failed approvals (disambiguate with
- ``_is_locked_out``). The code is hashed with each entry's salt and
- compared in constant time; legacy plaintext-key entries are ignored
- and pruned at TTL by ``_cleanup_expired``.
+ """Approve a pairing code and add its user to the approved list.
+
+ Returns ``{user_id, user_name}``, or ``None`` if the code is invalid/expired OR
+ the platform is locked out (disambiguate with ``_is_locked_out``). Constant-time
+ salted-hash compare; legacy plaintext entries are ignored and pruned at TTL.
"""
with self._lock:
self._cleanup_expired(platform)
code = code.upper().strip()
- # Must run before the pending lookup, or an already-issued valid
- # code would still be accepted during lockout, nullifying the
- # brute-force protection.
+ # Before the lookup, or an already-issued valid code would bypass lockout.
if self._is_locked_out(platform):
return None
pending = self._load_json(self._pending_path(platform))
- # Skip legacy/malformed entries rather than KeyError so an in-place
- # upgrade over an existing pending.json doesn't crash.
+ # Skip legacy/malformed entries so an in-place upgrade doesn't crash.
for entry_id, entry in pending.items():
if not _is_hashed_entry(entry):
continue
@@ -572,27 +542,18 @@ class PairingStore:
@staticmethod
def looks_like_request_id(value: str) -> bool:
- """True when ``value`` has the shape of a ``list_pending`` request id.
-
- Request ids are ``secrets.token_hex(8)`` (16 hex chars); pairing codes
- are 8 chars from an uppercase alphabet, so the shapes cannot collide
- and callers accepting either can dispatch on this.
- """
+ """True when ``value`` is shaped like a ``list_pending`` request id (16 hex chars);
+ pairing codes are 8 uppercase chars, so callers accepting either can dispatch on this."""
value = str(value or "").strip()
return len(value) == 16 and all(c in "0123456789abcdefABCDEF" for c in value)
def approve_request(self, platform: str, request_id: str) -> Optional[dict]:
- """Approve a pending request by its server-side request id.
-
- Grant path for authenticated admin surfaces (``hermes pairing list``,
- dashboard/desktop buttons) that must never reveal the DM'd code.
- Returns ``{user_id, user_name}`` or ``None`` for an unknown/expired id.
+ """Approve a pending request by its server-side request id (admin surfaces that
+ must never reveal the DM'd code). Returns ``{user_id, user_name}`` or ``None``.
- Unlike :meth:`approve_code` this neither counts toward nor is gated by
- the brute-force lockout: a request id is only obtainable by an admin
- already authenticated to this store, so a stale id means "the row you
- clicked expired", not an attack -- and counting it would let a few GUI
- clicks lock the operator out of the CLI's code path.
+ Neither counts toward nor is gated by the brute-force lockout: a request id is only
+ obtainable by an authenticated admin, so a stale id is "the row expired", not an
+ attack -- counting it would let a few GUI clicks lock the operator out.
"""
with self._lock:
self._cleanup_expired(platform)
@@ -607,12 +568,8 @@ class PairingStore:
return None
def list_pending(self, platform: str = None) -> list:
- """List pending pairing requests, optionally filtered by platform.
-
- Codes are hashed and never returned; each entry exposes a server-side
- ``request_id`` for :meth:`approve_request`. Legacy pre-hash entries
- report an empty ``request_id`` and age out at TTL.
- """
+ """List pending requests (codes are never returned; each exposes a ``request_id``
+ for :meth:`approve_request`; legacy pre-hash entries report an empty id)."""
results = []
with self._lock:
for p in [platform] if platform else self._all_platforms("pending"):