From 4e665e4e53203ab218d21e83209101859d4a4518 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 18:22:31 -0700 Subject: [PATCH] refactor(gateway): fold Slack/SMS env steps into _Cred rows, compact config dataclasses --- gateway/config.py | 732 +++++++++++++----------------------------- gateway/config_env.py | 222 ++++++------- 2 files changed, 316 insertions(+), 638 deletions(-) diff --git a/gateway/config.py b/gateway/config.py index 415450d1df..9923ccba4f 100644 --- a/gateway/config.py +++ b/gateway/config.py @@ -1,11 +1,5 @@ -""" -Gateway configuration management. - -Handles loading and validating configuration for: -- Connected platforms (Telegram, Discord, WhatsApp, Weixin, and more) -- Home channels for each platform -- Session reset policies -- Delivery preferences +"""Gateway configuration: connected platforms, home channels, session reset +policies and delivery preferences, loaded from config.yaml / gateway.json / env. """ import logging @@ -27,6 +21,9 @@ from utils import is_truthy_value logger = logging.getLogger(__name__) +_TRUTHY_STRINGS = frozenset({"1", "true", "yes", "on"}) +_FALSY_STRINGS = frozenset({"0", "false", "no", "off"}) + def _coerce_bool(value: Any, default: bool = True) -> bool: """Coerce bool-ish config values, preserving a caller-provided default.""" @@ -34,9 +31,9 @@ def _coerce_bool(value: Any, default: bool = True) -> bool: return default if isinstance(value, str): lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "on"}: + if lowered in _TRUTHY_STRINGS: return True - if lowered in {"false", "0", "no", "off"}: + if lowered in _FALSY_STRINGS: return False return default return is_truthy_value(value, default=default) @@ -80,50 +77,38 @@ def _normalize_multiplex_profile_allowlist(value: Any) -> Optional[List[str]]: return normalized -# Recognized truthy / falsy tokens for the GATEWAY_MULTIPLEX_PROFILES operator -# override. Anything not in either set — and a blank/whitespace value — is -# treated as "unset" so it falls through to config.yaml rather than silently -# forcing the flag off. -_MULTIPLEX_TRUTHY_STRINGS = frozenset({"1", "true", "yes", "on"}) -_MULTIPLEX_FALSY_STRINGS = frozenset({"0", "false", "no", "off"}) - - def _env_multiplex_profiles_override() -> "bool | None": - """Resolve the GATEWAY_MULTIPLEX_PROFILES operator override. + """GATEWAY_MULTIPLEX_PROFILES operator override: True/False for a recognized token. - Returns ``True``/``False`` when the env var is set to a recognized truthy/ - falsy token, or ``None`` when it is unset, blank, or unrecognized — in which - case the caller keeps the config.yaml value (env > config > default). Blank - is deliberately ``None``, not ``False``: a provisioned-but-unpopulated Fly - secret arrives as ``""`` and must NOT shadow a config.yaml opt-in. + ``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml + value (env > config > default). Blank is deliberately ``None``, not ``False``: + a provisioned-but-unpopulated Fly secret arrives as ``""`` and must NOT shadow + a config.yaml opt-in. """ raw = os.getenv("GATEWAY_MULTIPLEX_PROFILES") token = (raw or "").strip().lower() if not token: return None - if token in _MULTIPLEX_TRUTHY_STRINGS: + if token in _TRUTHY_STRINGS: return True - if token in _MULTIPLEX_FALSY_STRINGS: + if token in _FALSY_STRINGS: return False logger.warning( "Ignoring unrecognized GATEWAY_MULTIPLEX_PROFILES=%r " "(expected one of %s or %s); falling back to config.yaml.", raw, - sorted(_MULTIPLEX_TRUTHY_STRINGS), - sorted(_MULTIPLEX_FALSY_STRINGS), + sorted(_TRUTHY_STRINGS), + sorted(_FALSY_STRINGS), ) return None def _normalize_transport_token(value: Any) -> str: - """Normalize a streaming transport/mode value to a canonical token. + """Canonical streaming transport token. - Handles the YAML 1.1 boolean quirk where bare ``on`` / ``off`` parse to - Python ``True`` / ``False`` (see ``gateway/display_config.py`` ``_normalise``). - Without this, ``mode: off`` arrives as boolean ``False`` and stringifying it - yields ``"false"`` instead of the advertised ``"off"``, so streaming would be - enabled instead of disabled. Booleans map to ``"auto"`` (True) / ``"off"`` - (False); anything else is lower-cased, defaulting to ``"auto"``. + 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"``. """ if value is None: return "auto" @@ -133,7 +118,6 @@ def _normalize_transport_token(value: Any) -> str: def _coerce_float(value: Any, default: float) -> float: - """Coerce numeric config values, falling back on malformed input.""" if value is None: return default try: @@ -143,36 +127,23 @@ def _coerce_float(value: Any, default: float) -> float: def _coerce_int(value: Any, default: int) -> int: - """Coerce integer config values, falling back on malformed input.""" if value is None: return default try: return int(value) except (TypeError, ValueError, OverflowError): - # OverflowError: int(float("inf")) — a non-finite YAML value must - # degrade to the default, not abort gateway config loading. + # OverflowError: int(float("inf")) — non-finite YAML must degrade, not abort loading. return default def _coerce_optional_positive_int(value: Any, key: str) -> Optional[int]: - """Coerce an optional positive integer config value. - - ``None``/0/negative disable the setting. Malformed values are ignored with - a warning so a typo never prevents the gateway from starting. - """ + """``None``/0/negative disable; malformed values are ignored with a warning so a typo never blocks startup.""" if value is None: return None try: - if isinstance(value, bool): + if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()): raise ValueError(value) - if isinstance(value, float): - if not value.is_integer(): - raise ValueError(value) - parsed = int(value) - elif isinstance(value, str): - parsed = int(value.strip(), 10) - else: - parsed = int(value) + parsed = int(value.strip(), 10) if isinstance(value, str) else int(value) except (TypeError, ValueError): logger.warning( "Ignoring invalid %s=%r (expected a positive integer; 0/null disables)", key, value @@ -187,7 +158,7 @@ _SYSTEMD_WATCHDOG_MAX_SECONDS = 2_147_483_647 def coerce_systemd_watchdog_seconds( value: Any, key: str = "gateway.systemd_watchdog_seconds" ) -> int: - """Return a bounded positive watchdog interval or zero when disabled. + """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. @@ -220,7 +191,6 @@ def coerce_systemd_watchdog_seconds( def _coerce_dict(value: Any) -> Dict[str, Any]: - """Return *value* when it is a mapping, otherwise an empty dict.""" return value if isinstance(value, dict) else {} @@ -245,11 +215,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. - ``load_gateway_config()`` runs in many contexts, including multiplexed - profile startup where ``_profile_runtime_scope`` installs per-profile - secrets. In that scope we must prefer the scoped value; outside it we keep - legacy ``os.getenv`` behavior for single-profile callers and unscoped - gateway reads. + Multiplexed profile startup installs per-profile secrets, which must win; + outside a scope keep legacy ``os.getenv`` behavior. """ if current_secret_scope() is not None: scope_val = _get_secret(name, None) @@ -262,18 +229,16 @@ def _getenv_str(name: str, default: str = "") -> str: return val if val is not None else default -# Module-level cache for bundled platform plugin names (lives outside the -# enum so it doesn't become an accidental enum member). +# Bundled platform plugin names, cached outside the enum so it never becomes a member. _Platform__bundled_plugin_names: Optional[set] = None class Platform(Enum): """Supported messaging platforms. - Built-in platforms have explicit members. Plugin platforms use dynamic - members created on-demand by ``_missing_()`` so that - ``Platform("irc")`` works without modifying this enum. Dynamic members - are cached in ``_value2member_map_`` for identity-stable comparisons. + 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. """ LOCAL = "local" TELEGRAM = "telegram" @@ -299,39 +264,27 @@ class Platform(Enum): QQBOT = "qqbot" YUANBAO = "yuanbao" RELAY = "relay" # generic relay adapter fronted by the connector (EXPERIMENTAL) + @classmethod def _missing_(cls, value): - """Accept unknown platform names only for known plugin adapters. - - Creates a pseudo-member cached in ``_value2member_map_`` so that - ``Platform("irc") is Platform("irc")`` holds True (identity-stable). - Arbitrary strings are rejected to prevent enum pollution. - """ + """Accept unknown names only for bundled or runtime-registered plugin adapters (no enum pollution).""" if not isinstance(value, str) or not value.strip(): return None - # Normalise to lowercase to avoid case mismatches in config value = value.strip().lower() - # Check cache first (another call may have created it already) if value in cls._value2member_map_: return cls._value2member_map_[value] - # Only create pseudo-members for bundled plugin platforms (discovered - # via filesystem scan) or runtime-registered plugin platforms. global _Platform__bundled_plugin_names if _Platform__bundled_plugin_names is None: _Platform__bundled_plugin_names = cls._scan_bundled_plugin_platforms() if value in _Platform__bundled_plugin_names: return cls._add_pseudo_member(value) - - # Runtime-registered plugins (e.g. user-installed, discovered after - # the enum was defined). try: from gateway.platform_registry import platform_registry if platform_registry.is_registered(value): return cls._add_pseudo_member(value) except Exception: pass - return None @classmethod @@ -345,7 +298,7 @@ class Platform(Enum): @classmethod def _scan_bundled_plugin_platforms(cls) -> set: - """Return names of bundled platform plugins under ``plugins/platforms/``.""" + """Names of bundled platform plugins under ``plugins/platforms/``.""" names: set = set() try: platforms_dir = Path(__file__).parent.parent / "plugins" / "platforms" @@ -360,47 +313,29 @@ class Platform(Enum): return names -# Snapshot of built-in platform values before any dynamic _missing_ lookups. -# Used to distinguish real platforms from arbitrary strings. +# 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 (HTTP/webhook listeners). In a profile -# multiplexer the default profile owns the single shared listener and serves -# every profile through the /p// 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. +# Platforms that bind a host TCP port. In a profile multiplexer only the default +# profile owns the shared listener (served via /p//), 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. PORT_BINDING_PLATFORM_VALUES = frozenset({ - "webhook", - "api_server", - "msgraph_webhook", - "feishu", - "wecom_callback", - "bluebubbles", - "sms", - "whatsapp_cloud", - "line", - "teams", + "webhook", "api_server", "msgraph_webhook", "feishu", "wecom_callback", + "bluebubbles", "sms", "whatsapp_cloud", "line", "teams", }) -# 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). +# Platforms that only bind in one connection mode: Feishu's default websocket +# mode is an outbound long connection. platform value → the mode that binds. 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. - """ + """True when *platform_value* actually binds a port for *extra* config.""" if platform_value not in PORT_BINDING_PLATFORM_VALUES: return False expected_mode = PORT_BINDING_CONDITIONAL_MODES.get(platform_value) @@ -412,24 +347,21 @@ def platform_binds_port(platform_value: str, extra: Optional[dict] = None) -> bo @dataclass class HomeChannel: - """ - Default destination for a platform. - - When a cron job specifies deliver="telegram" without a specific chat ID, - messages are sent to this home channel. Thread-aware platforms may also - store a thread/topic ID so the bare platform target routes to the exact - conversation where /sethome was run. + """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. """ platform: Platform chat_id: str - name: str # Human-readable name for display + name: str thread_id: Optional[str] = None # Authenticated logical-target provenance observed by a platform adapter. - # Relay egress re-attaches these values, but the connector remains the - # authorization boundary and resolves them against its authoritative stores. + # Relay egress re-attaches these; the connector remains the authorization + # boundary and resolves them against its authoritative stores. user_id: Optional[str] = None scope_id: Optional[str] = None - + def to_dict(self) -> Dict[str, Any]: result = { "platform": self.platform.value, @@ -440,16 +372,15 @@ class HomeChannel: if getattr(self, key): result[key] = getattr(self, key) 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"), - thread_id=str(data["thread_id"]) if data.get("thread_id") else None, - user_id=str(data["user_id"]) if data.get("user_id") else None, - scope_id=str(data["scope_id"]) if data.get("scope_id") else None, + **optional, ) @@ -467,48 +398,32 @@ def persist_home_channel(home: HomeChannel, *, enabled_if_new: bool = False) -> @dataclass class SessionResetPolicy: - """ - Controls when sessions reset (lose context). - - Modes: - - "daily": Reset at a specific hour each day - - "idle": Reset after N minutes of inactivity - - "both": Whichever triggers first (daily boundary OR idle timeout) - - "none": Never auto-reset (context managed only by compression) + """Controls when sessions reset (lose context). - Default is "none" — sessions never auto-reset unless the user opts in - via the `session_reset` section in config.yaml (or gateway.json - overrides). Changed July 2026 from "both" (24h idle + daily 4am), which - surprised users who expected their conversations to persist. + 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). """ - mode: str = "none" # "daily", "idle", "both", or "none" - at_hour: int = 4 # Hour for daily reset (0-23, local time) - idle_minutes: int = 1440 # Minutes of inactivity before reset (24 hours) - notify: bool = True # Send a notification to the user when auto-reset occurs - notify_exclude_platforms: tuple = ("api_server", "webhook") # Platforms that don't get reset notifications - # A background process this many hours old (or older) no longer blocks - # session idle/daily reset. A forgotten preview server should not keep a - # session alive forever (#29177). The process is NOT killed — only ignored - # by the reset guard. Raise this if you run legitimate multi-day jobs whose - # liveness should pin the conversation open. + 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. bg_process_max_age_hours: int = 24 def to_dict(self) -> Dict[str, Any]: - return { - "mode": self.mode, - "at_hour": self.at_hour, - "idle_minutes": self.idle_minutes, - "notify": self.notify, - "notify_exclude_platforms": list(self.notify_exclude_platforms), - "bg_process_max_age_hours": self.bg_process_max_age_hours, - } - + return {**asdict(self), "notify_exclude_platforms": list(self.notify_exclude_platforms)} + @classmethod def from_dict(cls, data: Dict[str, Any]) -> "SessionResetPolicy": data = _coerce_dict(data) def val(key: str, default: Any) -> Any: - # Handle both missing keys and explicit null values (YAML null → None) + # Missing keys and explicit YAML nulls both take the default. value = data.get(key) return default if value is None else value @@ -525,13 +440,7 @@ class SessionResetPolicy: @dataclass class ChannelOverride: - """ - Per-channel override for model, provider, and system prompt. - - Used in config under platforms..channel_overrides[channel_id]. - Enables different channels (e.g. Discord #daily vs #dev) to use different - models and personas without running separate gateway instances. - """ + """Per-channel model/provider/system_prompt override (``platforms..channel_overrides[channel_id]``).""" model: Optional[str] = None provider: Optional[str] = None system_prompt: Optional[str] = None @@ -550,12 +459,11 @@ class ChannelOverride: ) -# Canonical map of platforms whose primary credential is ``PlatformConfig.token`` -# and the env var it loads from. Used for empty-token warnings at config -# validation and by the multiplex primary-startup credential gate in -# ``gateway.run`` (#64674). Platforms absent from this map authenticate some -# other way (session files, port-bound webhooks, api_key-only) and must never -# be skipped for a missing token. +# 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. PLATFORM_TOKEN_ENV_NAMES: dict["Platform", str] = { Platform.TELEGRAM: "TELEGRAM_BOT_TOKEN", Platform.DISCORD: "DISCORD_BOT_TOKEN", @@ -570,46 +478,24 @@ PLATFORM_TOKEN_ENV_NAMES: dict["Platform", str] = { class PlatformConfig: """Configuration for a single messaging platform.""" enabled: bool = False - token: Optional[str] = None # Bot token (Telegram, Discord) + token: Optional[str] = None api_key: Optional[str] = None # API key if different from token home_channel: Optional[HomeChannel] = None - - # Reply threading mode (Telegram/Slack) - # - "off": Never thread replies to original message - # - "first": Only first chunk threads to user's message (default) - # - "all": All chunks in multi-part replies thread to user's message + # Reply threading: "off" never threads, "first" threads only the first chunk, "all" every chunk. reply_to_mode: str = "first" - - # Whether the gateway is allowed to send "♻️ Gateway online" / - # "♻ Gateway restarted" lifecycle notifications on this platform. - # Default True preserves prior behavior. Set False on platforms used - # by end users (e.g. Slack) where operator-flavored restart pings are - # noise; keep True for back-channels where the operator wants them. + # "♻️ Gateway online/restarted" lifecycle pings. Set False on end-user + # platforms (e.g. Slack) where operator-flavored notices are noise. gateway_restart_notification: bool = True - - # Whether the gateway shows a "typing…" / "is thinking…" status indicator - # while the agent processes a message on this platform. Default True - # preserves prior behavior. Set False on platforms where the indicator is - # unwanted (e.g. Slack's assistant.threads.setStatus "is thinking…", which - # disables the compose box, or any platform where users find the bubble - # noisy). Drives the per-message _keep_typing refresh loop in - # gateway/platforms/base.py. + # "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: bool = True - - # Custom text for the working-state line on platforms whose typing - # indicator renders text rather than a native bubble: Slack's - # assistant.threads.setStatus line (shown next to the bot name; needs the - # assistant:write scope to render) and Google Chat's visible marker - # message. None keeps each platform's built-in default ("is thinking..." / - # "Hermes is thinking…"). Platforms with textless indicators (Discord, - # Telegram, Matrix, …) ignore it. + # 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. typing_status_text: Optional[str] = None - - # Per-channel model/provider/system_prompt overrides (channel_id -> ChannelOverride) channel_overrides: Dict[str, ChannelOverride] = field(default_factory=dict) - - # Platform-specific settings - extra: Dict[str, Any] = field(default_factory=dict) + extra: Dict[str, Any] = field(default_factory=dict) # Platform-specific settings def to_dict(self) -> Dict[str, Any]: result = { @@ -640,22 +526,20 @@ 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 - # arrive top-level or bridged into ``extra`` by the shared-key loop in - # load_gateway_config(), so YAML ``discord: gateway_restart_notification: false`` - # works without a separate platforms: block. Check both (top-level wins). + # gateway_restart_notification / typing_indicator / typing_status_text may be + # top-level or bridged into ``extra`` by the shared-key loop; top-level wins. extra = _coerce_dict(data.get("extra", {})) def toplevel_or_extra(key: str) -> Any: value = data.get(key) return extra.get(key) if value is None else value - channel_overrides: Dict[str, ChannelOverride] = {} raw_overrides = data.get("channel_overrides") or {} - if isinstance(raw_overrides, dict): - for cid, ov_data in raw_overrides.items(): - if isinstance(ov_data, dict): - channel_overrides[str(cid)] = ChannelOverride.from_dict(ov_data) + channel_overrides = { + str(cid): ChannelOverride.from_dict(ov_data) + for cid, ov_data in raw_overrides.items() + if isinstance(ov_data, dict) + } if isinstance(raw_overrides, dict) else {} return cls( enabled=_coerce_bool(data.get("enabled"), False), @@ -671,11 +555,9 @@ class PlatformConfig: ) -# Streaming defaults — single source of truth so both StreamingConfig and -# StreamConsumerConfig agree on the out-of-the-box edit rhythm. Tuned for -# Telegram's ~1 edit/s flood envelope: a touch under 1s lets the cadence -# breathe without bumping into rate limits, and a smaller buffer threshold -# makes short replies feel near-instant in DMs. +# 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. DEFAULT_STREAMING_EDIT_INTERVAL: float = 0.8 DEFAULT_STREAMING_BUFFER_THRESHOLD: int = 24 DEFAULT_STREAMING_CURSOR: str = " ▉" @@ -683,79 +565,41 @@ DEFAULT_STREAMING_CURSOR: str = " ▉" @dataclass class StreamingConfig: - """Configuration for real-time token streaming to messaging platforms.""" + """Real-time token streaming to messaging platforms.""" enabled: bool = False - # Transport selection: - # "auto" — prefer native streaming-draft updates when the platform - # supports them (Telegram sendMessageDraft, Bot API 9.5+); - # fall back to edit-based when not. - # "draft" — explicitly request native drafts; falls back to edit when - # the platform/chat doesn't support them. - # "edit" — progressive editMessageText only (legacy behaviour). - # "off" — disable streaming entirely. - # - # Default is "auto": prefer native draft streaming on platforms that - # support it (Telegram DMs via sendMessageDraft, Bot API 9.5+) and fall - # back to edit-based streaming everywhere else. This is safe as a global - # default because adapters without draft support (Discord, Slack, Matrix, - # …) report supports_draft_streaming() == False and transparently use the - # edit path — so "auto" never regresses non-Telegram platforms, it only - # upgrades the chats that can render the smoother native preview. + # 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. transport: str = "auto" edit_interval: float = DEFAULT_STREAMING_EDIT_INTERVAL buffer_threshold: int = DEFAULT_STREAMING_BUFFER_THRESHOLD cursor: str = DEFAULT_STREAMING_CURSOR - # Ported from openclaw/openclaw#72038. When >0, the final edit for - # a long-running streamed response is delivered as a fresh message - # if the original preview has been visible for at least this many - # seconds, so the platform's visible timestamp reflects completion - # time instead of the preview creation time. Currently applied to - # Telegram only (other platforms ignore the setting). Default 0 disables - # the fresh-message replacement path; set >0 to opt in. + # 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. fresh_final_after_seconds: float = 0.0 def to_dict(self) -> Dict[str, Any]: - return { - "enabled": self.enabled, - "transport": self.transport, - "edit_interval": self.edit_interval, - "buffer_threshold": self.buffer_threshold, - "cursor": self.cursor, - "fresh_final_after_seconds": self.fresh_final_after_seconds, - } + return asdict(self) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "StreamingConfig": if not isinstance(data, dict) or not data: return cls() - # ``mode`` is an ergonomic alias for the transport that ALSO implies - # ``enabled``. A config like ``streaming: {mode: auto}`` reads as - # "turn streaming on, transport=auto" — matching the natural intent - # of someone enabling streaming without also spelling out - # ``enabled: true``. Without this, ``mode`` was silently ignored and - # streaming stayed disabled (``enabled`` defaults to False), which is - # a surprising footgun: the whole reply buffers and sends at once. - # ``mode: off`` disables streaming; an explicit ``enabled`` key always - # wins so callers can force either state. - # - # ``transport`` alone does NOT imply ``enabled``: ``streaming.enabled`` - # is the documented master switch (see website/docs/user-guide/ - # configuration.md), so a bare ``transport`` only selects HOW to stream - # once streaming is on. Only the ``mode`` alias flips ``enabled``. + # ``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. raw_transport = data.get("transport") raw_mode = data.get("mode") - # Normalize both through the same helper so YAML's bare ``off``/``on`` - # (parsed as bool False/True) become canonical tokens rather than - # ``"false"``/``"true"``. - picked = raw_transport if raw_transport is not None else raw_mode - transport = _normalize_transport_token(picked) + transport = _normalize_transport_token(raw_transport if raw_transport is not None else raw_mode) if "enabled" in data: enabled = _coerce_bool(data.get("enabled"), False) elif raw_mode is not None: - # The ``mode`` alias (and only ``mode``) infers enabled: - # ``off`` disables, anything else enables. enabled = _normalize_transport_token(raw_mode) != "off" else: enabled = False @@ -763,32 +607,18 @@ class StreamingConfig: return cls( enabled=enabled, transport=transport, - edit_interval=_coerce_float( - data.get("edit_interval"), DEFAULT_STREAMING_EDIT_INTERVAL, - ), - buffer_threshold=_coerce_int( - data.get("buffer_threshold"), DEFAULT_STREAMING_BUFFER_THRESHOLD, - ), + edit_interval=_coerce_float(data.get("edit_interval"), DEFAULT_STREAMING_EDIT_INTERVAL), + buffer_threshold=_coerce_int(data.get("buffer_threshold"), DEFAULT_STREAMING_BUFFER_THRESHOLD), cursor=data.get("cursor", DEFAULT_STREAMING_CURSOR), - fresh_final_after_seconds=_coerce_float( - data.get("fresh_final_after_seconds"), 0.0 - ), + fresh_final_after_seconds=_coerce_float(data.get("fresh_final_after_seconds"), 0.0), ) -# ----------------------------------------------------------------------------- -# Built-in platform connection checkers -# ----------------------------------------------------------------------------- -# Each callable receives a ``PlatformConfig`` and returns ``True`` when the -# platform is sufficiently configured to be considered "connected". Platforms -# that rely on the generic ``token or api_key`` check (Telegram, Discord, -# Slack, Matrix, Mattermost, HomeAssistant) do not need an entry here. def _has_usable_api_server_key(key: object) -> bool: - """True when API_SERVER_KEY is present and strong enough to be usable. + """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``) so the platform is only - enrolled at load time when the adapter would actually agree to start. + (``has_usable_secret`` with ``min_length=16``). """ if not key: return False @@ -799,152 +629,96 @@ def _has_usable_api_server_key(key: object) -> bool: return has_usable_secret(key, min_length=16) +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. _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: lambda cfg: bool( - cfg.extra.get("phone_number_id") and cfg.extra.get("access_token") - ), - Platform.SIGNAL: lambda cfg: bool(cfg.extra.get("http_url")), - Platform.API_SERVER: lambda cfg: _has_usable_api_server_key( - cfg.extra.get("key") if cfg else None - ), + 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"), + Platform.SIGNAL: _needs_extra("http_url"), + Platform.API_SERVER: lambda cfg: _has_usable_api_server_key(cfg.extra.get("key") if cfg else None), Platform.WEBHOOK: lambda cfg: True, - Platform.MSGRAPH_WEBHOOK: lambda cfg: bool( - str(cfg.extra.get("client_state") or "").strip() - ), - Platform.BLUEBUBBLES: lambda cfg: bool( - cfg.extra.get("server_url") and cfg.extra.get("password") - ), - Platform.QQBOT: lambda cfg: bool( - cfg.extra.get("app_id") and cfg.extra.get("client_secret") - ), - Platform.YUANBAO: lambda cfg: bool( - cfg.extra.get("app_id") and cfg.extra.get("app_secret") - ), - # Relay dials OUT to a connector; it is "connected" once an endpoint URL is - # configured (extra["relay_url"] or extra["url"]). The capability descriptor - # is negotiated at handshake time, so the URL is the only config-level - # signal in the experimental phase. EXPERIMENTAL — may change. - Platform.RELAY: lambda cfg: bool( - cfg.extra.get("relay_url") or cfg.extra.get("url") - ), + Platform.MSGRAPH_WEBHOOK: lambda cfg: bool(str(cfg.extra.get("client_state") or "").strip()), + 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. + Platform.RELAY: lambda cfg: bool(cfg.extra.get("relay_url") or cfg.extra.get("url")), } @dataclass class GatewayConfig: - """ - Main gateway configuration. - - Manages all platform connections, session policies, and delivery settings. - """ - # Platform configurations + """Main gateway configuration: platform connections, session policies, delivery settings.""" platforms: Dict[Platform, PlatformConfig] = field(default_factory=dict) - - # Session reset policies by type default_reset_policy: SessionResetPolicy = field(default_factory=SessionResetPolicy) reset_by_type: Dict[str, SessionResetPolicy] = field(default_factory=dict) reset_by_platform: Dict[Platform, SessionResetPolicy] = field(default_factory=dict) - - # Reset trigger commands reset_triggers: List[str] = field(default_factory=lambda: ["/new", "/reset"]) - - # User-defined quick commands (slash commands that bypass the agent loop) + # Slash commands that bypass the agent loop. quick_commands: Dict[str, Any] = field(default_factory=dict) - - # Storage paths sessions_dir: Path = field(default_factory=lambda: get_hermes_home() / "sessions") - - # Whether to keep writing the legacy sessions.json mirror of the gateway - # routing index. The primary copy lives in state.db (gateway_routing - # table, #9006). Default True for backward compatibility with external - # tooling and downgrade safety; set gateway.write_sessions_json: false in - # config.yaml to stop producing the file. + # 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. write_sessions_json: bool = True - - # Delivery settings always_log_local: bool = True # Always save cron outputs to local files - # Drop outbound "silence narration" messages (e.g. *(silent)*, 🔇, a bare - # ".") pre-send. These are model hallucinations emitted when a persona has - # nothing actionable to say; in bot-to-bot channels they mirror back and - # forth, burning tokens and crashing models. Substrate-level guard that - # survives SOUL.md/prompt drift across providers. Opt out with False for - # raw passthrough. + # 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. filter_silence_narration: bool = True - - # STT settings - stt_enabled: bool = True # Whether to auto-transcribe inbound voice messages - stt_echo_transcripts: bool = True # Whether to echo raw STT transcripts back to the user - - # Session isolation in shared chats - group_sessions_per_user: bool = True # Isolate group/channel sessions per participant when user IDs are available - thread_sessions_per_user: bool = False # When False (default), threads are shared across all participants - max_concurrent_sessions: Optional[int] = None # Positive int caps simultaneous active chat sessions - - # Multi-profile multiplexing (opt-in; default off preserves one-gateway-per-profile). - # When True, the default profile's gateway serves inbound messages for every - # profile on the host: profiles are stamped into session keys and (in later - # phases) per-profile adapters/credentials are resolved. When False, the - # gateway behaves exactly as before — single HERMES_HOME, no profile stamping. + 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. multiplex_profiles: bool = False - # Optional named-profile allowlist for multiplex mode. None preserves the - # historical serve-all behavior; [] serves only the default profile. + # None = historical serve-all; [] = default profile only. multiplex_profile_allowlist: Optional[List[str]] = None - - # Public HTTPS endpoint another gateway may use for scoped RoomLink calls. - # Disabled by default: setting an API key alone must never expose or - # advertise a route. HERMES_ROOM_LINK_URL remains the operator override. + # Public HTTPS endpoint for scoped RoomLink calls. Disabled by default: 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 preserves Type=simple and - # disables sd_notify at runtime. + # 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 (#69089). A daemon OS thread - # probes the gateway loop with call_soon_threadsafe; after consecutive - # missed probes it dumps all-thread stacks and hard-exits with the - # service-restart code so the supervisor can revive the process. On by - # default; set gateway.loop_watchdog: false in config.yaml to disable. - # - # Tuning knobs (all seconds unless noted) make the watchdog tolerate - # *transient, self-recovering* event-loop stalls — e.g. Telegram/Discord - # reconnect doing synchronous socket I/O during a network blip — so a - # short block does not force exit code 75 and trigger a restart churn - # that stalls cron dispatch (recurring fleet incidents on 2026-08-17, - # kanban t_0f76430f/t_70483f23). A genuine wedge (event loop frozen for - # the full tolerance window) still escalates to a supervised restart. + # 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. loop_watchdog: bool = True - # Seconds the watchdog waits between liveness probes. loop_watchdog_probe_interval_s: float = DEFAULT_LOOP_WATCHDOG_INTERVAL_S - # Seconds a single probe may go unprocessed before it counts as a miss. loop_watchdog_probe_timeout_s: float = DEFAULT_LOOP_WATCHDOG_TIMEOUT_S - # Consecutive missed probes allowed before the watchdog hard-exits. - # Default stays at 3 (~90-120s of sustained loop block): the transient - # 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 fleet-wide would only delay genuine-wedge recovery. + # 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. loop_watchdog_max_strikes: int = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES - - # Unauthorized DM policy unauthorized_dm_behavior: str = "pair" # "pair" or "ignore" - - # Streaming configuration streaming: StreamingConfig = field(default_factory=StreamingConfig) - - # Session store pruning: drop SessionEntry records older than this many - # days from the in-memory dict and sessions.json. Keeps the store from - # growing unbounded in gateways serving many chats/threads/users over - # months. Pruning is invisible to users — if they resume, they get a - # fresh session exactly as if the reset policy had fired. 0 = disabled. + # Drop SessionEntry records older than this from the store and sessions.json. + # Invisible to users (a resumed chat gets a fresh session). 0 = disabled. session_store_max_age_days: int = 90 - - # Profile-based routing: route specific guilds/channels/threads to - # different profiles. See gateway/profile_routing.py. Each entry is a - # dict with: name, platform, profile, and optional guild_id/chat_id/thread_id. + # Route guilds/channels/threads to profiles (gateway/profile_routing.py). profile_routes: list = field(default_factory=list) + # Scalar fields serialized verbatim by ``to_dict`` (in output order). + _SCALAR_DICT_FIELDS = ( + "write_sessions_json", "always_log_local", "filter_silence_narration", "stt_enabled", + "stt_echo_transcripts", "group_sessions_per_user", "thread_sessions_per_user", + "max_concurrent_sessions", "multiplex_profiles", "multiplex_profile_allowlist", + "room_link_url", "systemd_watchdog_seconds", "loop_watchdog", + "loop_watchdog_probe_interval_s", "loop_watchdog_probe_timeout_s", + "loop_watchdog_max_strikes", "unauthorized_dm_behavior", + ) + def __post_init__(self) -> None: self.multiplex_profile_allowlist = _normalize_multiplex_profile_allowlist( self.multiplex_profile_allowlist @@ -954,13 +728,10 @@ class GatewayConfig: ) def get_connected_platforms(self) -> List[Platform]: - """Return list of platforms that are enabled and configured. + """Enabled + configured platforms, sorted by value. - Sorted by platform value so the rendered "Connected Platforms" list - (and the home-channel blocks derived from it) is byte-stable across - gateway restarts and mid-process platform registration — dict - insertion order is not a stable contract and a reorder busts the - prompt cache without any semantic change. + Sorted so the rendered "Connected Platforms" list is byte-stable across + restarts and mid-process registration: a reorder busts the prompt cache. """ connected = [ platform @@ -970,25 +741,17 @@ class GatewayConfig: return sorted(connected, key=lambda p: str(p.value)) def _is_platform_connected(self, platform: Platform, config: PlatformConfig) -> bool: - """Check whether a single platform is sufficiently configured.""" checker = _PLATFORM_CONNECTED_CHECKERS.get(platform) - # Weixin requires both a token and an account_id (checked first so - # the generic token branch doesn't let it through without account_id). + # Weixin needs token AND account_id, so it must bypass the generic token branch. if platform == Platform.WEIXIN: return checker(config) - - # Generic token/api_key auth covers Telegram, Discord, Slack, etc. if config.token or config.api_key: return True - - # Platform-specific check if checker is not None: return checker(config) - # Plugin-registered platforms. Force plugin discovery first so this - # works even when GatewayConfig is constructed directly (e.g. in tests - # or callers that bypass load_gateway_config(), which is what triggers - # discovery in the normal path). discover_plugins() is idempotent. + # Plugin-registered platforms. Force (idempotent) plugin discovery so this + # works when GatewayConfig is constructed directly, bypassing load_gateway_config(). try: from gateway.platform_registry import platform_registry try: @@ -1005,74 +768,44 @@ class GatewayConfig: return True except Exception: pass # Registry not yet initialised during early import - return False - + def get_home_channel(self, platform: Platform) -> Optional[HomeChannel]: - """Get the home channel for a platform.""" config = self.platforms.get(platform) return config.home_channel if config else None - + def get_reset_policy( - self, + self, platform: Optional[Platform] = None, session_type: Optional[str] = None ) -> SessionResetPolicy: - """ - Get the appropriate reset policy for a session. - - Priority: platform override > type override > default - """ - # Platform-specific override takes precedence + """Priority: platform override > type override > default.""" if platform and platform in self.reset_by_platform: return self.reset_by_platform[platform] - - # Type-specific override (dm, group, thread) if session_type and session_type in self.reset_by_type: return self.reset_by_type[session_type] - return self.default_reset_policy - + def to_dict(self) -> Dict[str, Any]: - return { - "platforms": { - p.value: c.to_dict() for p, c in self.platforms.items() - }, + result: Dict[str, Any] = { + "platforms": {p.value: c.to_dict() for p, c in self.platforms.items()}, "default_reset_policy": self.default_reset_policy.to_dict(), - "reset_by_type": { - k: v.to_dict() for k, v in self.reset_by_type.items() - }, - "reset_by_platform": { - p.value: v.to_dict() for p, v in self.reset_by_platform.items() - }, + "reset_by_type": {k: v.to_dict() for k, v in self.reset_by_type.items()}, + "reset_by_platform": {p.value: v.to_dict() for p, v in self.reset_by_platform.items()}, "reset_triggers": self.reset_triggers, "quick_commands": self.quick_commands, "sessions_dir": str(self.sessions_dir), - "write_sessions_json": self.write_sessions_json, - "always_log_local": self.always_log_local, - "filter_silence_narration": self.filter_silence_narration, - "stt_enabled": self.stt_enabled, - "stt_echo_transcripts": self.stt_echo_transcripts, - "group_sessions_per_user": self.group_sessions_per_user, - "thread_sessions_per_user": self.thread_sessions_per_user, - "max_concurrent_sessions": self.max_concurrent_sessions, - "multiplex_profiles": self.multiplex_profiles, - "multiplex_profile_allowlist": self.multiplex_profile_allowlist, - "room_link_url": self.room_link_url, - "systemd_watchdog_seconds": self.systemd_watchdog_seconds, - "loop_watchdog": self.loop_watchdog, - "loop_watchdog_probe_interval_s": self.loop_watchdog_probe_interval_s, - "loop_watchdog_probe_timeout_s": self.loop_watchdog_probe_timeout_s, - "loop_watchdog_max_strikes": self.loop_watchdog_max_strikes, - "unauthorized_dm_behavior": self.unauthorized_dm_behavior, - "streaming": self.streaming.to_dict(), - "session_store_max_age_days": self.session_store_max_age_days, - "profile_routes": [ - asdict(r) if is_dataclass(r) and not isinstance(r, type) else r - for r in self.profile_routes - ], } - + for name in self._SCALAR_DICT_FIELDS: + result[name] = getattr(self, name) + result["streaming"] = self.streaming.to_dict() + result["session_store_max_age_days"] = self.session_store_max_age_days + result["profile_routes"] = [ + asdict(r) if is_dataclass(r) and not isinstance(r, type) else r + for r in self.profile_routes + ] + return result + @classmethod def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig": data = _coerce_dict(data) @@ -1082,6 +815,10 @@ class GatewayConfig: """Top-level key wins by presence; else the nested ``gateway.`` form.""" return data[key] if key in data else nested_gateway.get(key) + def key_label(key: str) -> str: + """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): @@ -1110,10 +847,6 @@ class GatewayConfig: if not isinstance(room_link_url, str): room_link_url = None - # Key prefix for the warning: "gateway." when the nested form was the one consulted. - def key_label(key: str) -> str: - return key if key in data else f"gateway.{key}" - # 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: @@ -1129,14 +862,10 @@ class GatewayConfig: pick("systemd_watchdog_seconds"), key_label("systemd_watchdog_seconds") ) - # Multiplexing is a genuine 3-tier chain: 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 so the single multiplexed gateway the - # connector depends on is forced on at every boot regardless of the image's config.yaml); - # a blank or unrecognized env value falls through to config — a provisioned-but- - # unpopulated Fly secret must not shadow a config.yaml opt-in. Config side: the - # top-level VALUE wins when not None, else ``gateway.multiplex_profiles`` (written by - # ``hermes config set gateway.multiplex_profiles true``). + # 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``. multiplex_profiles = data.get("multiplex_profiles") if multiplex_profiles is None: multiplex_profiles = nested_gateway.get("multiplex_profiles") @@ -1153,9 +882,7 @@ class GatewayConfig: except (TypeError, ValueError): session_store_max_age_days = 90 - # Parse profile routes (validated by gateway.profile_routing) from gateway.profile_routing import parse_profile_routes - profile_routes = parse_profile_routes(data.get("profile_routes") or []) return cls( platforms=platforms, @@ -1191,15 +918,15 @@ class GatewayConfig: ), streaming=StreamingConfig.from_dict(data.get("streaming", {})), session_store_max_age_days=session_store_max_age_days, - profile_routes=profile_routes, + profile_routes=parse_profile_routes(data.get("profile_routes") or []), ) def get_unauthorized_dm_behavior(self, platform: Optional[Platform] = None) -> str: - """Return the effective unauthorized-DM behavior for a platform. + """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 - into pairing. A global default does not opt email into pairing. + unless ``platforms.email.unauthorized_dm_behavior`` explicitly opts in; + a global default does not opt email into pairing. """ if platform: platform_cfg = self.platforms.get(platform) @@ -1214,7 +941,7 @@ class GatewayConfig: return self.unauthorized_dm_behavior def get_notice_delivery(self, platform: Optional[Platform] = None) -> str: - """Return the effective notice-delivery mode for a platform.""" + """Effective notice-delivery mode ("public"/"private") for a platform.""" if platform: platform_cfg = self.platforms.get(platform) if platform_cfg and "notice_delivery" in platform_cfg.extra: @@ -1225,15 +952,7 @@ class GatewayConfig: def load_gateway_config() -> GatewayConfig: - """ - Load gateway configuration from multiple sources. - - Priority (highest to lowest): - 1. Environment variables - 2. ~/.hermes/config.yaml (primary user-facing config) - 3. ~/.hermes/gateway.json (legacy — provides defaults under config.yaml) - 4. Built-in defaults - """ + """Load gateway configuration. Priority: env > ~/.hermes/config.yaml > legacy gateway.json > defaults.""" from gateway import config_loader _home = get_hermes_home() @@ -1255,11 +974,7 @@ def load_gateway_config() -> GatewayConfig: def _validate_gateway_config(config: "GatewayConfig") -> None: - """Validate and sanitize a loaded GatewayConfig in place. - - Called by ``load_gateway_config()`` after all config sources are merged. - Extracted as a separate function for testability. - """ + """Validate and sanitize a loaded GatewayConfig in place (after all sources are merged).""" policy = config.default_reset_policy if not (0 <= policy.at_hour <= 23): @@ -1275,8 +990,7 @@ def _validate_gateway_config(config: "GatewayConfig") -> None: ) policy.idle_minutes = 1440 - # Warn about empty bot tokens — platforms that loaded an empty string - # won't connect and the cause can be confusing without a log line. + # An empty token won't connect and the cause is confusing without a log line. for platform, pconfig in config.platforms.items(): if not pconfig.enabled: continue @@ -1288,10 +1002,8 @@ def _validate_gateway_config(config: "GatewayConfig") -> None: platform.value, env_name, ) - # Reject known-weak placeholder tokens. - # Ported from openclaw/openclaw#64586: users who copy .env.example - # without changing placeholder values get a clear startup error instead - # of a confusing "auth failed" from the platform API. + # Reject known-weak placeholder tokens (copied .env.example) with a clear + # startup error instead of a confusing "auth failed" from the platform API. try: from hermes_cli.auth import has_usable_secret except ImportError: diff --git a/gateway/config_env.py b/gateway/config_env.py index fc56881975..0b90e0980c 100644 --- a/gateway/config_env.py +++ b/gateway/config_env.py @@ -2,9 +2,9 @@ Runs after ``GatewayConfig.from_dict`` so env always wins over config.yaml / gateway.json. Most platforms follow one shape — "credentials present in env -⇒ enable the platform and copy the values into ``extra``" — and are declared -as ``_Cred`` rows in ``_ENV_STEPS`` (source order = application order). -Platforms with unique gating live as small functions in the same table. +⇒ enable the platform and copy the values into ``extra``" — declared as +``_Cred`` rows in ``_ENV_STEPS`` (source order = application order). +Platforms with unique gating are small functions in the same table. """ import contextlib @@ -13,7 +13,7 @@ import logging import os from dataclasses import dataclass from functools import partial -from typing import Any, Callable, Dict, List, Optional +from typing import Any, Callable, Dict, Optional from gateway.config import ( GatewayConfig, @@ -30,15 +30,13 @@ logger = logging.getLogger("gateway.config") getenv = _getenv_str -# Platforms for which the "explicitly disabled in config.yaml, but credentials -# are present in the environment" WARNING has already been emitted in this -# process. Config reloads on every turn, so the notice is one-time per platform -# per process — loud once at startup, never a per-turn drumbeat. +# Platforms already warned about "explicitly disabled in config.yaml, but +# credentials present in env". Config reloads every turn, so the notice is +# one-time per platform per process. _EXPLICIT_DISABLE_WARNED: set = set() - # Env var(s) whose presence drives each platform's env-enable branch, named in -# the explicit-disable WARNING below. +# the explicit-disable WARNING. _ENV_ENABLE_CREDENTIALS: dict = { Platform.TELEGRAM: ("TELEGRAM_BOT_TOKEN",), Platform.DISCORD: ("DISCORD_BOT_TOKEN",), @@ -65,10 +63,9 @@ _ENV_ENABLE_CREDENTIALS: dict = { def _warn_explicit_disable_beats_env(platform: Platform) -> None: """One-time WARNING: ``platforms..enabled: false`` wins over env creds. - Until #48820 credential presence force-enabled twelve platforms regardless - of an explicit ``enabled: false``; users relying on "creds in .env = - platform on" need to be told why it went dark. Names the platform, the - winning config key, and the env var(s) that used to override it. + 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. """ if platform in _EXPLICIT_DISABLE_WARNED: return @@ -88,12 +85,12 @@ def _warn_explicit_disable_beats_env(platform: Platform) -> None: # --- small value parsers ----------------------------------------------------- -def _csv_list(value: str) -> List[str]: +def _csv_list(value: str) -> list: return [part.strip() for part in value.split(",") if part.strip()] def _int_or(default: int) -> Callable[[str], int]: - """``int(raw.strip(), 10)`` with *default* on malformed/blank input (``_getenv_int`` semantics).""" + """``int(raw.strip(), 10)`` with *default* on malformed/blank input.""" def parse(raw: str) -> int: try: return int(str(raw).strip(), 10) @@ -121,11 +118,7 @@ def _env_first(envs) -> str: """First truthy value among *envs* (a single name or a tuple of alternatives).""" if isinstance(envs, str): return getenv(envs) - for env in envs: - value = getenv(env) - if value: - return value - return "" + return next((v for v in map(getenv, envs) if v), "") # --- reusable steps ----------------------------------------------------------- @@ -136,8 +129,8 @@ _INT = object() # spec marker: ``int(value)``, silently skipped when malformed def _env_extras(extra: Dict[str, Any], spec, *, strip: bool = False) -> None: """``extra[key] = fn(value)`` for each ``(key, env[, fn])`` whose env value is truthy. - With ``strip=True`` the value is stripped BEFORE the truthiness check. ``fn=_INT`` parses an - int and silently ignores a non-integer value. + ``strip=True`` strips BEFORE the truthiness check. ``fn=_INT`` parses an int + and silently ignores a non-integer value. """ for key, env, *fn in spec: value = getenv(env) @@ -175,8 +168,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 later - also needs it. The marker is scrubbed for all platforms at the end of ``_apply_env_overrides``. + READS (does not pop) the ``_enabled_explicit`` marker: the registry-driven + plugin-enable pass also needs it; ``_scrub_explicit_markers`` removes it last. """ if platform not in config.platforms: config.platforms[platform] = PlatformConfig(enabled=True) @@ -184,7 +177,6 @@ def _enable_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfi platform_config = config.platforms[platform] if not platform_config.enabled: if platform_config.extra.get("_enabled_explicit", False): - # Credentials are present (that is why we are here) but the user said no in config.yaml. _warn_explicit_disable_beats_env(platform) else: platform_config.enabled = True @@ -194,10 +186,10 @@ 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. - In multiplex mode a secondary profile pins ``platforms..enabled: false`` so it shares the - default profile's listener instead of binding its own port, yet still inherits the process env; - without this guard the env presence would force-enable the listener and trip MultiplexConfigError. - POPs the ``_enabled_explicit`` marker: these branches are terminal (no later registry pass). + In multiplex mode a secondary profile pins ``platforms..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. """ platform_config = config.platforms.setdefault(platform, PlatformConfig()) explicit = platform_config.extra.pop("_enabled_explicit", False) @@ -211,11 +203,13 @@ 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``. - ``fixed``: ``(extra_key, env[, default[, fn]])`` always written once enabled (``env`` may be a - tuple of alternatives). ``optional`` / ``optional_stripped``: ``_env_extras`` specs, written only - when truthy. ``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. + ``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. """ platform: Platform creds: tuple @@ -268,14 +262,12 @@ def _telegram_fallback_ips(config: GatewayConfig) -> None: def _whatsapp(config: GatewayConfig) -> None: - """WhatsApp (Baileys bridge) uses a flag, not credentials.""" + """WhatsApp (Baileys bridge) uses a flag, not credentials; an explicit false overrides YAML.""" raw = getenv("WHATSAPP_ENABLED") enabled = is_truthy_value(raw) - disabled_explicitly = raw.lower() in {"false", "0", "no"} - if Platform.WHATSAPP in config.platforms: - # YAML config exists — respect explicit disable; otherwise keep whatever the YAML set. - wa_cfg = config.platforms[Platform.WHATSAPP] - if disabled_explicitly: + wa_cfg = config.platforms.get(Platform.WHATSAPP) + if wa_cfg is not None: + if raw.lower() in {"false", "0", "no"}: wa_cfg.enabled = False elif enabled: wa_cfg.enabled = True @@ -283,34 +275,23 @@ def _whatsapp(config: GatewayConfig) -> None: config.platforms[Platform.WHATSAPP] = PlatformConfig(enabled=True) -def _slack(config: GatewayConfig) -> None: - slack_token = getenv("SLACK_BOT_TOKEN") - if slack_token: - if Platform.SLACK not in config.platforms: - config.platforms[Platform.SLACK] = PlatformConfig(enabled=True) - else: - slack_config = config.platforms[Platform.SLACK] - if not slack_config.enabled and not slack_config.extra.get("_enabled_explicit", False): - # Top-level Slack settings such as channel prompts must not turn an env-token setup - # into a disabled platform; only an explicit enabled: false should. - slack_config.enabled = True - elif not slack_config.enabled: - _warn_explicit_disable_beats_env(Platform.SLACK) - # Token is stored even when yaml disables the adapter so Slack-sending skills can use it. - config.platforms[Platform.SLACK].token = slack_token +def _slack_home(config: GatewayConfig) -> None: + """SLACK_HOME_CHANNEL creates a disabled Slack entry if needed and keeps + user_id/scope_id provenance when the chat_id is unchanged.""" slack_home = getenv("SLACK_HOME_CHANNEL") - if slack_home: - slack_config = config.platforms.setdefault(Platform.SLACK, PlatformConfig(enabled=False)) - 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, - user_id=existing_home.user_id if same_home else None, - scope_id=existing_home.scope_id if same_home else None, - ) + if not slack_home: + return + slack_config = config.platforms.setdefault(Platform.SLACK, PlatformConfig(enabled=False)) + 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, + user_id=existing_home.user_id if same_home else None, + scope_id=existing_home.scope_id if same_home else None, + ) def _matrix_e2ee(config: GatewayConfig, matrix_config: PlatformConfig) -> None: @@ -324,15 +305,13 @@ def _matrix_e2ee(config: GatewayConfig, matrix_config: PlatformConfig) -> None: _env_extras(matrix_config.extra, (("device_id", "MATRIX_DEVICE_ID"),)) -def _sms(config: GatewayConfig) -> None: - if getenv("TWILIO_ACCOUNT_SID"): - _enable_from_env(config, Platform.SMS).api_key = getenv("TWILIO_AUTH_TOKEN") +def _sms_api_key(config: GatewayConfig, sms_config: PlatformConfig) -> None: + sms_config.api_key = getenv("TWILIO_AUTH_TOKEN") def _api_server(config: GatewayConfig) -> None: - """Require a usable key: API_SERVER_ENABLED alone would load an unauthenticated platform whose - adapter refuses to start at connect() anyway, leaving the reconnect watcher spinning forever. - Same strength bar as the startup guard (has_usable_secret, min_length=16).""" + """Require a usable key: API_SERVER_ENABLED alone would load an unauthenticated + platform whose adapter refuses to start, leaving the reconnect watcher spinning.""" key = getenv("API_SERVER_KEY") if not _has_usable_api_server_key(key): return @@ -365,8 +344,8 @@ def _msgraph_webhook(config: GatewayConfig) -> None: ): return msgraph_cfg = config.platforms.setdefault(Platform.MSGRAPH_WEBHOOK, PlatformConfig()) - # Same explicit-disable guard as the webhook branch, but READ (don't pop) the marker: - # the relay-exclusive pass below still consults it; the end-of-function scrub removes it. + # 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. 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),)) @@ -383,9 +362,8 @@ def _qq_home(config: GatewayConfig, qq_config: PlatformConfig) -> None: name_env = "QQBOT_HOME_CHANNEL_NAME" if not qq_home: # Back-compat: accept the pre-rename name and log a one-time warning. - legacy_home = getenv("QQ_HOME_CHANNEL").strip() - if legacy_home: - qq_home = legacy_home + qq_home = getenv("QQ_HOME_CHANNEL").strip() + if qq_home: name_env = "QQ_HOME_CHANNEL_NAME" logger.warning( "QQ_HOME_CHANNEL is deprecated; rename to QQBOT_HOME_CHANNEL " @@ -411,12 +389,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: the active installer used to be wired as ``check_fn`` and this - sweep pip-installed SDKs on every ``load_gateway_config()`` call, boot-looping the desktop app). - ``is_connected`` MUST gate enablement: ``check_fn`` alone ("is the SDK importable?") would enable - platforms the user never configured and the gateway would retry-connect forever with no token. + 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. """ try: from hermes_cli.plugins import discover_plugins @@ -429,43 +407,31 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None: logger.debug("unknown platform name %r: %s", entry.name, e) continue existing_cfg = config.platforms.get(platform) + already_enabled = existing_cfg is not None and existing_cfg.enabled + existing_extra = dict(existing_cfg.extra or {}) if existing_cfg is not None else {} # Never re-enable a platform the user explicitly disabled (marker set by the YAML loader). - if ( - existing_cfg is not None - and not existing_cfg.enabled - and bool((existing_cfg.extra or {}).get("_enabled_explicit", False)) - ): + 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 candidate extras so plugins whose ``is_connected`` reads ``config.extra`` + # (Google Chat) see the same state they will after enablement. seed_for_probe = None if entry.env_enablement_fn is not None: try: seed_for_probe = entry.env_enablement_fn() except Exception as e: logger.debug("env_enablement_fn for %s raised: %s", entry.name, e) - seed_for_probe = None has_seed = isinstance(seed_for_probe, dict) and bool(seed_for_probe) - # Only consult is_connected for platforms not already enabled by YAML/env (keep that decision). - if (existing_cfg is None or not existing_cfg.enabled) and entry.is_connected is not 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 with ``enabled=True``: we ask "would this be configured if enabled?" — - # some ``is_connected`` short-circuit on ``config.enabled`` being False. - probe_cfg = existing_cfg - if probe_cfg is None or not probe_cfg.enabled: - probe_cfg = PlatformConfig( - enabled=True, - extra=dict(existing_cfg.extra or {}) if existing_cfg is not None else {}, - ) + # Probe a transient ``enabled=True`` view (some ``is_connected`` + # short-circuit on ``config.enabled``); never mutate ``existing_cfg``. if has_seed: - # Transient view; never mutate ``existing_cfg`` for the probe. - probe_extra = dict(probe_cfg.extra or {}) for k, v in seed_for_probe.items(): if k != "home_channel": - probe_extra.setdefault(k, v) - probe_cfg = PlatformConfig(enabled=True, extra=probe_extra) - configured = bool(entry.is_connected(probe_cfg)) + existing_extra.setdefault(k, v) + configured = bool(entry.is_connected(PlatformConfig(enabled=True, extra=existing_extra))) except Exception as exc: logger.debug("is_connected for %s raised: %s — skipping enablement", entry.name, exc) configured = False @@ -486,8 +452,8 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None: continue platform_config = config.platforms.setdefault(platform, PlatformConfig()) platform_config.enabled = True - # Commit the env-seeded extras (reuse the probe result; don't call env_enablement_fn twice). if has_seed: + # Commit the env-seeded extras (reuse the probe result; don't call env_enablement_fn twice). seed = dict(seed_for_probe) home = seed.pop("home_channel", None) platform_config.extra.update(seed) @@ -503,19 +469,18 @@ def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None: def _relay(config: GatewayConfig) -> None: - """Relay (generic connector-fronted platform, EXPERIMENTAL). Enabled by GATEWAY_RELAY_URL (env) - or gateway.relay_url (config.yaml). The adapter dials OUT to the connector (no inbound port), - so it only needs Platform.RELAY present+enabled for start_gateway()'s connect loop. The - connected-checker keys on extra["relay_url"], so the URL is mirrored into extra here. + """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: a GATEWAY_RELAY_URL env stamp marks a connector-fronted 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 live 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 - exclusion set as the scale-to-zero arm gate) are untouched; relay via gateway.relay_url only - keeps the old additive behavior. Opt-out GATEWAY_RELAY_ALLOW_DIRECT_PLATFORMS=true is likewise - a deploy-stamp env var read through the profile-scope-aware getenv. + 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_url_env = getenv("GATEWAY_RELAY_URL").strip() existing_relay = config.platforms.get(Platform.RELAY) @@ -554,10 +519,10 @@ 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. +# 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. _ENV_STEPS: tuple = ( _Cred(Platform.TELEGRAM, ("TELEGRAM_BOT_TOKEN",), token="TELEGRAM_BOT_TOKEN"), _ReplyMode(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"), @@ -568,7 +533,7 @@ _ENV_STEPS: tuple = ( _ReplyMode(Platform.DISCORD, "DISCORD_REPLY_TO_MODE"), _whatsapp, _Home(Platform.WHATSAPP, "WHATSAPP_HOME_CHANNEL"), - # WhatsApp Cloud API (official Business Platform via Meta). Distinct from the Baileys bridge; + # WhatsApp Cloud API (Meta Business Platform). Distinct from the Baileys bridge; # both adapters can run in parallel against different phone numbers. _Cred( Platform.WHATSAPP_CLOUD, ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"), @@ -585,7 +550,8 @@ _ENV_STEPS: tuple = ( ), ), _Home(Platform.WHATSAPP_CLOUD, "WHATSAPP_CLOUD_HOME_CHANNEL"), - _slack, + _Cred(Platform.SLACK, ("SLACK_BOT_TOKEN",), token="SLACK_BOT_TOKEN"), + _slack_home, _Cred( Platform.SIGNAL, ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"), fixed=( @@ -615,7 +581,7 @@ _ENV_STEPS: tuple = ( fixed=(("address", "EMAIL_ADDRESS"), ("imap_host", "EMAIL_IMAP_HOST"), ("smtp_host", "EMAIL_SMTP_HOST")), ), _Home(Platform.EMAIL, "EMAIL_HOME_ADDRESS"), - _sms, + _Cred(Platform.SMS, ("TWILIO_ACCOUNT_SID",), then=_sms_api_key), _Home(Platform.SMS, "SMS_HOME_CHANNEL"), _api_server, _webhook,