The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): plugin platforms declare their env->config rows on PlatformEntry
Teknium3c3f85a0d06d
diff --git a/gateway/config_env.py b/gateway/config_env.pyindex 3c2280dbe17..bf270762989 100644--- a/gateway/config_env.py+++ b/gateway/config_env.py@@ -2,17 +2,14 @@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``" — declared as ``_Cred`` rows in ``_ENV_STEPS`` (source-order = application order). Platforms with unique gating are small functions in the same table.+copy the values into ``extra``" — declared by each platform plugin as ``PlatformEntry.env_overrides``+(``gateway.platform_env.EnvCred`` rows; see that module). Core-only platforms (api_server, webhook,+msgraph_webhook, relay) keep their small functions here."""-import contextlib-import jsonimport loggingimport os-from dataclasses import dataclass-from functools import partial-from typing import Any, Callable, Dict, Optional+from typing import Optionalfrom gateway.config import (GatewayConfig,@@ -23,6 +20,7 @@ from gateway.config import (_has_usable_api_server_key,SHARED_LISTENER_MIRROR_PLATFORMS,)+from gateway.platform_env import INT, csv_extras, env_extrasfrom utils import is_truthy_value# Logger name parity with the origin module: records stay under "gateway.config".@@ -34,37 +32,30 @@ getenv = _getenv_str# 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.+# Env var(s) whose presence drives a CORE platform's env-enable branch, named in the explicit-disable+# WARNING. Plugin platforms declare theirs as ``PlatformEntry.env_enable_credentials``._ENV_ENABLE_CREDENTIALS: dict = {- Platform.TELEGRAM: ("TELEGRAM_BOT_TOKEN",),- Platform.DISCORD: ("DISCORD_BOT_TOKEN",),- Platform.SLACK: ("SLACK_BOT_TOKEN",),- Platform.WHATSAPP: ("WHATSAPP_ENABLED",),- Platform.WHATSAPP_CLOUD: ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"),- Platform.SIGNAL: ("SIGNAL_HTTP_URL",),- Platform.MATTERMOST: ("MATTERMOST_TOKEN",),- Platform.MATRIX: ("MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD"),- Platform.EMAIL: ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"),- Platform.SMS: ("TWILIO_ACCOUNT_SID",),- Platform.DINGTALK: ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),- Platform.FEISHU: ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),- Platform.WECOM: ("WECOM_BOT_ID", "WECOM_SECRET"),- Platform.WECOM_CALLBACK: ("WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"),- Platform.WEIXIN: ("WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"),- Platform.BLUEBUBBLES: ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),- Platform.QQBOT: ("QQ_APP_ID", "QQ_CLIENT_SECRET"),- Platform.YUANBAO: ("YUANBAO_APP_ID", "YUANBAO_APP_SECRET"),Platform.RELAY: ("GATEWAY_RELAY_URL",),}+def _enable_credential_names(platform: Platform) -> tuple:+ """WARNING credential names: the core row, else the platform entry's declaration. The entry is+ already materialized (its own env step is what is warning), so the lookup never imports."""+ if platform in _ENV_ENABLE_CREDENTIALS:+ return _ENV_ENABLE_CREDENTIALS[platform]+ from gateway.platform_registry import platform_registry+ entry = platform_registry.get(platform.value)+ return tuple(getattr(entry, "env_enable_credentials", ()) or ())++def _warn_explicit_disable_beats_env(platform: Platform) -> None:"""One-time WARNING: ``platforms.<x>.enabled: false`` wins over env creds (whichused to force-enable), so users relying on "creds in .env = on" learn why it went dark."""if platform in _EXPLICIT_DISABLE_WARNED:return_EXPLICIT_DISABLE_WARNED.add(platform)- names = _ENV_ENABLE_CREDENTIALS.get(platform) or ()+ names = _enable_credential_names(platform)present = [n for n in names if (os.environ.get(n) or "").strip()]creds = ", ".join(present or names) or "its credentials"logger.warning(@@ -77,98 +68,6 @@ def _warn_explicit_disable_beats_env(platform: Platform) -> None:)-# --- small value parsers -------------------------------------------------------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."""- def parse(raw: str) -> int:- try:- return int(str(raw).strip(), 10)- except (TypeError, ValueError):- return default- return parse---def _strip_slash(value: str) -> str:- return value.rstrip("/")---def _strip_lower(value: str) -> str:- return value.strip().lower()---def _truthy_token(value: str) -> bool:- return value.lower() in {"true", "1", "yes", "on"}---def _csv_extras(extra: dict[str, Any], spec) -> None:- """``extra[key] = _csv_list(raw)`` for each ``(key, raw)`` whose list is non-empty."""- for key, raw in spec:- items = _csv_list(raw)- if items:- extra[key] = items---def _mention_patterns(value: str) -> Any:- try:- return json.loads(value)- except Exception:- return _csv_list(value.replace("\n", ","))---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)- return next((v for v in map(getenv, envs) if v), "")---# --- reusable steps -------------------------------------------------------------_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.-- ``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)- if strip:- value = value.strip()- if not value:- continue- if fn and fn[0] is _INT:- with contextlib.suppress(ValueError):- extra[key] = int(value)- else:- extra[key] = fn[0](value) if fn else value---def _env_home_channel(config: GatewayConfig, platform: Platform, env_base: str, *, strip: bool = False) -> None:- """Set ``home_channel`` from ``<env_base>`` (+``_NAME``/``_THREAD_ID``) when the platform is configured."""- chat_id = getenv(env_base)- if strip:- chat_id = chat_id.strip()- if chat_id and platform in config.platforms:- config.platforms[platform].home_channel = HomeChannel(- platform=platform, chat_id=chat_id,- name=getenv(f"{env_base}_NAME", "Home"), thread_id=getenv(f"{env_base}_THREAD_ID") or None,- )---def _env_reply_mode(config: GatewayConfig, platform: Platform, env: str) -> None:- mode = getenv(env).lower()- if mode in {"off", "first", "all"}:- config.platforms.setdefault(platform, PlatformConfig()).reply_to_mode = mode--def _loading_secondary_under_multiplexer() -> bool:"""True while a multiplexer loads a NON-default profile's config (``_profile_runtime_scope`` sets thehome override; the runner sets the multiplex flag). Same signal ``gateway.config`` uses for scoped reads."""@@ -206,103 +105,6 @@ def _enable_from_env(return platform_config-@dataclass(frozen=True)-class _Cred:- """Credential-gated platform enable, applied as ``step(config)``.-- ``creds``: env names that must ALL be truthy (inner tuple = ANY of). ``token``: env stored as- ``PlatformConfig.token`` even when yaml disables the adapter (sending skills use it). ``fixed``:- ``(extra_key, env[, default[, fn]])`` always written once enabled. ``optional*``: ``_env_extras``- specs. ``warn_missing``: ``(env, msg)`` logged BEFORE enabling when blank. ``then``: tail- ``fn(config, platform_config)``. ``home``: ``_env_home_channel`` env base applied only when the gate passed.- """- platform: Platform- creds: tuple- token: Optional[str] = None- fixed: tuple = ()- optional: tuple = ()- optional_stripped: tuple = ()- warn_missing: Optional[tuple] = None- then: Optional[Callable[[GatewayConfig, PlatformConfig], None]] = None- home: Optional[str] = None- home_strip: bool = False-- def __call__(self, config: GatewayConfig) -> None:- if not all(_env_first(group) for group in self.creds):- return- if self.warn_missing and not getenv(self.warn_missing[0]):- logger.warning(self.warn_missing[1])- platform_config = _enable_from_env(config, self.platform)- if self.token and (token := getenv(self.token)):- platform_config.token = token- extra = platform_config.extra- for key, env, *rest in self.fixed:- default = rest[0] if rest else ""- value = _env_first(env) or default if isinstance(env, tuple) else getenv(env, default)- extra[key] = rest[1](value) if len(rest) > 1 else value- _env_extras(extra, self.optional)- _env_extras(extra, self.optional_stripped, strip=True)- if self.then is not None:- self.then(config, platform_config)- if self.home:- _env_home_channel(config, self.platform, self.home, strip=self.home_strip)---def _Home(platform: Platform, env_base: str, *, strip: bool = False):- return partial(_env_home_channel, platform=platform, env_base=env_base, strip=strip)---def _ReplyMode(platform: Platform, env: str):- return partial(_env_reply_mode, platform=platform, env=env)---# --- platform-unique branches --------------------------------------------------def _telegram_fallback_ips(config: GatewayConfig) -> None:- if ips := getenv("TELEGRAM_FALLBACK_IPS"):- config.platforms.setdefault(Platform.TELEGRAM, PlatformConfig()).extra["fallback_ips"] = _csv_list(ips)---def _whatsapp(config: GatewayConfig) -> None:- """WhatsApp (Baileys bridge) uses a flag, not credentials. WHATSAPP_ENABLED=false overrides YAML;- WHATSAPP_ENABLED=true follows the credential contract — it never beats an explicit YAML disable- (the dashboard's disable action writes only ``platforms.whatsapp.enabled: false`` and leaves the- env flag on disk, #73289)."""- raw = getenv("WHATSAPP_ENABLED")- wa_cfg = config.platforms.get(Platform.WHATSAPP)- if wa_cfg is not None and raw.lower() in {"false", "0", "no"}:- wa_cfg.enabled = False- elif is_truthy_value(raw):- _enable_from_env(config, Platform.WHATSAPP)---def _slack_home(config: GatewayConfig) -> None:- """SLACK_HOME_CHANNEL creates a disabled Slack entry if needed; user_id/scope_id provenance survives an unchanged chat_id."""- if not (slack_home := getenv("SLACK_HOME_CHANNEL")):- 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:- mode = getenv("MATRIX_E2EE_MODE").strip().lower()- matrix_config.extra["encryption"] = mode in ("required", "require", "optional", "prefer", "preferred") or is_truthy_value(getenv("MATRIX_ENCRYPTION"))- if mode:- matrix_config.extra["e2ee_mode"] = mode- _env_extras(matrix_config.extra, (("device_id", "MATRIX_DEVICE_ID"),))---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: an unauthenticated adapter refuses to start and the reconnect watcher would spin."""key = getenv("API_SERVER_KEY")@@ -310,8 +112,8 @@ def _api_server(config: GatewayConfig) -> None:returnextra = _enable_from_env(config, Platform.API_SERVER, pop_marker=True, warn=False).extraextra["key"] = key- _csv_extras(extra, (("cors_origins", getenv("API_SERVER_CORS_ORIGINS")),))- _env_extras(extra, (("port", "API_SERVER_PORT", _INT), ("host", "API_SERVER_HOST"), ("model_name", "API_SERVER_MODEL_NAME")))+ csv_extras(extra, (("cors_origins", getenv("API_SERVER_CORS_ORIGINS")),))+ env_extras(extra, (("port", "API_SERVER_PORT", INT), ("host", "API_SERVER_HOST"), ("model_name", "API_SERVER_MODEL_NAME")))def _webhook(config: GatewayConfig) -> None:@@ -323,7 +125,7 @@ def _webhook(config: GatewayConfig) -> None:if enabledelse config.platforms[Platform.WEBHOOK])- _env_extras(webhook_config.extra, (("port", "WEBHOOK_PORT", _INT), ("secret", "WEBHOOK_SECRET")))+ env_extras(webhook_config.extra, (("port", "WEBHOOK_PORT", INT), ("secret", "WEBHOOK_SECRET")))def _msgraph_webhook(config: GatewayConfig) -> None:@@ -337,28 +139,10 @@ def _msgraph_webhook(config: GatewayConfig) -> None:msgraph_cfg = config.platforms.setdefault(Platform.MSGRAPH_WEBHOOK, PlatformConfig())if enabled: # same guard as webhook, but READ (don't pop) the marker: the relay pass still consults it_enable_from_env(config, Platform.MSGRAPH_WEBHOOK, warn=False)- _env_extras(msgraph_cfg.extra, (("port", "MSGRAPH_WEBHOOK_PORT", _INT),))+ env_extras(msgraph_cfg.extra, (("port", "MSGRAPH_WEBHOOK_PORT", INT),))if client_state:msgraph_cfg.extra["client_state"] = client_state- _csv_extras(msgraph_cfg.extra, (("accepted_resources", resources), ("allowed_source_cidrs", allowed_cidrs)))---def _qq_home(config: GatewayConfig, qq_config: PlatformConfig) -> None:- qq_home = getenv("QQBOT_HOME_CHANNEL").strip()- name_env = "QQBOT_HOME_CHANNEL_NAME"- if not qq_home and (qq_home := getenv("QQ_HOME_CHANNEL").strip()):- # Back-compat: accept the pre-rename name and warn.- name_env = "QQ_HOME_CHANNEL_NAME"- logger.warning(- "QQ_HOME_CHANNEL is deprecated; rename to QQBOT_HOME_CHANNEL "- "in your .env for consistency with the platform key."- )- if qq_home:- qq_config.home_channel = HomeChannel(- platform=Platform.QQBOT, chat_id=qq_home,- name=getenv("QQBOT_HOME_CHANNEL_NAME") or getenv(name_env, "Home"),- thread_id=getenv("QQBOT_HOME_CHANNEL_THREAD_ID") or getenv("QQ_HOME_CHANNEL_THREAD_ID") or None,- )+ csv_extras(msgraph_cfg.extra, (("accepted_resources", resources), ("allowed_source_cidrs", allowed_cidrs)))def _plugin_probe_seed(entry) -> Optional[dict]:@@ -437,26 +221,56 @@ def _enable_plugin_platform(config: GatewayConfig, entry) -> None:)-def _enable_plugin_platforms_from_env(config: GatewayConfig) -> None:- """Registry-driven enable for plugin platforms (built-ins have rows in ``_ENV_STEPS``).-- Enabled when credentials are configured (``is_connected`` MUST gate: ``check_fn`` alone would- enable unconfigured platforms that retry-connect forever) and deps are present (``check_fn``) or- installable later by ``create_adapter()`` — never here: installing in this sweep boot-looped the app.- """+def _configured_plugin_entries(config: GatewayConfig) -> list:+ """Plugin entries with activation evidence (config block, env/.env, credential pool); only those+ are imported — an unconfigured adapter has nothing to enable. See gateway.platform_activation.+ config.yaml blocks already materialized their adapters in load_yaml_layer (and every merged+ block is in config.platforms), so the YAML is not parsed a second time here."""try:from hermes_cli.plugins import discover_pluginsdiscover_plugins() # idempotentfrom gateway.platform_registry import platform_registryfrom gateway.platform_activation import configured_plugin_entries- # Only platforms with activation evidence (config block, env/.env, credential pool) are- # imported; an unconfigured adapter has nothing to enable. See gateway.platform_activation.- # config.yaml blocks already materialized their adapters in load_yaml_layer (and every merged- # block is in config.platforms), so the YAML is not parsed a second time here.- for entry in configured_plugin_entries(platform_registry, yaml_cfg={}, platform_names=config.platforms):+ return configured_plugin_entries(platform_registry, yaml_cfg={}, platform_names=config.platforms)+ except Exception as e: # health: allow BLE001 -- moved from the plugin pass: discovery never breaks config load+ logger.debug("Plugin platform discovery for env overrides failed: %s", e)+ return []+++def _platform_rank(entry) -> int:+ # Static ``Platform`` members first, in enum order (the order the env rows always ran in), so+ # ``config.platforms`` insertion order stays deterministic and independent of registry load order.+ members = list(Platform.__members__.values())+ try:+ return members.index(Platform(entry.name))+ except (ValueError, KeyError):+ return len(members)+++def _apply_plugin_env_overrides(config: GatewayConfig, entries: list) -> None:+ """Run each plugin platform's declared ``env_overrides`` steps (credential enable, home channel,+ reply mode, ...). Every step touches only its own platform, so only the order WITHIN an entry is+ significant (e.g. Telegram's reply mode may create the entry its home channel then attaches to)."""+ for entry in sorted(entries, key=_platform_rank):+ for step in getattr(entry, "env_overrides", ()) or ():+ try:+ step(config)+ except Exception as e: # health: allow BLE001 -- a broken plugin env row must not break config load+ logger.debug("env override for %s raised: %s", entry.name, e)+++def _enable_plugin_platforms_from_env(config: GatewayConfig, entries: list) -> None:+ """Registry-driven enable for plugin platforms whose ``env_overrides`` did not already enable them.++ Enabled when credentials are configured (``is_connected`` MUST gate: ``check_fn`` alone would+ enable unconfigured platforms that retry-connect forever) and deps are present (``check_fn``) or+ installable later by ``create_adapter()`` — never here: installing in this sweep boot-looped the app.+ """+ for entry in entries:+ try:_enable_plugin_platform(config, entry)- except Exception as e:- logger.debug("Plugin platform enable pass failed: %s", e)+ except Exception as e:+ logger.debug("Plugin platform enable pass failed for %s: %s", entry.name, e)def _relay(config: GatewayConfig) -> None:@@ -510,148 +324,19 @@ def _scrub_explicit_markers(config: GatewayConfig) -> None:for platform_config in config.platforms.values():platform_config.extra.pop("_enabled_explicit", None)-# Order is significant: a home channel only attaches to a platform that already exists (Telegram's-# reply mode may create the entry first; Discord reads home first). Relay disabling runs after the-# plugin pass; the marker scrub must be last.-_ENV_STEPS: tuple = (- _Cred(Platform.TELEGRAM, ("TELEGRAM_BOT_TOKEN",), token="TELEGRAM_BOT_TOKEN"),- _ReplyMode(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"),- _telegram_fallback_ips,- _Home(Platform.TELEGRAM, "TELEGRAM_HOME_CHANNEL"),- _Cred(Platform.DISCORD, ("DISCORD_BOT_TOKEN",), token="DISCORD_BOT_TOKEN"),- _Home(Platform.DISCORD, "DISCORD_HOME_CHANNEL"),- _ReplyMode(Platform.DISCORD, "DISCORD_REPLY_TO_MODE"),- _whatsapp,- _Home(Platform.WHATSAPP, "WHATSAPP_HOME_CHANNEL"),- # WhatsApp Cloud API (Meta). Distinct from the Baileys bridge; both may run against different numbers.- _Cred(- Platform.WHATSAPP_CLOUD, ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"),- fixed=(("phone_number_id", "WHATSAPP_CLOUD_PHONE_NUMBER_ID"), ("access_token", "WHATSAPP_CLOUD_ACCESS_TOKEN")),- optional=(- ("app_id", "WHATSAPP_CLOUD_APP_ID"), ("app_secret", "WHATSAPP_CLOUD_APP_SECRET"),- ("waba_id", "WHATSAPP_CLOUD_WABA_ID"), ("verify_token", "WHATSAPP_CLOUD_VERIFY_TOKEN"),- ("webhook_host", "WHATSAPP_CLOUD_WEBHOOK_HOST"), ("webhook_port", "WHATSAPP_CLOUD_WEBHOOK_PORT", _INT),- ("webhook_path", "WHATSAPP_CLOUD_WEBHOOK_PATH"), ("api_version", "WHATSAPP_CLOUD_API_VERSION"),- ),- ),- _Home(Platform.WHATSAPP_CLOUD, "WHATSAPP_CLOUD_HOME_CHANNEL"),- _Cred(Platform.SLACK, ("SLACK_BOT_TOKEN",), token="SLACK_BOT_TOKEN"),- _slack_home,- _Cred(- Platform.SIGNAL, ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"),- fixed=(- ("http_url", "SIGNAL_HTTP_URL"), ("account", "SIGNAL_ACCOUNT"),- ("ignore_stories", "SIGNAL_IGNORE_STORIES", "true", is_truthy_value),- ),- ),- _Home(Platform.SIGNAL, "SIGNAL_HOME_CHANNEL"),- _Cred(- Platform.MATTERMOST, ("MATTERMOST_TOKEN",), token="MATTERMOST_TOKEN",- warn_missing=("MATTERMOST_URL", "MATTERMOST_TOKEN set but MATTERMOST_URL is missing"),- fixed=(("url", "MATTERMOST_URL"),),- ),- _Home(Platform.MATTERMOST, "MATTERMOST_HOME_CHANNEL"),- _Cred(- Platform.MATRIX, (("MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD"),), token="MATRIX_ACCESS_TOKEN",- warn_missing=("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN/MATRIX_PASSWORD set but MATRIX_HOMESERVER is missing"),- fixed=(("homeserver", "MATRIX_HOMESERVER"),),- optional=(("user_id", "MATRIX_USER_ID"), ("password", "MATRIX_PASSWORD")),- then=_matrix_e2ee,- ),- _Home(Platform.MATRIX, "MATRIX_HOME_ROOM"),- _Cred(- Platform.EMAIL, ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"),- fixed=(("address", "EMAIL_ADDRESS"), ("imap_host", "EMAIL_IMAP_HOST"), ("smtp_host", "EMAIL_SMTP_HOST")),- ),- _Home(Platform.EMAIL, "EMAIL_HOME_ADDRESS"),- _Cred(Platform.SMS, ("TWILIO_ACCOUNT_SID",), then=_sms_api_key),- _Home(Platform.SMS, "SMS_HOME_CHANNEL"),- _api_server,- _webhook,- _msgraph_webhook,- _Cred(- Platform.DINGTALK, ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),- fixed=(("client_id", "DINGTALK_CLIENT_ID"), ("client_secret", "DINGTALK_CLIENT_SECRET")),- home="DINGTALK_HOME_CHANNEL",- ),- _Cred(- Platform.FEISHU, ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),- fixed=(- ("app_id", "FEISHU_APP_ID"), ("app_secret", "FEISHU_APP_SECRET"),- ("domain", "FEISHU_DOMAIN", "feishu"), ("connection_mode", "FEISHU_CONNECTION_MODE", "websocket"),- ),- optional=(("encrypt_key", "FEISHU_ENCRYPT_KEY"), ("verification_token", "FEISHU_VERIFICATION_TOKEN")),- home="FEISHU_HOME_CHANNEL",- ),- _Cred(- Platform.WECOM, ("WECOM_BOT_ID", "WECOM_SECRET"),- fixed=(("bot_id", "WECOM_BOT_ID"), ("secret", "WECOM_SECRET")),- optional=(("websocket_url", "WECOM_WEBSOCKET_URL"),),- home="WECOM_HOME_CHANNEL",- ),- _Cred(- Platform.WECOM_CALLBACK, ("WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"),- fixed=(- ("corp_id", "WECOM_CALLBACK_CORP_ID"), ("corp_secret", "WECOM_CALLBACK_CORP_SECRET"),- ("agent_id", "WECOM_CALLBACK_AGENT_ID"), ("token", "WECOM_CALLBACK_TOKEN"),- ("encoding_aes_key", "WECOM_CALLBACK_ENCODING_AES_KEY"),- # No host default: falsy extra.host lets the adapter's dual-stack DEFAULT_HOST=None bind v4+v6.- ("host", "WECOM_CALLBACK_HOST"), ("port", "WECOM_CALLBACK_PORT", "", _int_or(8645)),- ),- ),- # Weixin (personal WeChat via iLink Bot API)- _Cred(- Platform.WEIXIN, (("WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"),), token="WEIXIN_TOKEN",- optional=(("account_id", "WEIXIN_ACCOUNT_ID"),),- optional_stripped=(- ("base_url", "WEIXIN_BASE_URL", _strip_slash), ("cdn_base_url", "WEIXIN_CDN_BASE_URL", _strip_slash),- ("dm_policy", "WEIXIN_DM_POLICY", str.lower), ("group_policy", "WEIXIN_GROUP_POLICY", str.lower),- ("allow_from", "WEIXIN_ALLOWED_USERS"), ("group_allow_from", "WEIXIN_GROUP_ALLOWED_USERS"),- ("split_multiline_messages", "WEIXIN_SPLIT_MULTILINE_MESSAGES"),- ),- home="WEIXIN_HOME_CHANNEL", home_strip=True,- ),- # BlueBubbles (iMessage). ``require_mention`` is always written: an unset env reads as "" → False.- _Cred(- Platform.BLUEBUBBLES, ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),- fixed=(- ("server_url", "BLUEBUBBLES_SERVER_URL", "", _strip_slash), ("password", "BLUEBUBBLES_PASSWORD"),- ("webhook_host", "BLUEBUBBLES_WEBHOOK_HOST", "127.0.0.1"),- ("webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", "", _int_or(8645)),- ("webhook_path", "BLUEBUBBLES_WEBHOOK_PATH", "/bluebubbles-webhook"),- ("send_read_receipts", "BLUEBUBBLES_SEND_READ_RECEIPTS", "true", is_truthy_value),- ("require_mention", "BLUEBUBBLES_REQUIRE_MENTION", "", _truthy_token),- ),- optional=(("mention_patterns", "BLUEBUBBLES_MENTION_PATTERNS", _mention_patterns),),- ),- _Home(Platform.BLUEBUBBLES, "BLUEBUBBLES_HOME_CHANNEL"),- # QQ (Official Bot API v2)- _Cred(- Platform.QQBOT, (("QQ_APP_ID", "QQ_CLIENT_SECRET"),),- optional=(("app_id", "QQ_APP_ID"), ("client_secret", "QQ_CLIENT_SECRET")),- optional_stripped=(("allow_from", "QQ_ALLOWED_USERS"), ("group_allow_from", "QQ_GROUP_ALLOWED_USERS")),- then=_qq_home,- ),- # Yuanbao — YUANBAO_APP_ID preferred over the legacy YUANBAO_APP_KEY- _Cred(- Platform.YUANBAO, (("YUANBAO_APP_ID", "YUANBAO_APP_KEY"), "YUANBAO_APP_SECRET"),- fixed=(("app_id", ("YUANBAO_APP_ID", "YUANBAO_APP_KEY")), ("app_secret", "YUANBAO_APP_SECRET")),- optional=(- ("bot_id", "YUANBAO_BOT_ID"), ("ws_url", "YUANBAO_WS_URL"),- ("api_domain", "YUANBAO_API_DOMAIN"), ("route_env", "YUANBAO_ROUTE_ENV"),- ("dm_policy", "YUANBAO_DM_POLICY", _strip_lower), ("dm_allow_from", "YUANBAO_DM_ALLOW_FROM"),- ("group_policy", "YUANBAO_GROUP_POLICY", _strip_lower), ("group_allow_from", "YUANBAO_GROUP_ALLOW_FROM"),- ),- home="YUANBAO_HOME_CHANNEL",- ),-- _enable_plugin_platforms_from_env,- _relay,- _scrub_explicit_markers,-)-def _apply_env_overrides(config: GatewayConfig) -> None:- """Apply environment variable overrides to *config* (see ``_ENV_STEPS``)."""- for step in _ENV_STEPS:- step(config)+ """Apply environment variable overrides to *config*.++ Order: plugin platforms' declared env rows, then the core-only rows (api_server, webhook,+ msgraph_webhook; each touches only its own platform), then the registry enable pass, relay+ disabling (needs every platform's final ``enabled``), and the marker scrub, which must be last.+ """+ entries = _configured_plugin_entries(config)+ _apply_plugin_env_overrides(config, entries)+ _api_server(config)+ _webhook(config)+ _msgraph_webhook(config)+ _enable_plugin_platforms_from_env(config, entries)+ _relay(config)+ _scrub_explicit_markers(config)diff --git a/gateway/platform_env.py b/gateway/platform_env.pynew file mode 100644index 00000000000..ce0b810daa0--- /dev/null+++ b/gateway/platform_env.py@@ -0,0 +1,175 @@+"""Declarative env-credential bridge a platform plugin attaches to its ``PlatformEntry``.++A platform declares ``env_overrides`` (ordered ``step(config)`` callables, usually :class:`EnvCred`,+:func:`home_step`, :func:`reply_mode_step`) and ``env_enable_credentials`` (the env names its+explicit-disable WARNING cites). ``gateway.config_env._apply_env_overrides`` runs the steps of every+platform with activation evidence, so the data lives with the adapter instead of in a core table.++Import-light on purpose (only ``gateway.config``): adapters import it at module load.+"""++import contextlib+import json+import logging+from dataclasses import dataclass+from functools import partial+from typing import Any, Callable, Optional++from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig, _getenv_str++# Logger name parity with the origin module: records stay under "gateway.config".+logger = logging.getLogger("gateway.config")++getenv = _getenv_str+++# --- small value parsers -----------------------------------------------------++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."""+ def parse(raw: str) -> int:+ try:+ return int(str(raw).strip(), 10)+ except (TypeError, ValueError):+ return default+ return parse+++def strip_slash(value: str) -> str:+ return value.rstrip("/")+++def strip_lower(value: str) -> str:+ return value.strip().lower()+++def truthy_token(value: str) -> bool:+ return value.lower() in {"true", "1", "yes", "on"}+++def mention_patterns(value: str) -> Any:+ """JSON list, else comma/newline separated."""+ try:+ return json.loads(value)+ except ValueError: # json.JSONDecodeError+ return csv_list(value.replace("\n", ","))+++def csv_extras(extra: dict[str, Any], spec) -> None:+ """``extra[key] = csv_list(raw)`` for each ``(key, raw)`` whose list is non-empty."""+ for key, raw in spec:+ items = csv_list(raw)+ if items:+ extra[key] = items+++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)+ return next((v for v in map(getenv, envs) if v), "")+++# --- reusable steps -----------------------------------------------------------++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.++ ``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)+ if strip:+ value = value.strip()+ if not value:+ continue+ if fn and fn[0] is INT:+ with contextlib.suppress(ValueError):+ extra[key] = int(value)+ else:+ extra[key] = fn[0](value) if fn else value+++def env_home_channel(config: GatewayConfig, platform: Platform, env_base: str, *, strip: bool = False) -> None:+ """Set ``home_channel`` from ``<env_base>`` (+``_NAME``/``_THREAD_ID``) when the platform is configured."""+ chat_id = getenv(env_base)+ if strip:+ chat_id = chat_id.strip()+ if chat_id and platform in config.platforms:+ config.platforms[platform].home_channel = HomeChannel(+ platform=platform, chat_id=chat_id,+ name=getenv(f"{env_base}_NAME", "Home"), thread_id=getenv(f"{env_base}_THREAD_ID") or None,+ )+++def env_reply_mode(config: GatewayConfig, platform: Platform, env: str) -> None:+ mode = getenv(env).lower()+ if mode in {"off", "first", "all"}:+ config.platforms.setdefault(platform, PlatformConfig()).reply_to_mode = mode+++# ``partial`` (not a closure) so ``hermes_cli.profile_channels`` can read the env names a step owns+# from ``step.keywords`` (``env`` / ``env_base``).+def home_step(platform: Platform, env_base: str, *, strip: bool = False):+ return partial(env_home_channel, platform=platform, env_base=env_base, strip=strip)+++def reply_mode_step(platform: Platform, env: str):+ return partial(env_reply_mode, platform=platform, env=env)+++def enable_from_env(config: GatewayConfig, platform: Platform) -> PlatformConfig:+ """Enable *platform* on env credentials unless config.yaml explicitly disabled it (warns once).+ Delegates to the core gate, which owns the explicit-disable marker and the one-time WARNING."""+ from gateway.config_env import _enable_from_env # lazy: config_env imports this module+ return _enable_from_env(config, platform)+++@dataclass(frozen=True)+class EnvCred:+ """Credential-gated platform enable, applied as ``step(config)``.++ ``creds``: env names that must ALL be truthy (inner tuple = ANY of). ``token``: env stored as+ ``PlatformConfig.token`` even when yaml disables the adapter (sending skills use it). ``fixed``:+ ``(extra_key, env[, default[, fn]])`` always written once enabled. ``optional*``: ``env_extras``+ specs. ``warn_missing``: ``(env, msg)`` logged BEFORE enabling when blank. ``then``: tail+ ``fn(config, platform_config)``. ``home``: ``env_home_channel`` env base applied only when the gate passed.+ """+ platform: Platform+ creds: tuple+ token: Optional[str] = None+ fixed: tuple = ()+ optional: tuple = ()+ optional_stripped: tuple = ()+ warn_missing: Optional[tuple] = None+ then: Optional[Callable[[GatewayConfig, PlatformConfig], None]] = None+ home: Optional[str] = None+ home_strip: bool = False++ def __call__(self, config: GatewayConfig) -> None:+ if not all(env_first(group) for group in self.creds):+ return+ if self.warn_missing and not getenv(self.warn_missing[0]):+ logger.warning(self.warn_missing[1])+ platform_config = enable_from_env(config, self.platform)+ if self.token and (token := getenv(self.token)):+ platform_config.token = token+ extra = platform_config.extra+ for key, env, *rest in self.fixed:+ default = rest[0] if rest else ""+ value = env_first(env) or default if isinstance(env, tuple) else getenv(env, default)+ extra[key] = rest[1](value) if len(rest) > 1 else value+ env_extras(extra, self.optional)+ env_extras(extra, self.optional_stripped, strip=True)+ if self.then is not None:+ self.then(config, platform_config)+ if self.home:+ env_home_channel(config, self.platform, self.home, strip=self.home_strip)diff --git a/gateway/platform_registry.py b/gateway/platform_registry.pyindex 8a6043d0b67..c7a0625f10a 100644--- a/gateway/platform_registry.py+++ b/gateway/platform_registry.py@@ -160,6 +160,15 @@ class PlatformEntry:# ``{ENV_KEY: (accepts(value) -> bool, 400 detail)}``: the dashboard PUT rejects a non-empty value# the predicate refuses, catching credentials pasted into the wrong field.env_value_rules: dict = field(default_factory=dict)+ # --- env ---+ # Ordered ``step(GatewayConfig) -> None`` env->config bridge run by ``_apply_env_overrides`` for a+ # platform with activation evidence (``gateway.platform_env.EnvCred`` / ``home_step`` /+ # ``reply_mode_step``); () = none. Unlike ``env_enablement_fn`` it runs whether or not deps are+ # importable and may set token / home channel / reply mode or force-disable.+ env_overrides: tuple = ()+ # Env names whose presence drives that enable, cited by the explicit-disable WARNING and used by+ # ``hermes_cli.profile_channels`` as the platform's credential set; () = none declared.+ env_enable_credentials: tuple = ()def core_ships_platform(name: str) -> bool:diff --git a/hermes_cli/profile_channels.py b/hermes_cli/profile_channels.pyindex f1510b3e488..ac04c4a71a2 100644--- a/hermes_cli/profile_channels.py+++ b/hermes_cli/profile_channels.py@@ -7,8 +7,8 @@ duplicate-credential finding per platform.The inventory is OWNERSHIP-based and evaluated in the SOURCE profile's plugin scope: every adapter(built-in ``Platform`` member, a platform that left core — its ``LEFT_CORE`` row, plugin installed ornot — or a plugin registered under the source's ``HERMES_HOME``) owns the env-keys it declares outright (``required_env``, allowlist / allow-all / home-channel names, the gateway-env-override table ``gateway.config_env._ENV_STEPS`` / ``_ENV_ENABLE_CREDENTIALS``) plus every key+keys it declares outright (``required_env``, allowlist / allow-all / home-channel names, its+``env_overrides`` / ``env_enable_credentials``, core's ``config_env._ENV_ENABLE_CREDENTIALS``) plus every keyunder its canonical ``<PLATFORM>_`` prefix and its historical alias prefixes. Gateway-wide channelpolicy (``GATEWAY_ALLOW_ALL_USERS`` / ``GATEWAY_ALLOWED_USERS``) and relay enrollment identity(``GATEWAY_RELAY_*``) are channel settings too. A prefix an adapter SHARES with a non-channel@@ -120,7 +120,7 @@ def platform_ids(source_dir: Optional[Path] = None) -> list[str]:def _cred_row_envs(row) -> set[str]:- """Every env name a ``gateway.config_env._Cred`` row reads."""+ """Every env name a ``gateway.platform_env.EnvCred`` row reads."""names: set[str] = set()def _flatten(spec) -> None:@@ -142,20 +142,29 @@ def _cred_row_envs(row) -> set[str]:return names-def config_env_table_keys() -> dict[str, str]:- """``{ENV_KEY: platform_id}`` for the names the gateway env-override table reads outright: the- enable-credential sets and every ``_Cred`` row. Registry-free, so it is cheap at import time;- raises if the table cannot be read (callers decide whether that is fatal)."""+def config_env_table_keys(entries: Iterable = ()) -> dict[str, str]:+ """``{ENV_KEY: platform_id}`` for the names the gateway env overrides read outright: core's+ enable-credential sets plus, for each given registry entry, its ``env_enable_credentials`` and+ every ``EnvCred`` row of its ``env_overrides``. With no *entries* it is registry-free (core rows+ only), so it stays cheap at import time; raises if the core table cannot be read."""from gateway import config_env+ from gateway.platform_env import EnvCredkeys: dict[str, str] = {}for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():keys.update(dict.fromkeys(names, platform.value))- for step in config_env._ENV_STEPS:- if isinstance(step, config_env._Cred):- keys.update(dict.fromkeys(_cred_row_envs(step), step.platform.value))+ for entry in entries:+ keys.update(dict.fromkeys(getattr(entry, "env_enable_credentials", ()) or (), entry.name))+ for step in getattr(entry, "env_overrides", ()) or ():+ if isinstance(step, EnvCred):+ keys.update(dict.fromkeys(_cred_row_envs(step), step.platform.value))return keys+def _env_override_steps(entries: Iterable) -> list:+ """Every step a registry entry declares in ``env_overrides``."""+ return [step for entry in entries for step in getattr(entry, "env_overrides", ()) or ()]++def declared_channel_env_keys(source_dir: Optional[Path] = None) -> dict[str, str]:"""``{ENV_KEY: platform_id}`` for every env name an adapter declares outright (registry entryfields, the gateway env-override table) plus gateway-wide channel policy. Prefix matching covers@@ -164,14 +173,14 @@ def declared_channel_env_keys(source_dir: Optional[Path] = None) -> dict[str, stfor feature in _left_core_platforms():keys.update(dict.fromkeys(feature.enable_env, feature.platform))with _plugin_scope(source_dir):- for entry in _registry_entries():+ entries = _registry_entries()+ for entry in entries:for name in (*entry.required_env, entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var):if name:keys[name] = entry.namewith contextlib.suppress(Exception):- from gateway import config_env- keys.update(config_env_table_keys())- for step in config_env._ENV_STEPS:+ keys.update(config_env_table_keys(entries))+ for step in _env_override_steps(entries):if isinstance(step, partial):platform = step.keywords.get("platform")for kw in ("env", "env_base"):@@ -184,12 +193,13 @@ def _policy_env_keys(source_dir: Optional[Path] = None) -> set[str]:"""Allowlist / allow-all / home-channel names adapters declare — channel-only by nature."""names: set[str] = set(_GATEWAY_POLICY_KEYS)with _plugin_scope(source_dir):- for entry in _registry_entries():+ entries = _registry_entries()+ for entry in entries:names.update(n for n in (entry.allowed_users_env, entry.allow_all_env, entry.cron_deliver_env_var) if n)with contextlib.suppress(Exception):- from gateway import config_env- for step in config_env._ENV_STEPS:- if isinstance(step, config_env._Cred) and step.home:+ from gateway.platform_env import EnvCred+ for step in _env_override_steps(entries):+ if isinstance(step, EnvCred) and step.home:names.update({step.home, f"{step.home}_NAME", f"{step.home}_THREAD_ID"})elif isinstance(step, partial) and step.keywords.get("env_base"):base = step.keywords["env_base"]@@ -211,14 +221,18 @@ def credential_env_keys() -> dict[str, str]:keys: dict[str, str] = {}for feature in _left_core_platforms():keys.update(dict.fromkeys(feature.enable_env, feature.platform))- for entry in _registry_entries():+ entries = _registry_entries()+ for entry in entries:keys.update(dict.fromkeys(entry.required_env, entry.name))with contextlib.suppress(Exception):from gateway import config_env+ from gateway.platform_env import EnvCredfor platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():keys.update(dict.fromkeys(names, platform.value))- for step in config_env._ENV_STEPS:- if isinstance(step, config_env._Cred):+ for entry in entries:+ keys.update(dict.fromkeys(entry.env_enable_credentials, entry.name))+ for step in _env_override_steps(entries):+ if isinstance(step, EnvCred):creds: set[str] = set()for group in step.creds:creds.update((group,) if isinstance(group, str) else group)@@ -254,7 +268,7 @@ def _explicit_enabled(raw: dict, pid: str) -> Optional[bool]:def _shared_adapters_active(source_dir: Optional[Path], shared: dict[str, tuple[str, ...]]) -> set[str]:"""Shared-prefix platforms the SOURCE runs as a channel: explicitly enabled in its config.yaml, orauto-enabled by a complete credential set in its ``.env`` and not explicitly disabled — the same- gate ``gateway.config_env._Cred`` applies at gateway start."""+ gate ``gateway.platform_env.EnvCred`` applies at gateway start."""if source_dir is None:return set(shared) # no source to consult: the historical (strip) behaviourraw: dict = {}@@ -268,11 +282,16 @@ def _shared_adapters_active(source_dir: Optional[Path], shared: dict[str, tuple[from gateway import config_envfor platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():creds_by_platform[platform.value] = set(names)+ with _plugin_scope(source_dir):+ entries = _registry_entries()+ # A declared enable-credential set beats a left-core row and the manifest ``required_env``.+ for entry in entries:+ if entry.env_enable_credentials:+ creds_by_platform.setdefault(entry.name, set(entry.env_enable_credentials))for feature in _left_core_platforms():creds_by_platform.setdefault(feature.platform, set(feature.enable_env))- with _plugin_scope(source_dir):- for entry in _registry_entries():- creds_by_platform.setdefault(entry.name, set(entry.required_env))+ for entry in entries:+ creds_by_platform.setdefault(entry.name, set(entry.required_env))active: set[str] = set()for pid in shared:explicit = _explicit_enabled(raw, pid)diff --git a/plugins/platforms/bluebubbles/adapter.py b/plugins/platforms/bluebubbles/adapter.pyindex 0e2f0e5bdef..a473535df1c 100644--- a/plugins/platforms/bluebubbles/adapter.py+++ b/plugins/platforms/bluebubbles/adapter.py@@ -700,6 +700,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(name="bluebubbles", label="BlueBubbles (iMessage)", adapter_factory=BlueBubblesAdapter,dashboard_description="Use Hermes through iMessage via a BlueBubbles server.",@@ -717,4 +718,6 @@ def register(ctx) -> None:max_message_length=0, pii_safe=True, emoji="💬", allow_update_command=True,platform_hint=_PLATFORM_HINT,display_tier="low",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/bluebubbles/gateway_env.py b/plugins/platforms/bluebubbles/gateway_env.pynew file mode 100644index 00000000000..78053a15099--- /dev/null+++ b/plugins/platforms/bluebubbles/gateway_env.py@@ -0,0 +1,23 @@+"""BlueBubbles (iMessage) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, home_step, int_or, mention_patterns, strip_slash, truthy_token+from utils import is_truthy_value++ENV_ENABLE_CREDENTIALS = ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD")+# ``require_mention`` is always written: an unset env reads as "" -> False.+ENV_OVERRIDES = (+ EnvCred(+ Platform.BLUEBUBBLES, ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),+ fixed=(+ ("server_url", "BLUEBUBBLES_SERVER_URL", "", strip_slash), ("password", "BLUEBUBBLES_PASSWORD"),+ ("webhook_host", "BLUEBUBBLES_WEBHOOK_HOST", "127.0.0.1"),+ ("webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", "", int_or(8645)),+ ("webhook_path", "BLUEBUBBLES_WEBHOOK_PATH", "/bluebubbles-webhook"),+ ("send_read_receipts", "BLUEBUBBLES_SEND_READ_RECEIPTS", "true", is_truthy_value),+ ("require_mention", "BLUEBUBBLES_REQUIRE_MENTION", "", truthy_token),+ ),+ optional=(("mention_patterns", "BLUEBUBBLES_MENTION_PATTERNS", mention_patterns),),+ ),+ home_step(Platform.BLUEBUBBLES, "BLUEBUBBLES_HOME_CHANNEL"),+)diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex 5b38c411481..8eb6a5ed11f 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -849,6 +849,7 @@ def _is_connected(config) -> bool:def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(standalone_send=StandaloneSendPolicy(text_direct=True),name="dingtalk", label="DingTalk", adapter_factory=DingTalkAdapter, check_fn=dingtalk_deps_present,@@ -861,4 +862,6 @@ def register(ctx) -> None:allow_all_env="DINGTALK_ALLOW_ALL_USERS", cron_deliver_env_var="DINGTALK_HOME_CHANNEL",standalone_sender_fn=_standalone_send, emoji="🐳", allow_update_command=True,display_tier="low",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/dingtalk/gateway_env.py b/plugins/platforms/dingtalk/gateway_env.pynew file mode 100644index 00000000000..6cfdbd80aa8--- /dev/null+++ b/plugins/platforms/dingtalk/gateway_env.py@@ -0,0 +1,13 @@+"""DingTalk env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred++ENV_ENABLE_CREDENTIALS = ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET")+ENV_OVERRIDES = (+ EnvCred(+ Platform.DINGTALK, ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),+ fixed=(("client_id", "DINGTALK_CLIENT_ID"), ("client_secret", "DINGTALK_CLIENT_SECRET")),+ home="DINGTALK_HOME_CHANNEL",+ ),+)diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 70744128c3e..5fb1939ef97 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -7373,6 +7373,7 @@ def register(ctx) -> None:from plugins.platforms.discord.onboarding import interactive_setupfrom .dashboard_card import DASHBOARD_CARD+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(**SEND_ENTRY_KWARGS, # send_message target syntax + routingname="discord",@@ -7405,4 +7406,6 @@ def register(ctx) -> None:display_tier="high",# "-# " subtext reads as metadata.display_overrides={"reasoning_style": "subtext"},+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/discord/gateway_env.py b/plugins/platforms/discord/gateway_env.pynew file mode 100644index 00000000000..9414ab2b664--- /dev/null+++ b/plugins/platforms/discord/gateway_env.py@@ -0,0 +1,12 @@+"""Discord env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, home_step, reply_mode_step++ENV_ENABLE_CREDENTIALS = ("DISCORD_BOT_TOKEN",)+# Order matters: the home channel is read BEFORE the reply mode may create the entry.+ENV_OVERRIDES = (+ EnvCred(Platform.DISCORD, ("DISCORD_BOT_TOKEN",), token="DISCORD_BOT_TOKEN"),+ home_step(Platform.DISCORD, "DISCORD_HOME_CHANNEL"),+ reply_mode_step(Platform.DISCORD, "DISCORD_REPLY_TO_MODE"),+)diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex b5a40a8fc14..76ff8c70ae4 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -1011,6 +1011,7 @@ _SEND_TARGET_RE = re.compile(r"^\s*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=regex_stripped_parser(_SEND_TARGET_RE),standalone_send=StandaloneSendPolicy(text_direct=True),@@ -1025,4 +1026,6 @@ def register(ctx) -> None:max_message_length=50_000, pii_safe=True, emoji="📧", allow_update_command=True,platform_hint=_PLATFORM_HINT,display_tier="minimal",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/email/gateway_env.py b/plugins/platforms/email/gateway_env.pynew file mode 100644index 00000000000..fe5d82d568a--- /dev/null+++ b/plugins/platforms/email/gateway_env.py@@ -0,0 +1,13 @@+"""Email env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, home_step++ENV_ENABLE_CREDENTIALS = ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST")+ENV_OVERRIDES = (+ EnvCred(+ Platform.EMAIL, ("EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST"),+ fixed=(("address", "EMAIL_ADDRESS"), ("imap_host", "EMAIL_IMAP_HOST"), ("smtp_host", "EMAIL_SMTP_HOST")),+ ),+ home_step(Platform.EMAIL, "EMAIL_HOME_ADDRESS"),+)diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 7e16b35a8e3..e416e720fb4 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -4482,6 +4482,7 @@ def register(ctx) -> None:from plugins.platforms.feishu.adapter_hint import PLATFORM_HINTfrom plugins.platforms.feishu.send_targets import SEND_ENTRY_KWARGSfrom .dashboard_card import DASHBOARD_CARD+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(**SEND_ENTRY_KWARGS, # send_message target syntax + routingname="feishu", label="Feishu / Lark", adapter_factory=FeishuAdapter,@@ -4497,4 +4498,6 @@ def register(ctx) -> None:allow_bots_env="FEISHU_ALLOW_BOTS",platform_hint=PLATFORM_HINT,display_tier="medium",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/feishu/gateway_env.py b/plugins/platforms/feishu/gateway_env.pynew file mode 100644index 00000000000..21a04cce3b6--- /dev/null+++ b/plugins/platforms/feishu/gateway_env.py@@ -0,0 +1,17 @@+"""Feishu/Lark env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred++ENV_ENABLE_CREDENTIALS = ("FEISHU_APP_ID", "FEISHU_APP_SECRET")+ENV_OVERRIDES = (+ EnvCred(+ Platform.FEISHU, ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),+ fixed=(+ ("app_id", "FEISHU_APP_ID"), ("app_secret", "FEISHU_APP_SECRET"),+ ("domain", "FEISHU_DOMAIN", "feishu"), ("connection_mode", "FEISHU_CONNECTION_MODE", "websocket"),+ ),+ optional=(("encrypt_key", "FEISHU_ENCRYPT_KEY"), ("verification_token", "FEISHU_VERIFICATION_TOKEN")),+ home="FEISHU_HOME_CHANNEL",+ ),+)diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex eeb222d6ec5..8106041ac40 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -3259,6 +3259,7 @@ def register(ctx) -> None:from plugins.platforms.matrix.adapter_hint import PLATFORM_HINTfrom plugins.platforms.matrix.send_targets import SEND_ENTRY_KWARGSfrom .dashboard_card import DASHBOARD_CARD+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(**SEND_ENTRY_KWARGS, # send_message target syntax + routingname="matrix", label="Matrix", adapter_factory=MatrixAdapter, check_fn=matrix_deps_present,@@ -3271,4 +3272,6 @@ def register(ctx) -> None:allow_update_command=True,platform_hint=PLATFORM_HINT,display_tier="medium",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/matrix/gateway_env.py b/plugins/platforms/matrix/gateway_env.pynew file mode 100644index 00000000000..05f055c927e--- /dev/null+++ b/plugins/platforms/matrix/gateway_env.py@@ -0,0 +1,26 @@+"""Matrix env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platform_env import EnvCred, env_extras, getenv, home_step+from utils import is_truthy_value+++def _e2ee(config: GatewayConfig, matrix_config: PlatformConfig) -> None:+ mode = getenv("MATRIX_E2EE_MODE").strip().lower()+ matrix_config.extra["encryption"] = mode in ("required", "require", "optional", "prefer", "preferred") or is_truthy_value(getenv("MATRIX_ENCRYPTION"))+ if mode:+ matrix_config.extra["e2ee_mode"] = mode+ env_extras(matrix_config.extra, (("device_id", "MATRIX_DEVICE_ID"),))+++ENV_ENABLE_CREDENTIALS = ("MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD")+ENV_OVERRIDES = (+ EnvCred(+ Platform.MATRIX, (("MATRIX_ACCESS_TOKEN", "MATRIX_PASSWORD"),), token="MATRIX_ACCESS_TOKEN",+ warn_missing=("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN/MATRIX_PASSWORD set but MATRIX_HOMESERVER is missing"),+ fixed=(("homeserver", "MATRIX_HOMESERVER"),),+ optional=(("user_id", "MATRIX_USER_ID"), ("password", "MATRIX_PASSWORD")),+ then=_e2ee,+ ),+ home_step(Platform.MATRIX, "MATRIX_HOME_ROOM"),+)diff --git a/plugins/platforms/mattermost/adapter.py b/plugins/platforms/mattermost/adapter.pyindex 0d862da8976..81f2f66a5cb 100644--- a/plugins/platforms/mattermost/adapter.py+++ b/plugins/platforms/mattermost/adapter.py@@ -726,6 +726,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(name="mattermost", label="Mattermost", adapter_factory=MattermostAdapter,dashboard_description="Connect Hermes to Mattermost channels and direct messages.",@@ -741,4 +742,6 @@ def register(ctx) -> None:max_message_length=MAX_POST_LENGTH, emoji="💬", allow_update_command=True,platform_hint=_PLATFORM_HINT,display_tier="medium",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/mattermost/gateway_env.py b/plugins/platforms/mattermost/gateway_env.pynew file mode 100644index 00000000000..14a92e67489--- /dev/null+++ b/plugins/platforms/mattermost/gateway_env.py@@ -0,0 +1,14 @@+"""Mattermost env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, home_step++ENV_ENABLE_CREDENTIALS = ("MATTERMOST_TOKEN",)+ENV_OVERRIDES = (+ EnvCred(+ Platform.MATTERMOST, ("MATTERMOST_TOKEN",), token="MATTERMOST_TOKEN",+ warn_missing=("MATTERMOST_URL", "MATTERMOST_TOKEN set but MATTERMOST_URL is missing"),+ fixed=(("url", "MATTERMOST_URL"),),+ ),+ home_step(Platform.MATTERMOST, "MATTERMOST_HOME_CHANNEL"),+)diff --git a/plugins/platforms/qqbot/gateway_env.py b/plugins/platforms/qqbot/gateway_env.pynew file mode 100644index 00000000000..b2dc3ce71af--- /dev/null+++ b/plugins/platforms/qqbot/gateway_env.py@@ -0,0 +1,38 @@+"""QQ (Official Bot API v2) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++import logging++from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig+from gateway.platform_env import EnvCred, getenv++# Logger name parity with the origin module (gateway.config_env): records stay under "gateway.config".+logger = logging.getLogger("gateway.config")+++def _home(config: GatewayConfig, qq_config: PlatformConfig) -> None:+ qq_home = getenv("QQBOT_HOME_CHANNEL").strip()+ name_env = "QQBOT_HOME_CHANNEL_NAME"+ if not qq_home and (qq_home := getenv("QQ_HOME_CHANNEL").strip()):+ # Back-compat: accept the pre-rename name and warn.+ name_env = "QQ_HOME_CHANNEL_NAME"+ logger.warning(+ "QQ_HOME_CHANNEL is deprecated; rename to QQBOT_HOME_CHANNEL "+ "in your .env for consistency with the platform key."+ )+ if qq_home:+ qq_config.home_channel = HomeChannel(+ platform=Platform.QQBOT, chat_id=qq_home,+ name=getenv("QQBOT_HOME_CHANNEL_NAME") or getenv(name_env, "Home"),+ thread_id=getenv("QQBOT_HOME_CHANNEL_THREAD_ID") or getenv("QQ_HOME_CHANNEL_THREAD_ID") or None,+ )+++ENV_ENABLE_CREDENTIALS = ("QQ_APP_ID", "QQ_CLIENT_SECRET")+ENV_OVERRIDES = (+ EnvCred(+ Platform.QQBOT, (("QQ_APP_ID", "QQ_CLIENT_SECRET"),),+ optional=(("app_id", "QQ_APP_ID"), ("client_secret", "QQ_CLIENT_SECRET")),+ optional_stripped=(("allow_from", "QQ_ALLOWED_USERS"), ("group_allow_from", "QQ_GROUP_ALLOWED_USERS")),+ then=_home,+ ),+)diff --git a/plugins/platforms/qqbot/register.py b/plugins/platforms/qqbot/register.pyindex 8e53a15a9cf..7399a625067 100644--- a/plugins/platforms/qqbot/register.py+++ b/plugins/platforms/qqbot/register.py@@ -132,6 +132,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(standalone_send=StandaloneSendPolicy(label="QQ Bot", media=True, captionable=True, text_direct=True),name="qqbot",@@ -154,4 +155,6 @@ def register(ctx) -> None:# QQ's dm/group policy is YAML-only (no env var); QQ_ALLOW_ALL_USERS is still the opt-in.own_policy_env=("", ""),platform_hint=_PLATFORM_HINT,+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/signal/gateway_env.py b/plugins/platforms/signal/gateway_env.pynew file mode 100644index 00000000000..f11f1476b29--- /dev/null+++ b/plugins/platforms/signal/gateway_env.py@@ -0,0 +1,17 @@+"""Signal env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, home_step+from utils import is_truthy_value++ENV_ENABLE_CREDENTIALS = ("SIGNAL_HTTP_URL",)+ENV_OVERRIDES = (+ EnvCred(+ Platform.SIGNAL, ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"),+ fixed=(+ ("http_url", "SIGNAL_HTTP_URL"), ("account", "SIGNAL_ACCOUNT"),+ ("ignore_stories", "SIGNAL_IGNORE_STORIES", "true", is_truthy_value),+ ),+ ),+ home_step(Platform.SIGNAL, "SIGNAL_HOME_CHANNEL"),+)diff --git a/plugins/platforms/signal/register.py b/plugins/platforms/signal/register.pyindex 89618c50c04..c050b89017a 100644--- a/plugins/platforms/signal/register.py+++ b/plugins/platforms/signal/register.py@@ -51,6 +51,7 @@ def _parse_send_target(ref):def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=_parse_send_target,# Attachments ride the JSON-RPC param on the final chunk.@@ -72,4 +73,6 @@ def register(ctx) -> None:emoji="📡", pii_safe=True, allow_update_command=True,platform_hint=_PLATFORM_HINT,display_tier="low",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex e25c5c12483..4c3f8a6692f 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -6913,6 +6913,7 @@ def register(ctx) -> None:from plugins.platforms.slack.adapter_hint import PLATFORM_HINTfrom plugins.platforms.slack.send_targets import SEND_ENTRY_KWARGSfrom .dashboard_card import DASHBOARD_CARD+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(**SEND_ENTRY_KWARGS, # send_message target syntax + routingname="slack",@@ -6946,4 +6947,6 @@ def register(ctx) -> None:display_tier="medium",# Bolt posts cannot be edited like CLI; "new"/"all" spam permanent lines.display_overrides={"tool_progress": "off", "long_running_notifications": False, "busy_ack_detail": False},+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/slack/gateway_env.py b/plugins/platforms/slack/gateway_env.pynew file mode 100644index 00000000000..ff3906ef9b9--- /dev/null+++ b/plugins/platforms/slack/gateway_env.py@@ -0,0 +1,23 @@+"""Slack env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import GatewayConfig, HomeChannel, Platform, PlatformConfig+from gateway.platform_env import EnvCred, getenv+++def _home(config: GatewayConfig) -> None:+ """SLACK_HOME_CHANNEL creates a disabled Slack entry if needed; user_id/scope_id provenance survives an unchanged chat_id."""+ if not (slack_home := getenv("SLACK_HOME_CHANNEL")):+ 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,+ )+++ENV_ENABLE_CREDENTIALS = ("SLACK_BOT_TOKEN",)+ENV_OVERRIDES = (EnvCred(Platform.SLACK, ("SLACK_BOT_TOKEN",), token="SLACK_BOT_TOKEN"), _home)diff --git a/plugins/platforms/sms/adapter.py b/plugins/platforms/sms/adapter.pyindex 2d73bacd9c6..1af18e063ec 100644--- a/plugins/platforms/sms/adapter.py+++ b/plugins/platforms/sms/adapter.py@@ -339,6 +339,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(standalone_send=StandaloneSendPolicy(text_direct=True),name="sms", label="SMS (Twilio)", adapter_factory=SmsAdapter,@@ -354,4 +355,6 @@ def register(ctx) -> None:emoji="📱", allow_update_command=True,platform_hint=_PLATFORM_HINT,display_tier="minimal",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/sms/gateway_env.py b/plugins/platforms/sms/gateway_env.pynew file mode 100644index 00000000000..d0c46226871--- /dev/null+++ b/plugins/platforms/sms/gateway_env.py@@ -0,0 +1,15 @@+"""SMS (Twilio) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platform_env import EnvCred, getenv, home_step+++def _api_key(config: GatewayConfig, sms_config: PlatformConfig) -> None:+ sms_config.api_key = getenv("TWILIO_AUTH_TOKEN")+++ENV_ENABLE_CREDENTIALS = ("TWILIO_ACCOUNT_SID",)+ENV_OVERRIDES = (+ EnvCred(Platform.SMS, ("TWILIO_ACCOUNT_SID",), then=_api_key),+ home_step(Platform.SMS, "SMS_HOME_CHANNEL"),+)diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 63aaf87aad6..e1a77feea14 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -7310,6 +7310,7 @@ def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""from plugins.platforms.telegram.adapter_hint import PLATFORM_HINTfrom .dashboard_card import DASHBOARD_CARD+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(name="telegram", label="Telegram", adapter_factory=_build_adapter, check_fn=telegram_deps_present,**DASHBOARD_CARD,@@ -7323,4 +7324,6 @@ def register(ctx) -> None:# Mobile inbox: quiet tool_progress / busy-ack, but keep interim commentary and heartbeats.display_overrides={"tool_progress": "off", "busy_ack_detail": False},target_ref_syntax_fn=parse_send_target,+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/telegram/gateway_env.py b/plugins/platforms/telegram/gateway_env.pynew file mode 100644index 00000000000..f8d84b6b894--- /dev/null+++ b/plugins/platforms/telegram/gateway_env.py@@ -0,0 +1,19 @@+"""Telegram env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platform_env import EnvCred, csv_list, getenv, home_step, reply_mode_step+++def _fallback_ips(config: GatewayConfig) -> None:+ if ips := getenv("TELEGRAM_FALLBACK_IPS"):+ config.platforms.setdefault(Platform.TELEGRAM, PlatformConfig()).extra["fallback_ips"] = csv_list(ips)+++ENV_ENABLE_CREDENTIALS = ("TELEGRAM_BOT_TOKEN",)+# Order matters: the reply mode / fallback IPs may create the entry the home channel then attaches to.+ENV_OVERRIDES = (+ EnvCred(Platform.TELEGRAM, ("TELEGRAM_BOT_TOKEN",), token="TELEGRAM_BOT_TOKEN"),+ reply_mode_step(Platform.TELEGRAM, "TELEGRAM_REPLY_TO_MODE"),+ _fallback_ips,+ home_step(Platform.TELEGRAM, "TELEGRAM_HOME_CHANNEL"),+)diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.pyindex af037617c5c..e3e071aa31c 100644--- a/plugins/platforms/wecom/adapter.py+++ b/plugins/platforms/wecom/adapter.py@@ -847,6 +847,7 @@ _WECOM_PLATFORM_HINT = (def register(ctx) -> None:common = dict(install_hint="Run `hermes setup` to install WeCom support.", emoji="💼", allow_update_command=True)+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=parse_nonempty,standalone_send=StandaloneSendPolicy(text_direct=True),@@ -864,6 +865,8 @@ def register(ctx) -> None:display_tier="low",# Non-editable, but its native "stream" msgtype gives a typing animation + cumulative updates.display_overrides={"streaming": True},+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements, ensure_wecom_callback_requirementsctx.register_platform(@@ -883,4 +886,6 @@ def register(ctx) -> None:required_env=["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],allowed_users_env="WECOM_CALLBACK_ALLOWED_USERS", allow_all_env="WECOM_CALLBACK_ALLOW_ALL_USERS", **common,display_tier="low",+ env_overrides=gateway_env.CALLBACK_ENV_OVERRIDES,+ env_enable_credentials=gateway_env.CALLBACK_ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/wecom/gateway_env.py b/plugins/platforms/wecom/gateway_env.pynew file mode 100644index 00000000000..cc59112c5ca--- /dev/null+++ b/plugins/platforms/wecom/gateway_env.py@@ -0,0 +1,28 @@+"""WeCom (bot + callback sibling) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, int_or++ENV_ENABLE_CREDENTIALS = ("WECOM_BOT_ID", "WECOM_SECRET")+ENV_OVERRIDES = (+ EnvCred(+ Platform.WECOM, ("WECOM_BOT_ID", "WECOM_SECRET"),+ fixed=(("bot_id", "WECOM_BOT_ID"), ("secret", "WECOM_SECRET")),+ optional=(("websocket_url", "WECOM_WEBSOCKET_URL"),),+ home="WECOM_HOME_CHANNEL",+ ),+)++CALLBACK_ENV_ENABLE_CREDENTIALS = ("WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET")+CALLBACK_ENV_OVERRIDES = (+ EnvCred(+ Platform.WECOM_CALLBACK, ("WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"),+ fixed=(+ ("corp_id", "WECOM_CALLBACK_CORP_ID"), ("corp_secret", "WECOM_CALLBACK_CORP_SECRET"),+ ("agent_id", "WECOM_CALLBACK_AGENT_ID"), ("token", "WECOM_CALLBACK_TOKEN"),+ ("encoding_aes_key", "WECOM_CALLBACK_ENCODING_AES_KEY"),+ # No host default: falsy extra.host lets the adapter's dual-stack DEFAULT_HOST=None bind v4+v6.+ ("host", "WECOM_CALLBACK_HOST"), ("port", "WECOM_CALLBACK_PORT", "", int_or(8645)),+ ),+ ),+)diff --git a/plugins/platforms/weixin/adapter.py b/plugins/platforms/weixin/adapter.pyindex a565af42216..3ebf6e79ed2 100644--- a/plugins/platforms/weixin/adapter.py+++ b/plugins/platforms/weixin/adapter.py@@ -1404,6 +1404,7 @@ _SEND_TARGET_RE = re.compile(r"^\s*((?:wxid|gh|v\d+|wm|wb)_[A-Za-z0-9_-]+|[A-Za-def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=regex_groups_parser(_SEND_TARGET_RE, thread_group=False),standalone_send=StandaloneSendPolicy(label="Weixin", media=True),@@ -1422,4 +1423,6 @@ def register(ctx) -> None:own_policy_env=("WEIXIN_DM_POLICY", "WEIXIN_GROUP_POLICY"),platform_hint=_PLATFORM_HINT,display_tier="low",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/weixin/gateway_env.py b/plugins/platforms/weixin/gateway_env.pynew file mode 100644index 00000000000..e146e7b0ded--- /dev/null+++ b/plugins/platforms/weixin/gateway_env.py@@ -0,0 +1,19 @@+"""Weixin (personal WeChat via iLink Bot API) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, strip_slash++ENV_ENABLE_CREDENTIALS = ("WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID")+ENV_OVERRIDES = (+ EnvCred(+ Platform.WEIXIN, (("WEIXIN_TOKEN", "WEIXIN_ACCOUNT_ID"),), token="WEIXIN_TOKEN",+ optional=(("account_id", "WEIXIN_ACCOUNT_ID"),),+ optional_stripped=(+ ("base_url", "WEIXIN_BASE_URL", strip_slash), ("cdn_base_url", "WEIXIN_CDN_BASE_URL", strip_slash),+ ("dm_policy", "WEIXIN_DM_POLICY", str.lower), ("group_policy", "WEIXIN_GROUP_POLICY", str.lower),+ ("allow_from", "WEIXIN_ALLOWED_USERS"), ("group_allow_from", "WEIXIN_GROUP_ALLOWED_USERS"),+ ("split_multiline_messages", "WEIXIN_SPLIT_MULTILINE_MESSAGES"),+ ),+ home="WEIXIN_HOME_CHANNEL", home_strip=True,+ ),+)diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex daa0cc74434..85aeef7c2be 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -1247,6 +1247,7 @@ _SEND_JID_RE = re.compile(r"^\s*[\w-]+@(?:g\.us|s\.whatsapp\.net|lid|broadcast|ndef register(ctx) -> None:+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=regex_stripped_parser(_SEND_JID_RE),# Media goes through Baileys /send-media; ``mentions`` force the standalone route too.@@ -1268,4 +1269,6 @@ def register(ctx) -> None:platform_hint=_PLATFORM_HINT,# Baileys bridge supports /edit.display_tier="medium",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/whatsapp/gateway_env.py b/plugins/platforms/whatsapp/gateway_env.pynew file mode 100644index 00000000000..4c6439872b4--- /dev/null+++ b/plugins/platforms/whatsapp/gateway_env.py@@ -0,0 +1,22 @@+"""WhatsApp (Baileys bridge) env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import GatewayConfig, Platform+from gateway.platform_env import enable_from_env, getenv, home_step+from utils import is_truthy_value+++def _enabled_flag(config: GatewayConfig) -> None:+ """WhatsApp (Baileys bridge) uses a flag, not credentials. WHATSAPP_ENABLED=false overrides YAML;+ WHATSAPP_ENABLED=true follows the credential contract — it never beats an explicit YAML disable+ (the dashboard's disable action writes only ``platforms.whatsapp.enabled: false`` and leaves the+ env flag on disk, #73289)."""+ raw = getenv("WHATSAPP_ENABLED")+ wa_cfg = config.platforms.get(Platform.WHATSAPP)+ if wa_cfg is not None and raw.lower() in {"false", "0", "no"}:+ wa_cfg.enabled = False+ elif is_truthy_value(raw):+ enable_from_env(config, Platform.WHATSAPP)+++ENV_ENABLE_CREDENTIALS = ("WHATSAPP_ENABLED",)+ENV_OVERRIDES = (_enabled_flag, home_step(Platform.WHATSAPP, "WHATSAPP_HOME_CHANNEL"))diff --git a/plugins/platforms/whatsapp_cloud/adapter.py b/plugins/platforms/whatsapp_cloud/adapter.pyindex 6facab8b614..70e7c0d4924 100644--- a/plugins/platforms/whatsapp_cloud/adapter.py+++ b/plugins/platforms/whatsapp_cloud/adapter.py@@ -1104,6 +1104,7 @@ def register(ctx) -> None:``whatsapp_cloud_unconfigured`` fatal error (same outcome as the former core wiring). No``standalone_sender_fn`` / ``max_message_length``: out-of-process ``send_message`` had noWhatsApp Cloud sender in core either, and ``send()`` chunks itself."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(name="whatsapp_cloud", label="WhatsApp Business (Cloud)", adapter_factory=WhatsAppCloudAdapter,dashboard_label="WhatsApp Cloud API",@@ -1118,4 +1119,6 @@ def register(ctx) -> None:platform_hint=_PLATFORM_HINT,# Adapter lacks edit_message; promote once it lands.display_tier="low",+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/plugins/platforms/whatsapp_cloud/gateway_env.py b/plugins/platforms/whatsapp_cloud/gateway_env.pynew file mode 100644index 00000000000..11be6c75572--- /dev/null+++ b/plugins/platforms/whatsapp_cloud/gateway_env.py@@ -0,0 +1,20 @@+"""WhatsApp Cloud API env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import INT, EnvCred, home_step++ENV_ENABLE_CREDENTIALS = ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN")+# Distinct from the Baileys bridge; both may run against different numbers.+ENV_OVERRIDES = (+ EnvCred(+ Platform.WHATSAPP_CLOUD, ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"),+ fixed=(("phone_number_id", "WHATSAPP_CLOUD_PHONE_NUMBER_ID"), ("access_token", "WHATSAPP_CLOUD_ACCESS_TOKEN")),+ optional=(+ ("app_id", "WHATSAPP_CLOUD_APP_ID"), ("app_secret", "WHATSAPP_CLOUD_APP_SECRET"),+ ("waba_id", "WHATSAPP_CLOUD_WABA_ID"), ("verify_token", "WHATSAPP_CLOUD_VERIFY_TOKEN"),+ ("webhook_host", "WHATSAPP_CLOUD_WEBHOOK_HOST"), ("webhook_port", "WHATSAPP_CLOUD_WEBHOOK_PORT", INT),+ ("webhook_path", "WHATSAPP_CLOUD_WEBHOOK_PATH"), ("api_version", "WHATSAPP_CLOUD_API_VERSION"),+ ),+ ),+ home_step(Platform.WHATSAPP_CLOUD, "WHATSAPP_CLOUD_HOME_CHANNEL"),+)diff --git a/plugins/platforms/yuanbao/gateway_env.py b/plugins/platforms/yuanbao/gateway_env.pynew file mode 100644index 00000000000..6ef7b167906--- /dev/null+++ b/plugins/platforms/yuanbao/gateway_env.py@@ -0,0 +1,20 @@+"""Yuanbao env -> gateway config bridge (``PlatformEntry.env_overrides``)."""++from gateway.config import Platform+from gateway.platform_env import EnvCred, strip_lower++ENV_ENABLE_CREDENTIALS = ("YUANBAO_APP_ID", "YUANBAO_APP_SECRET")+# YUANBAO_APP_ID preferred over the legacy YUANBAO_APP_KEY.+ENV_OVERRIDES = (+ EnvCred(+ Platform.YUANBAO, (("YUANBAO_APP_ID", "YUANBAO_APP_KEY"), "YUANBAO_APP_SECRET"),+ fixed=(("app_id", ("YUANBAO_APP_ID", "YUANBAO_APP_KEY")), ("app_secret", "YUANBAO_APP_SECRET")),+ optional=(+ ("bot_id", "YUANBAO_BOT_ID"), ("ws_url", "YUANBAO_WS_URL"),+ ("api_domain", "YUANBAO_API_DOMAIN"), ("route_env", "YUANBAO_ROUTE_ENV"),+ ("dm_policy", "YUANBAO_DM_POLICY", strip_lower), ("dm_allow_from", "YUANBAO_DM_ALLOW_FROM"),+ ("group_policy", "YUANBAO_GROUP_POLICY", strip_lower), ("group_allow_from", "YUANBAO_GROUP_ALLOW_FROM"),+ ),+ home="YUANBAO_HOME_CHANNEL",+ ),+)diff --git a/plugins/platforms/yuanbao/register.py b/plugins/platforms/yuanbao/register.pyindex c77fa7aab46..614a9d1292d 100644--- a/plugins/platforms/yuanbao/register.py+++ b/plugins/platforms/yuanbao/register.py@@ -92,6 +92,7 @@ def _parse_send_target(ref):def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""+ from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)ctx.register_platform(target_ref_syntax_fn=_parse_send_target,standalone_send=StandaloneSendPolicy(label="Yuanbao", media=True, text_direct=True),@@ -107,4 +108,6 @@ def register(ctx) -> None:standalone_sender_fn=_standalone_send, emoji="💎", allow_update_command=False,own_policy_env=("YUANBAO_DM_POLICY", "YUANBAO_GROUP_POLICY"),platform_hint=_PLATFORM_HINT,+ env_overrides=gateway_env.ENV_OVERRIDES,+ env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS,)diff --git a/tests/gateway/relay/test_explicit_disable.py b/tests/gateway/relay/test_explicit_disable.pyindex ce6fdd92ffd..9c28f574b73 100644--- a/tests/gateway/relay/test_explicit_disable.py+++ b/tests/gateway/relay/test_explicit_disable.py@@ -41,7 +41,7 @@ def profile(tmp_path, monkeypatch):monkeypatch.setenv("GATEWAY_RELAY_PLATFORMS", "slack")monkeypatch.setenv("GATEWAY_RELAY_IDP_TOKEN_URL", "https://identity.example/token")monkeypatch.setenv("SLACK_BOT_TOKEN", "native-test-token")- monkeypatch.setattr("hermes_cli.plugins.discover_plugins", lambda: None)+ # Discovery stays live: Slack's SLACK_BOT_TOKEN env row is declared by its bundled plugin entry.monkeypatch.setattr(GatewayStartupMixin, "_register_config_hooks", lambda *a, **k: None)platform_registry.unregister("relay")yield tmp_pathdiff --git a/tests/gateway/test_platform_env_overrides.py b/tests/gateway/test_platform_env_overrides.pynew file mode 100644index 00000000000..be992ddaef4--- /dev/null+++ b/tests/gateway/test_platform_env_overrides.py@@ -0,0 +1,42 @@+"""Invariants for the env -> GatewayConfig bridge that platform plugins declare on their+``PlatformEntry`` (``env_overrides`` / ``env_enable_credentials``, applied by+``gateway.config_env._apply_env_overrides``)."""++from gateway.config import Platform+from gateway.platform_registry import platform_registry++# Core-only platforms keep their env rows in gateway/config_env.py.+_CORE_ONLY = {"local", "api_server", "webhook", "msgraph_webhook", "relay"}+++def _entries():+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ return platform_registry.all_entries()+++def test_every_static_plugin_platform_declares_its_env_bridge():+ """A static ``Platform`` member served by a bundled plugin must carry its env rows: without them+ its env-only setup (``TELEGRAM_BOT_TOKEN`` in .env) would silently stop enabling the platform."""+ _entries()+ missing = []+ for member in Platform:+ if member.value in _CORE_ONLY:+ continue+ entry = platform_registry.get(member.value)+ if entry is None or not entry.env_overrides or not entry.env_enable_credentials:+ missing.append(member.value)+ assert missing == []+++def test_env_override_secrets_stay_in_terminal_secret_blocklist():+ """The terminal tool's adapter-secret blocklist is built at import time and cannot load adapters,+ so every secret a plugin's env rows read must already be declared where that policy looks."""+ from hermes_cli.config import PLATFORM_SECRET_ENV_SUFFIXES+ from hermes_cli.profile_channels import config_env_table_keys+ from tools.environments.local_env_policy import _ADAPTER_SECRET_ENV++ secrets = {name.upper() for name in config_env_table_keys(_entries())+ if name.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES)}+ assert "WEIXIN_TOKEN" in secrets # the rows were actually read+ assert sorted(secrets - _ADAPTER_SECRET_ENV) == []diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.pyindex 04b7f3eae9d..3dfb9988171 100644--- a/tools/environments/local_env_policy.py+++ b/tools/environments/local_env_policy.py@@ -110,8 +110,12 @@ def _build_adapter_secret_env() -> frozenset:CORE_DECLARED_ENV_NAMES, OPTIONAL_ENV_VARS, PLATFORM_SECRET_ENV_SUFFIXES, platform_manifest_secret_envs)from hermes_cli.profile_channels import config_env_table_keys# Read in code only, declared nowhere else: the Microsoft Graph app secret and webhook- # clientState, and the QQ bot's speech-to-text key.- names: set[str] = {"MSGRAPH_CLIENT_SECRET", "MSGRAPH_WEBHOOK_CLIENT_STATE", "QQ_STT_API_KEY"}+ # clientState, the QQ bot's speech-to-text key, and secrets only a plugin's ``env_overrides``+ # reads (Feishu webhook keys, Yuanbao's legacy app key). Those rows live on the adapter's+ # PlatformEntry, which this import-time policy cannot load without importing every adapter;+ # tests/gateway/test_platform_env_overrides.py pins that every such secret is listed here.+ names: set[str] = {"MSGRAPH_CLIENT_SECRET", "MSGRAPH_WEBHOOK_CLIENT_STATE", "QQ_STT_API_KEY",+ "FEISHU_ENCRYPT_KEY", "FEISHU_VERIFICATION_TOKEN", "YUANBAO_APP_KEY"}names.update(name.upper() for name, meta in OPTIONAL_ENV_VARS.items()if name in CORE_DECLARED_ENV_NAMESand meta.get("category") == "messaging" and meta.get("password"))