The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): table-driven bridge specs in config_loader, compact registry/display/routing docs
Tekniumfb0f7806ee5a
diff --git a/gateway/__init__.py b/gateway/__init__.pyindex 140cc32fc5a..120327026bb 100644--- a/gateway/__init__.py+++ b/gateway/__init__.py@@ -1,13 +1,5 @@-"""-Hermes Gateway - Multi-platform messaging integration.--This module provides a unified gateway for connecting the Hermes agent-to various messaging platforms (Telegram, Discord, WhatsApp, Weixin, and more) with:-- Session management (persistent conversations with reset policies)-- Dynamic context injection (agent knows where messages come from)-- Delivery routing (cron job outputs to appropriate channels)-- Platform-specific toolsets (different capabilities per platform)-"""+"""Hermes Gateway - multi-platform messaging integration (sessions, context+injection, delivery routing, platform-specific toolsets)."""from .config import GatewayConfig, PlatformConfig, HomeChannel, load_gateway_configfrom .session import (@@ -19,17 +11,7 @@ from .session import (from .delivery import DeliveryRouter, DeliveryTarget__all__ = [- # Config- "GatewayConfig",- "PlatformConfig",- "HomeChannel",- "load_gateway_config",- # Session- "SessionContext",- "SessionStore",- "SessionResetPolicy",- "build_session_context_prompt",- # Delivery- "DeliveryRouter",- "DeliveryTarget",+ "GatewayConfig", "PlatformConfig", "HomeChannel", "load_gateway_config",+ "SessionContext", "SessionStore", "SessionResetPolicy", "build_session_context_prompt",+ "DeliveryRouter", "DeliveryTarget",]diff --git a/gateway/config_loader.py b/gateway/config_loader.pyindex abec9891a2a..6ef62d927b7 100644--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@ -62,31 +62,32 @@ def _is_dict(value: Any) -> bool:return isinstance(value, dict)+def _dm_behavior_choice(value: Any, default: str = "pair") -> str:+ return _normalize_choice(value, {"pair", "ignore"}, default)+++def _presence(*keys: str) -> tuple:+ return tuple((k, k, "presence", None, None) for k in keys)++# (yaml key, gw_data key, mode, accept(value) -> bool, transform(value))_TOPLEVEL_BRIDGE: tuple = (("session_reset", "default_reset_policy", "presence", lambda v: bool(v) and isinstance(v, dict), None),("quick_commands", "quick_commands", "none", _quick_commands_ok, None),("stt", "stt", "presence", _is_dict, None),- ("stt_echo_transcripts", "stt_echo_transcripts", "presence", None, None),- ("group_sessions_per_user", "group_sessions_per_user", "presence", None, None),- ("thread_sessions_per_user", "thread_sessions_per_user", "presence", None, None),+ *_presence("stt_echo_transcripts", "group_sessions_per_user", "thread_sessions_per_user"),("multiplex_profiles", "multiplex_profiles", "gwdata", None, None),- ("multiplex_profile_allowlist", "multiplex_profile_allowlist", "presence", None, None),- ("room_link_url", "room_link_url", "presence", None, None),+ *_presence("multiplex_profile_allowlist", "room_link_url"),("profile_routes", "profile_routes", "none", lambda v: isinstance(v, list), None),- ("max_concurrent_sessions", "max_concurrent_sessions", "presence", None, None),+ *_presence("max_concurrent_sessions"),("systemd_watchdog_seconds", "systemd_watchdog_seconds", "nested", None, None),("streaming", "streaming", "dict", None, None),- ("reset_triggers", "reset_triggers", "presence", None, None),- ("always_log_local", "always_log_local", "presence", None, None),- ("write_sessions_json", "write_sessions_json", "presence", None, None),- ("loop_watchdog", "loop_watchdog", "presence", None, None),- ("loop_watchdog_probe_interval_s", "loop_watchdog_probe_interval_s", "presence", None, None),- ("loop_watchdog_probe_timeout_s", "loop_watchdog_probe_timeout_s", "presence", None, None),- ("loop_watchdog_max_strikes", "loop_watchdog_max_strikes", "presence", None, None),- ("filter_silence_narration", "filter_silence_narration", "presence", None, None),- ("unauthorized_dm_behavior", "unauthorized_dm_behavior", "presence", None,- lambda v: _normalize_choice(v, {"pair", "ignore"}, "pair")),+ *_presence(+ "reset_triggers", "always_log_local", "write_sessions_json", "loop_watchdog",+ "loop_watchdog_probe_interval_s", "loop_watchdog_probe_timeout_s", "loop_watchdog_max_strikes",+ "filter_silence_narration",+ ),+ ("unauthorized_dm_behavior", "unauthorized_dm_behavior", "presence", None, _dm_behavior_choice),)@@ -153,21 +154,10 @@ def merge_platform_sections(yaml_cfg: dict, gateway_cfg: Any, gw_data: dict) ->merged["extra"] = merged_extraplatforms_data[plat_name] = merged- gateway_platforms = gateway_cfg.get("platforms") if isinstance(gateway_cfg, dict) else None- merge(gateway_platforms)+ nested_gateway = gateway_cfg if isinstance(gateway_cfg, dict) else {}+ merge(nested_gateway.get("platforms"))merge(yaml_cfg.get("platforms"))- if isinstance(gateway_cfg, dict):- nested: dict = {}- for key, value in gateway_cfg.items():- if key == "platforms":- continue- try:- Platform(key)- except (ValueError, AttributeError):- continue- if isinstance(value, dict):- nested[key] = value- merge(nested)+ merge({k: v for k, v in nested_gateway.items() if k != "platforms" and isinstance(v, dict) and _is_platform_name(k)})api_plat = platforms_data.get("api_server")if isinstance(api_plat, dict):@@ -178,6 +168,14 @@ def merge_platform_sections(yaml_cfg: dict, gateway_cfg: Any, gw_data: dict) ->return platforms_data+def _is_platform_name(key: Any) -> bool:+ try:+ Platform(key)+ except (ValueError, AttributeError):+ return False+ return True++def platform_section(yaml_cfg: dict, name: str, gateway_platforms: Any) -> tuple:"""Return ``(section, is_toplevel)`` for platform *name*.@@ -199,43 +197,32 @@ def _str_keyed(value: Any) -> Any:return {str(k): v for k, v in value.items()} if isinstance(value, dict) else value-def _dm_behavior(gw_data: dict):- return lambda v: _normalize_choice(v, {"pair", "ignore"}, gw_data.get("unauthorized_dm_behavior", "pair"))--_TELEGRAM = frozenset({Platform.TELEGRAM})_DISCORD_SLACK = frozenset({Platform.DISCORD, Platform.SLACK})-# Keys copied from a platform's YAML section into ``extra`` (``None`` = every platform);-# third element transforms the value.+def _plain(*keys: str) -> tuple:+ """Keys copied verbatim into ``extra`` for every platform."""+ return tuple((k, None, None) for k in keys)+++# (key, platforms-or-None, transform-or-None), in ``extra`` insertion order.+# ``"dm"`` defers to the global unauthorized_dm_behavior._SHARED_KEYS: tuple = (("unauthorized_dm_behavior", None, "dm"),("notice_delivery", None, lambda v: _normalize_choice(v, {"public", "private"}, "public")),- ("reply_prefix", None, None),- ("reply_in_thread", None, None),- ("cron_continuable_surface", None, None),- ("require_mention", None, None),- ("send_read_receipts", None, None),+ *_plain("reply_prefix", "reply_in_thread", "cron_continuable_surface", "require_mention", "send_read_receipts"),("allowed_chats", _TELEGRAM, None),("group_allowed_chats", _TELEGRAM, None),("allowed_topics", _TELEGRAM, None),- ("free_response_channels", None, None),- ("mention_patterns", None, None),- ("exclusive_bot_mentions", None, None),+ *_plain("free_response_channels", "mention_patterns", "exclusive_bot_mentions"),("observe_unmentioned_group_messages", _TELEGRAM, None),- ("dm_policy", None, None),- ("allow_from", None, None),- ("allow_admin_from", None, None),- ("user_allowed_commands", None, None),- ("group_policy", None, None),- ("group_allow_from", None, None),- ("group_allow_admin_from", None, None),- ("group_user_allowed_commands", None, None),+ *_plain(+ "dm_policy", "allow_from", "allow_admin_from", "user_allowed_commands",+ "group_policy", "group_allow_from", "group_allow_admin_from", "group_user_allowed_commands",+ ),("channel_skill_bindings", _DISCORD_SLACK, None),("channel_prompts", None, _str_keyed),- ("gateway_restart_notification", None, None),- ("typing_indicator", None, None),- ("typing_status_text", None, None),+ *_plain("gateway_restart_notification", "typing_indicator", "typing_status_text"),)# Top-level port/host/secret bridged into ``extra`` for adapters that read them from config.extra.@@ -254,8 +241,9 @@ def _bridged_keys(plat: Platform, platform_cfg: dict, gw_data: dict) -> dict:if key not in platform_cfg or (only is not None and plat not in only):continueif transform == "dm":- transform = _dm_behavior(gw_data)- bridged[key] = transform(platform_cfg[key]) if transform else platform_cfg[key]+ bridged[key] = _dm_behavior_choice(platform_cfg[key], gw_data.get("unauthorized_dm_behavior", "pair"))+ else:+ bridged[key] = transform(platform_cfg[key]) if transform else platform_cfg[key]for key in _PORT_BRIDGE_KEYS.get(plat, ()):if key in platform_cfg and key not in platform_cfg.get("extra", {}):bridged[key] = platform_cfg[key]@@ -285,7 +273,7 @@ def bridge_platform_shared_keys(``merge_platform_sections`` already merged it with the correct precedence, and re-applying it herewould overwrite that. An explicit top-level enable/disable sets ``_enabled_explicit`` so the envpass honors ``enabled: false`` for migrated plugin platforms instead of re-enabling them on- token/SDK presence (#41112).+ token/SDK presence."""for plat in targets:if plat == Platform.LOCAL:@@ -315,7 +303,7 @@ def bridge_platform_shared_keys(def apply_plugin_yaml_hooks(yaml_cfg: dict, gateway_platforms: Any, platforms_data: dict, registry) -> None:- """Plugin-owned YAML→env config bridges (``PlatformEntry.apply_yaml_config_fn``, #24836).+ """Plugin-owned YAML→env config bridges (``PlatformEntry.apply_yaml_config_fn``).Order: shared-key loop → this dispatch → core-only bridges (require_mention/signal) →``_apply_env_overrides()`` after ``GatewayConfig.from_dict``.@@ -333,20 +321,16 @@ def apply_plugin_yaml_hooks(yaml_cfg: dict, gateway_platforms: Any, platforms_daexcept Exception as e:logger.debug("apply_yaml_config_fn for %s raised: %s", entry.name, e)continue- if not isinstance(seeded, dict) or not seeded:- continue- _dict_slot(_dict_slot(platforms_data, entry.name), "extra").update(seeded)+ if isinstance(seeded, dict) and seeded:+ _dict_slot(_dict_slot(platforms_data, entry.name), "extra").update(seeded)def bridge_core_env_settings(yaml_cfg: dict, platforms_data: dict) -> None:- """The two YAML→env bridges that stay in core.-- Slack/Telegram/WhatsApp/DingTalk/Mattermost/Matrix/Feishu settings→env bridges migrated to- each plugin's ``apply_yaml_config_fn`` hook (#41112 / #3823 / #25443).+ """The two YAML→env bridges that stay in core (the per-platform ones live in plugin hooks).Top-level ``require_mention`` → Telegram when the ``telegram:`` section has none: users write it- alongside ``group_sessions_per_user`` expecting it to work (#3979). It keys off the TOP-LEVEL key,- so the telegram plugin's hook (which only runs when a telegram block exists) can't cover it.+ alongside ``group_sessions_per_user`` expecting it to work. It keys off the TOP-LEVEL key, so+ the telegram plugin's hook (which only runs when a telegram block exists) can't cover it.Signal ``require_mention`` → ``SIGNAL_REQUIRE_MENTION`` (env wins when already set)."""tl_require_mention = yaml_cfg.get("require_mention")diff --git a/gateway/display_config.py b/gateway/display_config.pyindex a02a62c1373..85ad1fb3e51 100644--- a/gateway/display_config.py+++ b/gateway/display_config.py@@ -1,63 +1,42 @@-"""Per-platform display/verbosity configuration resolver.--``resolve_display_setting()`` is the single entry-point. Resolution order-(first non-None wins):- 1. ``display.platforms.<platform>.<key>`` — explicit per-platform override- 2. ``display.<key>`` — global user setting- 3. ``_PLATFORM_DEFAULTS[<platform>][<key>]`` — built-in platform default- 4. ``_GLOBAL_DEFAULTS[<key>]`` — built-in global default--Exception: ``display.streaming`` is CLI-only. Gateway streaming follows the-top-level ``streaming`` config unless ``display.platforms.<platform>.streaming``-sets an explicit per-platform override.--Backward compatibility: ``display.tool_progress_overrides`` is still read as a-fallback for ``tool_progress`` when no ``display.platforms`` entry exists (a-config migration moves the old format into ``display.platforms``).+"""Per-platform display/verbosity resolver (``resolve_display_setting``).++Resolution order, first non-None wins: ``display.platforms.<platform>.<key>`` →+``display.<key>`` → ``_PLATFORM_DEFAULTS[platform][key]`` → ``_GLOBAL_DEFAULTS[key]``.+Exception: ``display.streaming`` is CLI-only; gateway streaming follows the top-level+``streaming`` config unless a per-platform override sets it. Legacy+``display.tool_progress_overrides`` is still read as a ``tool_progress`` fallback."""from __future__ import annotationsfrom typing import Any-# Settings configurable per-platform, with global defaults. Other display-# settings (compact, personality, skin, ...) are CLI-only.+# Settings configurable per-platform; other display settings are CLI-only._GLOBAL_DEFAULTS: dict[str, Any] = {"tool_progress": "all","tool_progress_grouping": "accumulate", # "accumulate" = edit one bubble; "separate" = one msg per tool"show_reasoning": False,- # Reasoning summary rendering: "code" (💭 **Reasoning:** + fenced block),- # "blockquote" ("> " lines), "subtext" ("-# " Discord small grey text).+ # "code" (💭 **Reasoning:** + fenced block), "blockquote" ("> "), "subtext" ("-# " Discord)."reasoning_style": "code","tool_preview_length": 0,"streaming": None, # None = follow top-level streaming config- # Gateway-only assistant/status chatter; default on for back-compat, mobile- # platforms opt down to final-answer-first.+ # Gateway-only assistant/status chatter; mobile platforms opt down to final-answer-first."interim_assistant_messages": True,"long_running_notifications": True,"busy_ack_detail": True,- # busy_input_mode=steer confirmation echo ("Steered into current run").- # Disabling only suppresses the echo; the text still lands in the run.+ # busy_input_mode=steer echo ("Steered into current run"); the text still lands in the run."busy_steer_ack_enabled": True,- # Delete tool-progress / "⏳ Working" / status bubbles after the final- # response on platforms that support deletion (e.g. Telegram). Off by- # default; progress is still shown live, only cleaned up after success so- # the chat doesn't fill with stale breadcrumbs. Failed runs leave bubbles- # in place as breadcrumbs.+ # Delete tool-progress / "⏳ Working" bubbles after a SUCCESSFUL final response on+ # platforms that support deletion (Telegram); failed runs keep them as breadcrumbs."cleanup_progress": False,- # Live working-state text on platforms whose typing indicator renders text- # (Slack assistant status): "full"/true = verb + argument preview,- # "verb" = verb only (keeps paths/commands out of shared channels),- # "off"/false = static text. Independent of tool_progress and free: the- # existing typing refresh cadence just renders different text.+ # Working-state text on text-rendering indicators (Slack assistant status):+ # "full"/true = verb + argument preview, "verb" = verb only (keeps paths out of+ # shared channels), "off"/false = static text."live_status": "full",}-# Per-platform defaults tiered by capability:-# HIGH — message editing, personal/team use-# MEDIUM — editing, but often workspace/customer-facing-# LOW — no edit support: each progress message is permanent-# MINIMAL — batch / non-interactive delivery+# Tiers: HIGH = editing, personal/team use; MEDIUM = editing but customer-facing;+# LOW = no edit support (progress messages are permanent); MINIMAL = batch delivery._TIER_HIGH = {"tool_progress": "all","show_reasoning": False,@@ -79,8 +58,7 @@ _TIER_LOW = {_TIER_MINIMAL = {**_TIER_LOW, "tool_preview_length": 0}_PLATFORM_DEFAULTS: dict[str, dict[str, Any]] = {- # Telegram is usually a mobile inbox: quiet tool_progress and no busy-ack- # iteration counter, but DO surface interim assistant commentary and+ # Mobile inbox: quiet tool_progress / busy-ack, but keep interim commentary and# heartbeats so it doesn't look like "typing..." for 30 minutes."telegram": {**_TIER_HIGH, "tool_progress": "off", "busy_ack_detail": False},# Discord's "-# " subtext reads as metadata, so reasoning defaults to it.@@ -96,25 +74,18 @@ _PLATFORM_DEFAULTS: dict[str, dict[str, Any]] = {"mattermost": _TIER_MEDIUM,"matrix": _TIER_MEDIUM,"feishu": _TIER_MEDIUM,- # Buzz (Nostr via buzz-cli) can edit in place but channels are shared- # community spaces; without an entry it inherited the verbose globals.+ # Buzz (Nostr) can edit in place but channels are shared community spaces."buzz": _TIER_MEDIUM,"signal": _TIER_LOW,"whatsapp": _TIER_MEDIUM, # Baileys bridge supports /edit- # Cloud API supports editing but our adapter lacks edit_message; promote- # to MEDIUM once it lands.- "whatsapp_cloud": _TIER_LOW,- # Photon and BlueBubbles are permanent-message iMessage inboxes (no edit);- # without an entry Photon inherited the noisy "all" globals and narrated- # on nearly every turn.+ "whatsapp_cloud": _TIER_LOW, # adapter lacks edit_message; promote once it lands+ # Permanent-message iMessage inboxes (no edit)."photon": _TIER_LOW,"bluebubbles": _TIER_LOW,"weixin": _TIER_LOW,- # WeCom is non-editable but has a native streaming transport (msgtype- # "stream") the consumer routes mid-stream content through; streaming on- # gives the client a typing animation + cumulative updates instead of a- # single one-shot markdown drop.+ # Non-editable, but its native "stream" msgtype gives a typing animation ++ # cumulative updates instead of a one-shot markdown drop."wecom": {**_TIER_LOW, "streaming": True},"wecom_callback": _TIER_LOW,"dingtalk": _TIER_LOW,@@ -155,8 +126,7 @@ def resolve_display_setting(if isinstance(legacy, dict) and legacy.get(platform_key) is not None:return _normalise(setting, legacy[platform_key])- # 2. Global user setting. display.streaming controls only CLI terminal- # streaming; gateway streaming follows the top-level config + platform overrides.+ # 2. Global user setting (display.streaming is CLI-only, see module docstring).if setting != "streaming" and display_cfg.get(setting) is not None:return _normalise(setting, display_cfg[setting])@@ -167,9 +137,7 @@ def resolve_display_setting(return fallback if val is None else val-# ----------------------------------------------------------------------------# Normalisation of YAML quirks (bare ``off`` → False in YAML 1.1, etc.)-# ---------------------------------------------------------------------------+# --- Normalisation of YAML quirks (bare ``off`` → False in YAML 1.1, etc.) ---_TRUTHY = {"true", "1", "yes", "on"}_FALSY = {"false", "0", "no"}diff --git a/gateway/platform_registry.py b/gateway/platform_registry.pyindex 80a513e282a..7614ecad41b 100644--- a/gateway/platform_registry.py+++ b/gateway/platform_registry.py@@ -1,25 +1,11 @@-"""-Platform Adapter Registry+"""Platform adapter registry.Platform adapters (built-in and plugin) self-register here so the gateway can-discover and instantiate them without hardcoded if/elif chains. Plugins+discover and instantiate them without hardcoded if/elif chains. Pluginsregister via ``PluginContext.register_platform()``; ``GatewayRunner._create_adapter()`` consults the registry first and falls back to the legacy-built-in path.--Usage (plugin side)::-- platform_registry.register(PlatformEntry(- name="irc", label="IRC",- adapter_factory=lambda cfg: IRCAdapter(cfg),- check_fn=check_requirements,- validate_config=lambda cfg: bool(cfg.extra.get("server")),- required_env=["IRC_SERVER"], install_hint="pip install irc",- ))--Usage (gateway side)::-- adapter = platform_registry.create_adapter("irc", platform_config)+built-in path. Plugin side: ``platform_registry.register(PlatformEntry(...))``;+gateway side: ``platform_registry.create_adapter("irc", platform_config)``."""import logging@@ -60,113 +46,81 @@ def _caller_plugin_scope() -> Optional[str]:class PlatformEntry:"""Metadata and factory for a single platform adapter."""- # Identifier used in config.yaml (e.g. "irc") and human-readable label.- name: str- label: str-- # Receives a PlatformConfig, returns an adapter instance. A factory (not a- # bare class) lets plugins do custom init / wrapping.+ name: str # config.yaml identifier (e.g. "irc")+ label: str # human-readable+ # Receives a PlatformConfig, returns an adapter instance (a factory, not a+ # bare class, so plugins can do custom init / wrapping).adapter_factory: Callable[[Any], Any]-- # PASSIVE dependency probe: True when deps are importable RIGHT NOW. Must- # be side-effect free -- it runs from status displays (`hermes setup`,- # `hermes status`, dashboard readiness) and the config enablement pass,- # none of which may pip-install. Install logic belongs in ensure_deps_fn.+ # PASSIVE dependency probe: True when deps are importable RIGHT NOW. Must be+ # side-effect free -- it runs from status displays and the config enablement+ # pass, none of which may pip-install. Install logic belongs in ensure_deps_fn.check_fn: Callable[[], bool]-- # Optional config check. None = skip and let connect() fail descriptively.+ # Optional config check. None = skip and let connect() fail descriptively.validate_config: Optional[Callable[[Any], bool]] = None-- # ACTIVE dependency installer: make deps importable (pip / lazy_deps),- # returning True on success. Called by ``create_adapter()`` only when- # ``check_fn`` is False -- the one moment the user has the platform- # enabled+configured and the gateway is about to connect it. None = a- # False ``check_fn`` is a hard block (correct for platforms without- # optional deps). The passive/active split exists because a single field- # either pip-installed from every status display or never installed at all.+ # ACTIVE dependency installer, returning True on success. Called by+ # ``create_adapter()`` only when ``check_fn`` is False -- the one moment the+ # platform is enabled+configured and about to connect. None = a False+ # ``check_fn`` is a hard block. The passive/active split exists because a+ # single field either pip-installed from every status display or never at all.ensure_deps_fn: Optional[Callable[[], bool]] = None-- # Is the platform connected/enabled for this PlatformConfig? Used by- # ``GatewayConfig.get_connected_platforms()`` and setup UI status; None- # falls back to ``validate_config`` or ``check_fn``.+ # Is the platform connected/enabled for this PlatformConfig? Used by+ # ``GatewayConfig.get_connected_platforms()`` and setup UI status; None falls+ # back to ``validate_config`` or ``check_fn``.is_connected: Optional[Callable[[Any], bool]] = None-- # Env vars this platform needs (``hermes setup`` display) and the hint- # shown when check_fn returns False.+ # Env vars this platform needs (``hermes setup`` display) and the hint shown+ # when check_fn returns False.required_env: list = field(default_factory=list)install_hint: str = ""-- # Interactive setup ``() -> None``. None falls back to- # _setup_standard_platform (needs token_var + vars) or a generic env display.+ # Interactive setup ``() -> None``. None falls back to _setup_standard_platform+ # (needs token_var + vars) or a generic env display.setup_fn: Optional[Callable[[], None]] = None-# "builtin" or "plugin"; plugin_name is the owning manifest (empty for# built-ins) so ``hermes gateway setup`` can auto-enable the plugin.source: str = "plugin"plugin_name: str = ""-# Auth env var names for _is_user_authorized: comma-separated allowed user# IDs, and a truthy "allow everyone" switch.allowed_users_env: str = ""allow_all_env: str = ""-- # Max message length for smart-chunking; 0 = no limit.- max_message_length: int = 0-- # If True, session descriptions redact PII (phone numbers, etc.).- pii_safe: bool = False-- # Emoji for CLI/gateway display.- emoji: str = "🔌"-- # Whether /update may be issued from this platform (_UPDATE_ALLOWED_PLATFORMS).- allow_update_command: bool = True-- # Platform hint injected into the system prompt; empty = none.- platform_hint: str = ""-- # Env-driven auto-configuration ``() -> Optional[dict]``: returns- # ``PlatformConfig.extra`` fields to seed when the platform is auto-enabled.- # Runs during ``_apply_env_overrides`` BEFORE the adapter is constructed so- # ``gateway status`` reflects env-only config. None/empty dict = skip.+ max_message_length: int = 0 # smart-chunking cap; 0 = no limit+ pii_safe: bool = False # session descriptions redact PII (phone numbers, etc.)+ emoji: str = "🔌" # CLI/gateway display+ allow_update_command: bool = True # /update may be issued from this platform+ platform_hint: str = "" # injected into the system prompt; empty = none+ # Env-driven auto-configuration ``() -> Optional[dict]``: ``PlatformConfig.extra``+ # fields to seed when the platform is auto-enabled. Runs during+ # ``_apply_env_overrides`` BEFORE the adapter is constructed so ``gateway status``+ # reflects env-only config. None/empty dict = skip.env_enablement_fn: Optional[Callable[[], Optional[dict]]] = None-- # YAML->env bridge ``(yaml_cfg, platform_cfg) -> Optional[dict]``: lets a- # plugin own its config.yaml translation instead of core gateway/config.py.- # Called from ``load_gateway_config()`` after the generic shared-key loop and- # before ``_apply_env_overrides``. May mutate ``os.environ`` (guard with- # ``not os.getenv(...)`` to keep env > YAML precedence); the returned dict is- # merged into ``PlatformConfig.extra``. Exceptions are logged at debug.- # Full contract: website/docs/developer-guide/adding-platform-adapters.md.+ # YAML->env bridge ``(yaml_cfg, platform_cfg) -> Optional[dict]``: a plugin owns+ # its config.yaml translation. Called from ``load_gateway_config()`` after the+ # generic shared-key loop and before ``_apply_env_overrides``. May mutate+ # ``os.environ`` (guard with ``not os.getenv(...)`` to keep env > YAML); the+ # returned dict is merged into ``PlatformConfig.extra``. Exceptions logged at+ # debug. Full contract: website/docs/developer-guide/adding-platform-adapters.md.apply_yaml_config_fn: Optional[Callable[[dict, dict], Optional[dict]]] = None-- # Home-channel env var (e.g. "IRC_HOME_CHANNEL"). When set, cron.scheduler- # accepts ``deliver=<name>`` and reads it for the default chat/room ID.+ # Home-channel env var (e.g. "IRC_HOME_CHANNEL"): cron.scheduler accepts+ # ``deliver=<name>`` and reads it for the default chat/room ID.cron_deliver_env_var: str = ""-# Target parsing ``(target_ref) -> Optional[(chat_id, thread_id)]``, run by# ``tools/send_message_tool._parse_target_ref`` before channel-directory- # fallback so plugins can declare native target syntax- # (e.g. ``fmsg:@[email protected]``). None result = continue to directory- # resolution; no opaque fallback is applied.+ # fallback so plugins can declare native target syntax (``fmsg:@alice@x``).+ # None result = continue to directory resolution; no opaque fallback.parse_target_ref_fn: Optional[Callable[[str], Optional[tuple[str, Optional[str]]]]] = None-- # Validation after parsing/normalization or directory resolution: True to- # accept, False to reject, or a non-empty string to reject with diagnostic.+ # Validation after parsing or directory resolution: True to accept, False to+ # reject, or a non-empty string to reject with diagnostic.validate_target_ref_fn: Optional[Callable[[str], bool | str]] = None-# Whole-request delivery handler ``(args, normalized_chat_id, platform_name,- # pconfig)``, sync or async. Prefer standalone_sender_fn when the standard+ # pconfig)``, sync or async. Prefer standalone_sender_fn when the standard# send contract suffices.send_message_handler: Optional[Callable[[dict, str, str, Any], Any]] = None-- # Out-of-process sender used by ``_send_via_adapter`` when cron runs apart- # from the gateway and the in-process adapter weakref is None::+ # Out-of-process sender used by ``_send_via_adapter`` when cron runs apart from+ # the gateway and the in-process adapter weakref is None::# async (pconfig, chat_id, message, *, thread_id=None,# media_files=None, force_document=False) -> dict- # Returns ``{"success": True, "message_id": ...}`` or ``{"error": str}``.- # Without it, plugin platforms cannot be cron ``deliver=`` targets when the- # gateway is not co-resident.+ # Returns ``{"success": True, "message_id": ...}`` or ``{"error": str}``. Without+ # it, plugin platforms cannot be cron ``deliver=`` targets when the gateway is+ # not co-resident.standalone_sender_fn: Optional[Callable[..., Awaitable[dict]]] = None@@ -185,7 +139,7 @@ class PlatformRegistry:# process-global entries for lookups in that profile's runtime scope.self._scoped_entries: dict[str, dict[str, PlatformEntry]] = {}# Deferred loaders: name -> zero-arg callable that imports the owning- # plugin module (which calls register()). Adapter modules import heavy+ # plugin module (which calls register()). Adapter modules import heavy# SDKs at module level; eagerly loading ~20 bundled platforms added# seconds to every `hermes` invocation, so the real import happens only# when a lookup actually asks for that platform.@@ -220,28 +174,24 @@ class PlatformRegistry:entry = entries.get(name)loader = deferred.get(name)if entry is None and loader is None:- loader = self._inflight_loaders.get((scope, name))- if entry is None and loader is None:- loader = self._consumed_loaders.get((scope, name))+ loader = self._inflight_loaders.get((scope, name)) or self._consumed_loaders.get((scope, name))return entry, loaderdef _prune_scope(self, scope: Optional[str]) -> None:if scope is None:return- if not self._scoped_entries.get(scope):- self._scoped_entries.pop(scope, None)- if not self._scoped_deferred.get(scope):- self._scoped_deferred.pop(scope, None)+ for maps in (self._scoped_entries, self._scoped_deferred):+ if not maps.get(scope):+ maps.pop(scope, None)# -- deferred loading ----------------------------------------------------def register_deferred(self, name: str, loader: _Loader, *, scope: Optional[str] = None) -> None:"""Register a lazy loader for a platform that hasn't been imported yet.- *loader* imports the owning plugin module, which must call- :meth:`register` for *name*. It runs at most once, on first lookup- (or full materialization). A concrete registration takes precedence- and drops the loader.+ *loader* imports the owning plugin module, which must call :meth:`register`+ for *name*. It runs at most once, on first lookup (or full materialization).+ A concrete registration takes precedence and drops the loader."""with self._lock:entries, deferred = self._scope_maps(scope, create=True)@@ -271,7 +221,7 @@ class PlatformRegistry:"""Restore a registration if its full state is still *current* (CAS).Identity checks protect a later registration from removal while letting- an unloaded override reveal what it displaced. Deferred loaders are+ an unloaded override reveal what it displaced. Deferred loaders arepart of the state because bundled platform plugins load lazily."""with self._lock:@@ -355,7 +305,7 @@ class PlatformRegistry:self._resolve(name, active_scope)def is_deferred_load_cancelled(self, name: str, *, scope: Optional[str] = None) -> bool:- """Return whether ownership teardown cancelled an in-flight loader."""+ """Whether ownership teardown cancelled an in-flight loader."""with self._lock:return (scope, name) in self._cancelled_inflight@@ -364,7 +314,7 @@ class PlatformRegistry:Only the iterate-all accessors (``all_entries``/``plugin_entries``) callthis, from paths that genuinely need every adapter (gateway startup,- ``hermes setup``/``gateway status``, channel directory). CLI chat never+ ``hermes setup``/``gateway status``, channel directory). CLI chat neveriterates the full set."""active_scope = self.current_scope_key()@@ -386,11 +336,11 @@ class PlatformRegistry:"""Register a platform adapter entry (last writer wins on name clash)."""with self._lock:if scope is None and entry.source == "plugin":- scope = _caller_plugin_scope()- if scope is None:- scope = _plugin_scope_from_callable(entry.adapter_factory)- if scope is None:- scope = _plugin_scope_from_callable(entry.check_fn)+ scope = (+ _caller_plugin_scope()+ or _plugin_scope_from_callable(entry.adapter_factory)+ or _plugin_scope_from_callable(entry.check_fn)+ )# A concrete registration supersedes any pending deferred loader.entries, deferred = self._scope_maps(scope, create=True)self._consumed_loaders.pop((scope, entry.name), None)@@ -404,7 +354,7 @@ class PlatformRegistry:logger.debug("Registered platform adapter: %s (%s)", entry.name, entry.source)def unregister(self, name: str, *, scope: Optional[str] = None) -> bool:- """Remove a platform entry. Returns True if it existed."""+ """Remove a platform entry. Returns True if it existed."""with self._lock:inferred_scope = scope if scope is not None else _caller_plugin_scope()active_scope = inferred_scope or self.current_scope_key()@@ -455,7 +405,7 @@ class PlatformRegistry:"""Concrete and deferred platform names without loading adapters.Same scope semantics as ``is_registered()``: current profile scope AND- process-global names. Plugin platforms register deferred loaders under+ process-global names. Plugin platforms register deferred loaders undera profile scope, so the global maps alone would miss every plugin."""with self._lock:diff --git a/gateway/profile_routing.py b/gateway/profile_routing.pyindex 9b533b5274f..b5d248af64f 100644--- a/gateway/profile_routing.py+++ b/gateway/profile_routing.py@@ -1,35 +1,9 @@-"""Profile-based routing for the gateway with hierarchical matching.--Lets a single Hermes instance route specific Discord guilds/channels/threads-to different profiles — each with their own model, tools, memory, and persona.--Matching priority (most specific first):- 1. platform + chat_id + thread_id (exact thread) — specificity 14- 2. platform + chat_id (channel route) — specificity 6- 3. platform + guild_id (guild/server route) — specificity 2- 4. No match → default profile--Parent-chain matching: for Discord threads and forum posts, ``parent_chat_id``-carries the direct parent, so a route keyed on a channel also matches messages-in any thread/post under it.--Configuration (config.yaml)::-- gateway:- profile_routes:- - name: server-default- platform: discord- guild_id: "YOUR_GUILD_ID"- profile: server-profile- - name: thread-route- platform: discord- chat_id: "YOUR_CHANNEL_ID"- thread_id: "YOUR_THREAD_ID"- profile: thread-profile- - name: owner-whatsapp- platform: whatsapp- chat_id: "15551234567" # phone, JID, or LID — all equivalent- profile: owner+"""Profile-based routing: route guilds/channels/threads to different profiles.++Matching priority, most specific first (``gateway.profile_routes`` in config.yaml):+platform + chat_id + thread_id (14) → platform + chat_id (6) → platform + guild_id (2)+→ default profile. For Discord threads/forum posts ``parent_chat_id`` carries the+direct parent, so a channel route also matches any thread/post under it."""from __future__ import annotations@@ -41,8 +15,7 @@ import logginglogger = logging.getLogger(__name__)-# Baileys and Cloud share phone/JID/LID identity rules. Other platforms keep-# exact string compare so Telegram numeric ids and Discord snowflakes stay unchanged.+# Baileys and Cloud share phone/JID/LID identity rules; other platforms compare exactly._WHATSAPP_IDENTITY_PLATFORMS = {"whatsapp", "whatsapp_cloud"}_WHATSAPP_NON_USER_SUFFIXES = ("@g.us", "@broadcast", "@newsletter")@@ -59,15 +32,14 @@ def _whatsapp_user_chat_ids_match(platform: str, left: Optional[str], right: Opt"""True when two WhatsApp *user* chat_ids refer to the same person.Uses ``expand_whatsapp_aliases`` (same helper as session keys and adapter- allowlists) so a bare number, ``@s.whatsapp.net`` JID and ``@lid`` LID- collapse to one identity. Group/broadcast JIDs are chats, not senders,- and non-WhatsApp platforms always return False (exact match only).+ allowlists) so a bare number, JID and LID collapse to one identity.+ Group/broadcast JIDs are chats, not senders; non-WhatsApp platforms → False."""- if (platform or "").strip().lower() not in _WHATSAPP_IDENTITY_PLATFORMS:- return False- if not left or not right:- return False- if _is_whatsapp_non_user_chat(left) or _is_whatsapp_non_user_chat(right):+ if (+ (platform or "").strip().lower() not in _WHATSAPP_IDENTITY_PLATFORMS+ or not left or not right+ or _is_whatsapp_non_user_chat(left) or _is_whatsapp_non_user_chat(right)+ ):return Falsefrom gateway.whatsapp_identity import expand_whatsapp_aliases@@ -104,13 +76,11 @@ class ProfileRoute:thread_id: Optional[str] = None,parent_chat_id: Optional[str] = None,) -> bool:- """Return True if every discriminator the route declares holds (AND).+ """True if every discriminator the route declares holds (AND).- ``chat_id`` matches the channel directly or as the parent of a- thread/forum post; a route with both ``guild_id`` and ``chat_id``- requires both. WhatsApp ``chat_id`` also matches across user-identity- forms (number/JID/LID) after the exact check; groups/broadcasts stay- exact-only.+ ``chat_id`` matches the channel directly or as the parent of a thread/forum+ post; WhatsApp ``chat_id`` also matches across number/JID/LID after the+ exact check (groups/broadcasts stay exact-only)."""if not self.enabled or self.platform != platform:return False@@ -129,11 +99,9 @@ class ProfileRoute:def _coerce_route_id(value: Any) -> Optional[str]:"""Normalize a route discriminator to str for strict equality matching.- PyYAML loads unquoted numeric IDs as ``int`` while inbound ``SessionSource``- fields are always ``str``, so ints must be coerced or ``matches()`` fails- silently. Only ``int`` (not ``bool``) is coerced; floats and other types- stringify to something (``"123.0"``) that can never match, so they pass- through with a load-time warning instead of being silently "fixed".+ PyYAML loads unquoted numeric IDs as ``int`` while ``SessionSource`` fields are+ ``str``. Only ``int`` (not ``bool``) is coerced; floats stringify to something+ (``"123.0"``) that can never match, so they get a load-time warning instead."""if value is None or isinstance(value, str):return value@@ -161,8 +129,7 @@ def parse_profile_routes(raw: Optional[List[Dict[str, Any]]]) -> List[ProfileRouif not platform or not profile:logger.warning("Skipping profile route %s: missing platform or profile", name)continue- # Validate profile name to prevent path traversal. Lazy import avoids a- # circular dependency at module load time.+ # Validate profile name to prevent path traversal (lazy import: cycle).try:from hermes_cli.profiles import normalize_profile_name, validate_profile_name