config.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. """Gateway configuration: connected platforms, home channels, session reset
  2. policies and delivery preferences, loaded from config.yaml / gateway.json / env.
  3. """
  4. import contextlib
  5. import logging
  6. import math
  7. import os
  8. import re
  9. from pathlib import Path
  10. from dataclasses import asdict, dataclass, field, fields, is_dataclass
  11. from typing import Dict, List, Optional, Any, Callable
  12. from enum import Enum
  13. from hermes_cli.config import get_hermes_home
  14. from agent.secret_scope import current_secret_scope, get_secret as _get_secret
  15. from gateway.shutdown_watchdog import (
  16. DEFAULT_LOOP_WATCHDOG_INTERVAL_S,
  17. DEFAULT_LOOP_WATCHDOG_MAX_STRIKES,
  18. DEFAULT_LOOP_WATCHDOG_TIMEOUT_S,
  19. )
  20. from utils import fast_safe_load, is_truthy_value
  21. logger = logging.getLogger(__name__)
  22. _TRUTHY_STRINGS = frozenset({"1", "true", "yes", "on"})
  23. _FALSY_STRINGS = frozenset({"0", "false", "no", "off"})
  24. def _bool_token(value: Any) -> Optional[bool]:
  25. """True/False for a recognized truthy/falsy token, else None."""
  26. token = str(value).strip().lower()
  27. return True if token in _TRUTHY_STRINGS else False if token in _FALSY_STRINGS else None
  28. def _coerce_bool(value: Any, default: bool = True) -> bool:
  29. """Coerce bool-ish config values, preserving a caller-provided default."""
  30. if value is None:
  31. return default
  32. if isinstance(value, str):
  33. parsed = _bool_token(value)
  34. return default if parsed is None else parsed
  35. return is_truthy_value(value, default=default)
  36. def _env_multiplex_profiles_override() -> bool | None:
  37. """GATEWAY_MULTIPLEX_PROFILES operator override: True/False for a recognized token.
  38. ``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml
  39. value (env > config > default). Blank is deliberately ``None``, not ``False``:
  40. a provisioned-but-unpopulated Fly secret arrives as ``""`` and must NOT shadow
  41. a config.yaml opt-in.
  42. """
  43. raw = os.getenv("GATEWAY_MULTIPLEX_PROFILES")
  44. if not (raw or "").strip():
  45. return None
  46. parsed = _bool_token(raw)
  47. if parsed is None:
  48. logger.warning(
  49. "Ignoring unrecognized GATEWAY_MULTIPLEX_PROFILES=%r "
  50. "(expected one of %s or %s); falling back to config.yaml.",
  51. raw, sorted(_TRUTHY_STRINGS), sorted(_FALSY_STRINGS),
  52. )
  53. return parsed
  54. # What the runner does when the last messaging adapter goes down (GatewayConfig.on_all_adapters_down).
  55. ON_ALL_ADAPTERS_DOWN_POLICIES = ("exit", "stay_alive")
  56. def _env_on_all_adapters_down_override() -> str | None:
  57. """GATEWAY_ON_ALL_ADAPTERS_DOWN operator override: 'exit'/'stay_alive' for a recognized token.
  58. ``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml value
  59. (env > config > default). Launchers without a supervising service manager (the desktop app
  60. spawns ``hermes serve`` directly) set ``stay_alive``: a failure exit there only severs the
  61. UI's websocket connections and drops in-flight assistant messages (#118080).
  62. """
  63. raw = os.getenv("GATEWAY_ON_ALL_ADAPTERS_DOWN")
  64. if not (raw or "").strip():
  65. return None
  66. token = raw.strip().lower()
  67. if token in ON_ALL_ADAPTERS_DOWN_POLICIES:
  68. return token
  69. logger.warning(
  70. "Ignoring unrecognized GATEWAY_ON_ALL_ADAPTERS_DOWN=%r "
  71. "(expected one of %s); falling back to config.yaml.",
  72. raw, list(ON_ALL_ADAPTERS_DOWN_POLICIES),
  73. )
  74. return None
  75. def _normalize_transport_token(value: Any) -> str:
  76. """Canonical streaming transport token. YAML 1.1 parses bare ``on``/``off`` as
  77. booleans (``mode: off`` → ``False`` → ``"false"`` would ENABLE streaming), so
  78. booleans map to ``"auto"``/``"off"``; anything else lower-cases, default ``"auto"``."""
  79. if value is None:
  80. return "auto"
  81. if isinstance(value, bool):
  82. return "auto" if value else "off"
  83. return str(value).strip().lower() or "auto"
  84. def _coerce_num(cast, value: Any, default):
  85. # OverflowError: ``int(float("inf"))`` — non-finite YAML must degrade, not abort loading.
  86. try:
  87. return default if value is None else cast(value)
  88. except (TypeError, ValueError, OverflowError):
  89. return default
  90. def _coerce_float(value: Any, default: float) -> float:
  91. return _coerce_num(float, value, default)
  92. def _coerce_int(value: Any, default: int) -> int:
  93. return _coerce_num(int, value, default)
  94. def _coerce_optional_positive_int(value: Any, key: str) -> Optional[int]:
  95. """``None``/0/negative disable; malformed values are ignored with a warning so a typo never blocks startup."""
  96. if value is None:
  97. return None
  98. try:
  99. if isinstance(value, bool) or (isinstance(value, float) and not value.is_integer()):
  100. raise ValueError(value)
  101. parsed = int(value.strip(), 10) if isinstance(value, str) else int(value)
  102. except (TypeError, ValueError):
  103. logger.warning("Ignoring invalid %s=%r (expected a positive integer; 0/null disables)", key, value)
  104. return None
  105. return parsed if parsed > 0 else None
  106. _SYSTEMD_WATCHDOG_MAX_SECONDS = 2_147_483_647
  107. def coerce_systemd_watchdog_seconds(
  108. value: Any, key: str = "gateway.systemd_watchdog_seconds"
  109. ) -> int:
  110. """Bounded positive watchdog interval, or zero when disabled/invalid. Shared by runtime
  111. and service generation so a value can never enable ``Type=notify`` without heartbeats."""
  112. if value is None:
  113. return 0
  114. parsed: Optional[int] = None
  115. if isinstance(value, int) and not isinstance(value, bool):
  116. parsed = value
  117. elif isinstance(value, str) and value.strip().isascii() and value.strip().isdecimal():
  118. with contextlib.suppress(TypeError, ValueError, OverflowError): # int() digit limit
  119. parsed = int(value.strip(), 10)
  120. if parsed is None:
  121. logger.warning("Ignoring invalid %s (expected a positive integer)", key)
  122. return 0
  123. if parsed and not 0 < parsed <= _SYSTEMD_WATCHDOG_MAX_SECONDS:
  124. logger.warning("Ignoring invalid %s (expected an integer from 1 to %d)", key, _SYSTEMD_WATCHDOG_MAX_SECONDS)
  125. return 0
  126. return parsed
  127. def _coerce_dict(value: Any) -> dict[str, Any]:
  128. return value if isinstance(value, dict) else {}
  129. # "pair" DMs a pairing code, "ignore" drops silently, "decline" sends one polite refusal then goes
  130. # silent toward that sender for gateway.pairing.DECLINE_DEDUPE_SECONDS (#88028).
  131. UNAUTHORIZED_DM_BEHAVIORS = {"pair", "ignore", "decline"}
  132. DEFAULT_UNAUTHORIZED_DM_DECLINE_MESSAGE = (
  133. "Hi! I'm a personal assistant and can only chat with my owner, so I can't help you directly. Sorry!"
  134. )
  135. def _normalize_choice(value: Any, choices: set, default: str) -> str:
  136. """Lower-cased *value* when it is one of *choices*, else *default*."""
  137. normalized = value.strip().lower() if isinstance(value, str) else None
  138. return normalized if normalized in choices else default
  139. def _dict_slot(container: dict, key: str) -> dict:
  140. """Get-or-create ``container[key]`` as a dict, replacing a non-dict value with ``{}``."""
  141. value = container.setdefault(key, {})
  142. if not isinstance(value, dict):
  143. value = {}
  144. container[key] = value
  145. return value
  146. def _getenv(name: str, default: Optional[str] = None) -> Optional[str]:
  147. """Env read through the active profile secret scope when present (multiplexed
  148. per-profile secrets must win); otherwise legacy ``os.getenv``."""
  149. if current_secret_scope() is not None:
  150. scope_val = _get_secret(name, None)
  151. return scope_val if scope_val is not None else default
  152. return os.environ.get(name, default)
  153. def _getenv_str(name: str, default: str = "") -> str:
  154. return val if (val := _getenv(name, default)) is not None else default
  155. _Platform__bundled_plugin_names: Optional[set] = None # cached outside the enum: never a member
  156. _Platform__bundled_plugin_aliases: Optional[dict] = None # manifest ``name:`` (lower) -> directory name
  157. def _bundled_platform_manifest_name(plugin_dir: Path) -> Optional[str]:
  158. """Lowercased ``name:`` from a bundled platform's plugin manifest (None when absent/unreadable)."""
  159. try:
  160. manifest_file = next(
  161. (plugin_dir / m for m in ("plugin.yaml", "plugin.yml") if (plugin_dir / m).exists()), None)
  162. if manifest_file is None:
  163. return None
  164. data = fast_safe_load(manifest_file.read_text(encoding="utf-8-sig")) or {}
  165. name = data.get("name") if isinstance(data, dict) else None
  166. return str(name).strip().lower() or None
  167. except Exception:
  168. return None
  169. class Platform(Enum):
  170. """Supported messaging platforms. Plugin platforms are dynamic members created on
  171. demand by ``_missing_`` and cached so ``Platform("irc") is Platform("irc")`` holds."""
  172. LOCAL = "local"
  173. TELEGRAM = "telegram"
  174. DISCORD = "discord"
  175. WHATSAPP = "whatsapp"
  176. WHATSAPP_CLOUD = "whatsapp_cloud"
  177. SLACK = "slack"
  178. SIGNAL = "signal"
  179. MATTERMOST = "mattermost"
  180. MATRIX = "matrix"
  181. EMAIL = "email"
  182. SMS = "sms"
  183. DINGTALK = "dingtalk"
  184. API_SERVER = "api_server"
  185. WEBHOOK = "webhook"
  186. MSGRAPH_WEBHOOK = "msgraph_webhook"
  187. FEISHU = "feishu"
  188. WECOM = "wecom"
  189. WECOM_CALLBACK = "wecom_callback"
  190. WEIXIN = "weixin"
  191. BLUEBUBBLES = "bluebubbles"
  192. QQBOT = "qqbot"
  193. YUANBAO = "yuanbao"
  194. RELAY = "relay" # generic relay adapter fronted by the connector (EXPERIMENTAL)
  195. @classmethod
  196. def _missing_(cls, value):
  197. """Accept unknown names only for bundled or runtime-registered plugin adapters (no enum pollution)."""
  198. if not isinstance(value, str) or not value.strip():
  199. return None
  200. value = value.strip().lower()
  201. if value in cls._value2member_map_:
  202. return cls._value2member_map_[value]
  203. global _Platform__bundled_plugin_names, _Platform__bundled_plugin_aliases
  204. if _Platform__bundled_plugin_names is None:
  205. _Platform__bundled_plugin_names, _Platform__bundled_plugin_aliases = cls._scan_bundled_plugin_platforms()
  206. registered = value in _Platform__bundled_plugin_names
  207. if not registered:
  208. alias = _Platform__bundled_plugin_aliases.get(value)
  209. if alias is not None:
  210. # A bundled platform whose plugin.yaml ``name:`` differs from its directory (e.g. dir
  211. # "a2a", name "a2a-platform") is configured under the manifest name — ``plugins
  212. # enable`` writes that key — so resolve it to the directory-name member that the
  213. # registry and every value-based consumer key on.
  214. return cls._value2member_map_.get(alias) or cls._add_pseudo_member(alias)
  215. with contextlib.suppress(Exception):
  216. from gateway.platform_registry import platform_registry
  217. registered = platform_registry.is_registered(value)
  218. return cls._add_pseudo_member(value) if registered else None
  219. @classmethod
  220. def _add_pseudo_member(cls, value: str) -> "Platform":
  221. pseudo = object.__new__(cls)
  222. pseudo._value_ = value
  223. pseudo._name_ = value.upper().replace("-", "_").replace(" ", "_")
  224. cls._value2member_map_[value] = pseudo
  225. cls._member_map_[pseudo._name_] = pseudo
  226. return pseudo
  227. @classmethod
  228. def _scan_bundled_plugin_platforms(cls) -> tuple[set, dict]:
  229. """Directory names of bundled platform plugins under ``plugins/platforms/``, plus a map of
  230. manifest ``name:`` keys that differ from their directory (alias -> directory name). Aliases
  231. never shadow a directory name, so the directory stays the canonical platform value."""
  232. try:
  233. platforms_dir = Path(__file__).parent.parent / "plugins" / "platforms"
  234. dirs = [
  235. child for child in (platforms_dir.iterdir() if platforms_dir.is_dir() else ())
  236. if child.is_dir() and (child / "__init__.py").exists()
  237. and ((child / "plugin.yaml").exists() or (child / "plugin.yml").exists())
  238. ]
  239. names = {child.name.lower() for child in dirs}
  240. aliases = {}
  241. for child in dirs:
  242. manifest_name = _bundled_platform_manifest_name(child)
  243. if manifest_name and manifest_name not in names and manifest_name not in aliases:
  244. aliases[manifest_name] = child.name.lower()
  245. return names, aliases
  246. except Exception:
  247. return set(), {}
  248. # Built-in values snapshotted before any dynamic _missing_ lookup.
  249. _BUILTIN_PLATFORM_VALUES = frozenset(m.value for m in Platform.__members__.values())
  250. # Platforms that bind a host TCP port. In a multiplexer only the default profile binds: a SECONDARY
  251. # profile's port-binder is built in shared-listener mode and served at /p/<profile>/<path> on the
  252. # default's listener (gateway/platforms/shared_ingress.py); api_server/webhook are mirrored there.
  253. PORT_BINDING_PLATFORM_VALUES = frozenset({
  254. "webhook", "api_server", "msgraph_webhook", "feishu", "wecom_callback",
  255. "bluebubbles", "sms", "whatsapp_cloud", "line", "teams",
  256. })
  257. # Platforms that only bind in one connection mode (Feishu's default websocket mode is outbound).
  258. PORT_BINDING_CONDITIONAL_MODES: dict[str, str] = {"feishu": "webhook"}
  259. # Port-binders whose /p/<profile>/ surface is a MIRROR served by the default's own adapter; a secondary
  260. # never gets an instance of these (api_server: /p/<profile>/v1/..., webhook: profile-bound routes).
  261. SHARED_LISTENER_MIRROR_PLATFORMS = frozenset({"api_server", "webhook"})
  262. # Path a client appends to ``<default listener>/p/<profile>`` to reach each mirror.
  263. SHARED_LISTENER_MIRROR_PATHS: dict[str, str] = {"api_server": "/v1", "webhook": "/webhooks/<route>"}
  264. def platform_binds_port(platform_value: str, extra: Optional[dict] = None) -> bool:
  265. """True when *platform_value* actually binds a port for *extra* config."""
  266. if platform_value not in PORT_BINDING_PLATFORM_VALUES:
  267. return False
  268. expected_mode = PORT_BINDING_CONDITIONAL_MODES.get(platform_value)
  269. return expected_mode is None or str((extra or {}).get("connection_mode", "websocket")).strip().lower() == expected_mode
  270. _DISCORD_CHANNEL_LINK_RE = re.compile(
  271. r"https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/channels/(?:[0-9]+|@me)/([0-9]+)/?")
  272. def discord_channel_id_from_link(value: str) -> Optional[str]:
  273. """Channel id from a pasted Discord channel link (``https://discord.com/channels/<guild>/<channel>``),
  274. else None. Message links (a third path segment) and anything that is not a channel link are
  275. left alone so callers keep their own error path."""
  276. match = _DISCORD_CHANNEL_LINK_RE.fullmatch(value)
  277. return match.group(1) if match else None
  278. @dataclass
  279. class HomeChannel:
  280. """Default destination for a platform (``deliver="telegram"`` without a chat ID);
  281. ``thread_id`` routes the bare target to the topic where /sethome was run."""
  282. platform: Platform
  283. chat_id: str
  284. name: str
  285. thread_id: Optional[str] = None
  286. # Authenticated logical-target provenance (relay egress re-attaches; connector stays the authz boundary).
  287. user_id: Optional[str] = None
  288. scope_id: Optional[str] = None
  289. def __post_init__(self) -> None:
  290. # Copy Link is next to Copy Channel ID in Discord. Normalize at the
  291. # shared home boundary so env, YAML and plugin-seeded homes agree.
  292. if self.platform == Platform.DISCORD and isinstance(self.chat_id, str):
  293. self.chat_id = discord_channel_id_from_link(self.chat_id.strip()) or self.chat_id
  294. def to_dict(self) -> dict[str, Any]:
  295. optional = {k: v for k in ("thread_id", "user_id", "scope_id") if (v := getattr(self, k))}
  296. return {"platform": self.platform.value, "chat_id": self.chat_id, "name": self.name, **optional}
  297. @classmethod
  298. def from_dict(cls, data: dict[str, Any]) -> "HomeChannel":
  299. optional = {k: str(data[k]) if data.get(k) else None for k in ("thread_id", "user_id", "scope_id")}
  300. return cls(platform=Platform(data["platform"]), chat_id=str(data["chat_id"]), name=data.get("name", "Home"), **optional)
  301. def persist_home_channel(home: HomeChannel, *, enabled_if_new: bool = False) -> None:
  302. """Persist a logical home without falsely enabling a Relay-fronted adapter."""
  303. from hermes_cli.config import load_config, save_config
  304. config = load_config()
  305. platform_config = _dict_slot(_dict_slot(config, "platforms"), home.platform.value)
  306. if enabled_if_new:
  307. platform_config.setdefault("enabled", True)
  308. platform_config["home_channel"] = home.to_dict()
  309. save_config(config)
  310. @dataclass
  311. class ChannelOverride:
  312. """Per-channel reply policy/model/provider/system_prompt override (``platforms.<name>.channel_overrides[channel_id]``)."""
  313. model: Optional[str] = None
  314. provider: Optional[str] = None
  315. system_prompt: Optional[str] = None
  316. allow_silence: Optional[bool] = None
  317. def to_dict(self) -> dict[str, Any]:
  318. return {k: v for k, v in asdict(self).items() if v is not None}
  319. @classmethod
  320. def from_dict(cls, data: dict[str, Any]) -> "ChannelOverride":
  321. return cls(**{f.name: data.get(f.name) for f in fields(cls)}) if data else cls()
  322. # Platforms whose primary credential is ``PlatformConfig.token`` → its env var (empty-token
  323. # warnings; multiplex primary-startup gate in ``gateway.run``). Platforms absent here
  324. # authenticate another way and must never be skipped for a missing token.
  325. # Platforms absent from this map authenticate some other way (session files, port-bound webhooks,
  326. # api_key-only) and must never be skipped for a missing token. See #64674.
  327. PLATFORM_TOKEN_ENV_NAMES: dict[Platform, str] = {
  328. Platform.TELEGRAM: "TELEGRAM_BOT_TOKEN",
  329. Platform.DISCORD: "DISCORD_BOT_TOKEN",
  330. Platform.SLACK: "SLACK_BOT_TOKEN",
  331. Platform.MATTERMOST: "MATTERMOST_TOKEN",
  332. Platform.MATRIX: "MATRIX_ACCESS_TOKEN",
  333. Platform.WEIXIN: "WEIXIN_TOKEN",
  334. }
  335. @dataclass
  336. class PlatformConfig:
  337. """Configuration for a single messaging platform."""
  338. enabled: bool = False
  339. token: Optional[str] = None
  340. api_key: Optional[str] = None # API key if different from token
  341. home_channel: Optional[HomeChannel] = None
  342. reply_to_mode: str = "first" # "off" never threads, "first" only the first chunk, "all" every chunk
  343. gateway_restart_notification: bool = True # "♻️ Gateway online/restarted" pings; noise on end-user platforms
  344. typing_indicator: bool = True # drives _keep_typing; False where unwanted (Slack setStatus blocks compose)
  345. # Working-state text for text-rendering indicators (Slack status, Google Chat marker); None = platform default.
  346. typing_status_text: Optional[str] = None
  347. channel_overrides: dict[str, ChannelOverride] = field(default_factory=dict)
  348. extra: dict[str, Any] = field(default_factory=dict) # Platform-specific settings
  349. # Runtime-only, never serialized: set when the GATEWAY_RELAY_URL relay-exclusive rule
  350. # (config_env._relay) switched an enabled platform off, so surfaces can say why (#141175).
  351. disabled_by_relay: bool = False
  352. def to_dict(self) -> dict[str, Any]:
  353. result = {
  354. "enabled": self.enabled, "extra": self.extra, "reply_to_mode": self.reply_to_mode,
  355. "gateway_restart_notification": self.gateway_restart_notification,
  356. "typing_indicator": self.typing_indicator,
  357. **({"typing_status_text": self.typing_status_text} if self.typing_status_text is not None else {}),
  358. **{k: v for k in ("token", "api_key") if (v := getattr(self, k))},
  359. }
  360. if self.home_channel:
  361. result["home_channel"] = self.home_channel.to_dict()
  362. if self.channel_overrides:
  363. result["channel_overrides"] = {cid: ov.to_dict() for cid, ov in self.channel_overrides.items()}
  364. return result
  365. # Keys consumed by typed fields; everything else at the top of a platform block is adapter
  366. # config and belongs in ``extra`` (see from_dict).
  367. _TYPED_KEYS = frozenset({
  368. "enabled", "token", "api_key", "home_channel", "reply_to_mode", "channel_overrides", "extra",
  369. "gateway_restart_notification", "typing_indicator", "typing_status_text",
  370. })
  371. @classmethod
  372. def from_dict(cls, data: dict[str, Any]) -> "PlatformConfig":
  373. data = _coerce_dict(data)
  374. home = data.get("home_channel")
  375. # Adapters read their settings from ``extra`` (``config.extra.get("port")``), but users
  376. # write them where the docs and ``hermes config set platforms.webhook.port`` put them:
  377. # directly under the platform block. Promote every non-typed top-level key so neither
  378. # spelling is silently dropped (#10206); an explicit ``extra:`` value wins on a clash.
  379. extra = {**{k: v for k, v in data.items() if k not in cls._TYPED_KEYS}, **_coerce_dict(data.get("extra", {}))}
  380. def toplevel_or_extra(key: str) -> Any:
  381. value = data.get(key)
  382. return extra.get(key) if value is None else value
  383. raw_overrides = data.get("channel_overrides") or {}
  384. channel_overrides = {
  385. str(cid): ChannelOverride.from_dict(ov_data)
  386. for cid, ov_data in raw_overrides.items()
  387. if isinstance(ov_data, dict)
  388. } if isinstance(raw_overrides, dict) else {}
  389. return cls(
  390. enabled=_coerce_bool(data.get("enabled"), False),
  391. token=data.get("token"),
  392. api_key=data.get("api_key"),
  393. home_channel=HomeChannel.from_dict(home) if isinstance(home, dict) else None,
  394. reply_to_mode=data.get("reply_to_mode", "first"),
  395. gateway_restart_notification=_coerce_bool(toplevel_or_extra("gateway_restart_notification"), True),
  396. typing_indicator=_coerce_bool(toplevel_or_extra("typing_indicator"), True),
  397. typing_status_text=toplevel_or_extra("typing_status_text"), # string passthrough, no coercion
  398. channel_overrides=channel_overrides,
  399. extra=extra,
  400. )
  401. # Shared by StreamingConfig and StreamConsumerConfig. Tuned for Telegram's ~1 edit/s
  402. # flood envelope; the small buffer threshold makes short DM replies feel instant.
  403. DEFAULT_STREAMING_EDIT_INTERVAL: float = 0.8
  404. DEFAULT_STREAMING_BUFFER_THRESHOLD: int = 24
  405. DEFAULT_STREAMING_CURSOR: str = " ▉"
  406. @dataclass
  407. class StreamingConfig:
  408. """Real-time token streaming to messaging platforms."""
  409. enabled: bool = False
  410. # "auto" prefers native drafts (Telegram sendMessageDraft) with edit fallback (adapters without
  411. # draft support use the edit path unchanged); "draft" / "edit" force one; "off" disables.
  412. transport: str = "auto"
  413. edit_interval: float = DEFAULT_STREAMING_EDIT_INTERVAL
  414. buffer_threshold: int = DEFAULT_STREAMING_BUFFER_THRESHOLD
  415. cursor: str = DEFAULT_STREAMING_CURSOR
  416. # >0: final edit becomes a fresh message once the preview was visible this long (Telegram only; 0 = off).
  417. # Ported from openclaw/openclaw#72038. When >0, the final edit for a long-running streamed response is
  418. # delivered as a fresh message if the original preview has been visible for at least this many seconds,
  419. # so the platform's visible timestamp reflects completion time instead of the preview creation time.
  420. # Currently applied to Telegram only (other platforms ignore the setting). Default 0 disables the
  421. # fresh-message replacement path; set >0 to opt in.
  422. fresh_final_after_seconds: float = 0.0
  423. @property
  424. def globally_enabled(self) -> bool:
  425. """The ``streaming.enabled`` master switch (``transport: off`` also disables)."""
  426. return bool(self.enabled) and self.transport != "off"
  427. def enabled_for(self, platform_override: Any) -> bool:
  428. """Effective streaming for one platform.
  429. ``platform_override`` is ``display.platforms.<plat>.streaming`` (``None`` = follow global).
  430. A per-platform value can only narrow the global switch, never enable streaming on its own.
  431. """
  432. return self.globally_enabled and (platform_override is None or bool(platform_override))
  433. def to_dict(self) -> dict[str, Any]:
  434. return asdict(self)
  435. @classmethod
  436. def from_dict(cls, data: dict[str, Any]) -> "StreamingConfig":
  437. if not isinstance(data, dict) or not data:
  438. return cls()
  439. # ``mode`` is a transport alias that ALSO implies ``enabled`` (``mode: off`` disables;
  440. # explicit ``enabled`` wins). A bare ``transport`` does NOT imply enabled:
  441. # ``streaming.enabled`` is the documented master switch.
  442. raw_transport = data.get("transport")
  443. raw_mode = data.get("mode")
  444. if "enabled" in data:
  445. enabled = _coerce_bool(data.get("enabled"), False)
  446. else:
  447. enabled = raw_mode is not None and _normalize_transport_token(raw_mode) != "off"
  448. return cls(
  449. enabled=enabled,
  450. transport=_normalize_transport_token(raw_transport if raw_transport is not None else raw_mode),
  451. edit_interval=_coerce_float(data.get("edit_interval"), DEFAULT_STREAMING_EDIT_INTERVAL),
  452. buffer_threshold=_coerce_int(data.get("buffer_threshold"), DEFAULT_STREAMING_BUFFER_THRESHOLD),
  453. cursor=data.get("cursor", DEFAULT_STREAMING_CURSOR),
  454. fresh_final_after_seconds=_coerce_float(data.get("fresh_final_after_seconds"), 0.0),
  455. )
  456. def _has_usable_api_server_key(key: object) -> bool:
  457. """True when API_SERVER_KEY is strong enough for the adapter to start (mirrors the
  458. ``has_usable_secret(min_length=16)`` guard in ``gateway/platforms/api_server.py``)."""
  459. if not key:
  460. return False
  461. try:
  462. from hermes_cli.auth import has_usable_secret
  463. return has_usable_secret(key, min_length=16)
  464. except ImportError:
  465. return len(str(key).strip()) >= 16
  466. # Core-only "sufficiently configured?" checks (no plugin entry). Plugin platforms declare theirs as
  467. # ``PlatformEntry.config_connected_fn`` (or rely on the generic ``token or api_key`` check).
  468. _PLATFORM_CONNECTED_CHECKERS: dict[Platform, Callable[[PlatformConfig], bool]] = {
  469. Platform.API_SERVER: lambda cfg: _has_usable_api_server_key(cfg.extra.get("key") if cfg else None),
  470. Platform.WEBHOOK: lambda cfg: True,
  471. Platform.MSGRAPH_WEBHOOK: lambda cfg: bool(str(cfg.extra.get("client_state") or "").strip()),
  472. # Relay dials OUT: "connected" once an endpoint URL is configured. EXPERIMENTAL.
  473. Platform.RELAY: lambda cfg: bool(cfg.extra.get("relay_url") or cfg.extra.get("url")),
  474. }
  475. def _discovered_registry_entry(platform: Platform):
  476. """Registry entry for *platform* after (idempotent) plugin discovery, so a directly-constructed
  477. config sees plugin platforms; None when absent or the registry is not initialised yet (early import).
  478. Enablement gate (#31116): a plugin's ``is_connected`` ("has the user actually configured
  479. credentials for this?") is consulted before treating it as connected; ``check_fn`` alone — a
  480. passive "is the SDK importable?" probe — must never make a platform the user never opted into
  481. look connected (``_platform_status`` was fixed for the same bug class in commit 7849a3d73)."""
  482. with contextlib.suppress(Exception):
  483. from hermes_cli.plugins import discover_plugins
  484. discover_plugins()
  485. with contextlib.suppress(Exception): # registry not initialised yet during early import
  486. from gateway.platform_registry import platform_registry
  487. return platform_registry.get(platform.value)
  488. return None
  489. # Top-level bool-ish keys read verbatim (no nested ``gateway.`` fallback) with their defaults.
  490. _TOPLEVEL_BOOL_DEFAULTS = {
  491. "write_sessions_json": True, "always_log_local": True, "filter_silence_narration": True,
  492. "group_sessions_per_user": True, "thread_sessions_per_user": False,
  493. }
  494. @dataclass
  495. class GatewayConfig:
  496. """Main gateway configuration: platform connections, session policies, delivery settings."""
  497. platforms: dict[Platform, PlatformConfig] = field(default_factory=dict)
  498. reset_triggers: list[str] = field(default_factory=lambda: ["/new", "/reset"])
  499. quick_commands: dict[str, Any] = field(default_factory=dict) # slash commands that bypass the agent loop
  500. sessions_dir: Path = field(default_factory=lambda: get_hermes_home() / "sessions")
  501. # Legacy sessions.json mirror of the routing index (primary: state.db) for external tooling / downgrades.
  502. # The primary copy lives in state.db (gateway_routing table, #9006). Default True for backward
  503. # compatibility with external tooling and downgrade safety; set gateway.write_sessions_json: false in
  504. # config.yaml to stop producing the file.
  505. write_sessions_json: bool = True
  506. always_log_local: bool = True # Always save cron outputs to local files
  507. # Drop outbound "silence narration" (*(silent)*, 🔇, a bare ".") that ping-pongs in bot-to-bot
  508. # channels; a substrate guard that survives prompt drift.
  509. filter_silence_narration: bool = True
  510. stt_enabled: bool = True # Auto-transcribe inbound voice messages
  511. stt_echo_transcripts: bool = True # Echo raw STT transcripts back to the user
  512. group_sessions_per_user: bool = True # Isolate group sessions per participant when user IDs exist
  513. thread_sessions_per_user: bool = False # False = threads shared across participants
  514. max_concurrent_sessions: Optional[int] = None # Positive int caps simultaneous active sessions
  515. # The default profile's gateway serves every profile on the host (profiles stamped into session
  516. # keys, per-profile adapters/credentials). On by default (DEFAULT_CONFIG), but UNSET here is
  517. # ``None``: a request the gateway settles at boot, not a verdict. ``hermes_cli.gateway_multiplex_mode
  518. # .resolve_multiplex_mode`` runs the migration preflight (default profile, >= 2 profiles, no
  519. # secondary running its own gateway, no blocker, migratable host) and only then writes True/False.
  520. # An explicit value (config.yaml, GATEWAY_MULTIPLEX_PROFILES, a constructor argument) is honoured
  521. # verbatim. Every reader tests truthiness, so an unresolved ``None`` never multiplexes by accident.
  522. multiplex_profiles: Optional[bool] = None
  523. # Public HTTPS endpoint for scoped RoomLink calls (an API key alone must never advertise a
  524. # route); HERMES_ROOM_LINK_URL overrides.
  525. room_link_url: Optional[str] = None
  526. systemd_watchdog_seconds: int = 0 # opt-in; zero keeps Type=simple and disables sd_notify
  527. # In-process loop liveness watchdog: after consecutive missed probes it dumps all-thread stacks
  528. # and hard-exits with the service-restart code. The knobs tolerate transient self-recovering
  529. # stalls (adapter reconnect doing sync socket I/O) so a short block does not cause restart churn.
  530. # max_strikes ~= 90-120s sustained block; the heartbeat-fsync false positive is fixed at the root
  531. # (off-loop write + two-witness probe), so raising it would only delay recovery.
  532. # On by default; set gateway.loop_watchdog: false in config.yaml to disable. Telegram/Discord reconnect
  533. # doing synchronous socket I/O during a network blip — so a short block does not force exit code 75 and
  534. # trigger a restart churn that stalls cron dispatch (recurring fleet incidents on 2026-08-17, kanban
  535. # t_0f76430f/t_70483f23). A genuine wedge (event loop frozen for the full tolerance window) still
  536. # escalates to a supervised restart. See #69089.
  537. loop_watchdog: bool = True
  538. loop_watchdog_probe_interval_s: float = DEFAULT_LOOP_WATCHDOG_INTERVAL_S
  539. loop_watchdog_probe_timeout_s: float = DEFAULT_LOOP_WATCHDOG_TIMEOUT_S
  540. loop_watchdog_max_strikes: int = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES
  541. # What happens when the LAST messaging adapter goes down. ``exit`` (default) shuts the gateway
  542. # down with the failure verdict so a supervising service manager (systemd/launchd) restarts it;
  543. # ``stay_alive`` keeps the process running and leaves recovery to the reconnect watcher — for
  544. # launchers with no supervisor (the desktop app spawns ``hermes serve`` directly), where a
  545. # failure exit only severs the UI's websockets and drops in-flight assistant messages (#118080).
  546. # Retryable failures are recoverable in both modes; non-retryable adapter loss always exits.
  547. on_all_adapters_down: str = "exit" # "exit" | "stay_alive"; GATEWAY_ON_ALL_ADAPTERS_DOWN overrides
  548. unauthorized_dm_behavior: str = "pair" # UNAUTHORIZED_DM_BEHAVIORS
  549. unauthorized_dm_decline_message: str = "" # "decline" reply text; empty → DEFAULT_UNAUTHORIZED_DM_DECLINE_MESSAGE
  550. streaming: StreamingConfig = field(default_factory=StreamingConfig)
  551. # Prune SessionEntry records older than this (a resumed chat gets a fresh session). 0 = off.
  552. session_store_max_age_days: int = 90
  553. profile_routes: list = field(default_factory=list) # gateway/profile_routing.py
  554. # Scalar fields serialized verbatim by ``to_dict`` (in output order).
  555. _SCALAR_DICT_FIELDS = (
  556. "write_sessions_json", "always_log_local", "filter_silence_narration", "stt_enabled",
  557. "stt_echo_transcripts", "group_sessions_per_user", "thread_sessions_per_user",
  558. "max_concurrent_sessions", "multiplex_profiles",
  559. "on_all_adapters_down",
  560. "room_link_url", "systemd_watchdog_seconds", "loop_watchdog",
  561. "loop_watchdog_probe_interval_s", "loop_watchdog_probe_timeout_s",
  562. "loop_watchdog_max_strikes", "unauthorized_dm_behavior", "unauthorized_dm_decline_message",
  563. )
  564. def __post_init__(self) -> None:
  565. self.systemd_watchdog_seconds = coerce_systemd_watchdog_seconds(self.systemd_watchdog_seconds)
  566. def get_connected_platforms(self) -> list[Platform]:
  567. """Enabled + configured platforms, sorted by value so the rendered "Connected
  568. Platforms" prompt block is byte-stable (a reorder busts the prompt cache)."""
  569. connected = [p for p, c in self.platforms.items() if c.enabled and self._is_platform_connected(p, c)]
  570. return sorted(connected, key=lambda p: str(p.value))
  571. def _is_platform_connected(self, platform: Platform, config: PlatformConfig) -> bool:
  572. checker = _PLATFORM_CONNECTED_CHECKERS.get(platform)
  573. if checker is not None:
  574. return bool(config.token or config.api_key) or checker(config)
  575. entry = _discovered_registry_entry(platform)
  576. # ``config_connected_fn`` owns the token shortcut (Weixin needs token AND account_id).
  577. if entry is not None and entry.config_connected_fn is not None:
  578. return entry.config_connected_fn(config)
  579. if config.token or config.api_key:
  580. return True
  581. if entry is None:
  582. return False
  583. check = entry.is_connected if entry.is_connected is not None else entry.validate_config
  584. try:
  585. return True if check is None else check(config)
  586. except Exception:
  587. return False
  588. def get_home_channel(self, platform: Platform) -> Optional[HomeChannel]:
  589. return self.platforms[platform].home_channel if self.platforms.get(platform) else None
  590. def to_dict(self) -> dict[str, Any]:
  591. return {
  592. "platforms": {p.value: c.to_dict() for p, c in self.platforms.items()},
  593. "reset_triggers": self.reset_triggers,
  594. "quick_commands": self.quick_commands,
  595. "sessions_dir": str(self.sessions_dir),
  596. **{name: getattr(self, name) for name in self._SCALAR_DICT_FIELDS},
  597. "streaming": self.streaming.to_dict(),
  598. "session_store_max_age_days": self.session_store_max_age_days,
  599. "profile_routes": [
  600. {k: v for k, v in asdict(r).items() if k != "user_id" or v is not None}
  601. if is_dataclass(r) and not isinstance(r, type) else r
  602. for r in self.profile_routes
  603. ],
  604. }
  605. @classmethod
  606. def from_dict(cls, data: dict[str, Any]) -> "GatewayConfig":
  607. data = _coerce_dict(data)
  608. nested_gateway = _coerce_dict(data.get("gateway"))
  609. def pick(key: str) -> Any:
  610. """Top-level key wins by presence; else the nested ``gateway.<key>`` form."""
  611. return data[key] if key in data else nested_gateway.get(key)
  612. def key_label(key: str) -> str:
  613. """Warning key prefix: "gateway." when the nested form was the one consulted."""
  614. return key if key in data else f"gateway.{key}"
  615. def by_platform(key: str, parse, *, dicts_only: bool = False) -> dict:
  616. """``{Platform(name): parse(block)}`` for a platform-keyed mapping; unknown platforms skipped."""
  617. out = {}
  618. for platform_name, block in _coerce_dict(data.get(key, {})).items():
  619. if dicts_only and not isinstance(block, dict):
  620. continue
  621. try:
  622. out[Platform(platform_name)] = parse(block)
  623. except ValueError:
  624. pass
  625. return out
  626. def stt_setting(flat_key: str, nested_key: str) -> Any:
  627. value = data.get(flat_key)
  628. return _coerce_dict(data.get("stt")).get(nested_key) if value is None else value
  629. def bounded_float(key: str, default: float, lo: float, hi: float) -> float:
  630. # Out-of-range / non-finite watchdog knobs fall back to the shipped defaults.
  631. value = _coerce_float(pick(key), default)
  632. return value if math.isfinite(value) and lo <= value <= hi else default
  633. room_link_url = data.get("room_link_url")
  634. max_strikes = _coerce_int(pick("loop_watchdog_max_strikes"), DEFAULT_LOOP_WATCHDOG_MAX_STRIKES)
  635. if not 1 <= max_strikes <= 1000:
  636. max_strikes = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES
  637. systemd_watchdog_seconds = coerce_systemd_watchdog_seconds(
  638. pick("systemd_watchdog_seconds"), key_label("systemd_watchdog_seconds")
  639. )
  640. # env > config.yaml > unset: a recognized GATEWAY_MULTIPLEX_PROFILES wins (hosted deployments
  641. # stamp it on the container); blank/unrecognized falls through to the top-level VALUE when not
  642. # None, else ``gateway.multiplex_profiles``. Nothing set stays ``None`` so the boot-time guard
  643. # (``resolve_multiplex_mode``) can tell "the operator chose" from "the default applies".
  644. multiplex_profiles = data.get("multiplex_profiles")
  645. if multiplex_profiles is None:
  646. multiplex_profiles = nested_gateway.get("multiplex_profiles")
  647. env_multiplex = _env_multiplex_profiles_override()
  648. if env_multiplex is not None:
  649. multiplex_profiles = env_multiplex
  650. # env > config.yaml > default: GATEWAY_ON_ALL_ADAPTERS_DOWN wins for launchers that know
  651. # whether a service manager is watching (the desktop launcher sets stay_alive); anything
  652. # unrecognized (env or yaml) falls back to "exit", the historical behavior (#118080).
  653. on_all_adapters_down = _env_on_all_adapters_down_override()
  654. if on_all_adapters_down is None:
  655. on_all_adapters_down = _normalize_choice(
  656. pick("on_all_adapters_down"), ON_ALL_ADAPTERS_DOWN_POLICIES, "exit"
  657. )
  658. max_concurrent_sessions = _coerce_optional_positive_int(
  659. pick("max_concurrent_sessions"), key_label("max_concurrent_sessions")
  660. )
  661. try:
  662. session_store_max_age_days = max(int(data.get("session_store_max_age_days", 90)), 0)
  663. except (TypeError, ValueError):
  664. session_store_max_age_days = 90
  665. from gateway.profile_routing import parse_profile_routes
  666. return cls(
  667. platforms=by_platform("platforms", PlatformConfig.from_dict, dicts_only=True),
  668. reset_triggers=data.get("reset_triggers", ["/new", "/reset"]),
  669. quick_commands=_coerce_dict(data.get("quick_commands", {})),
  670. sessions_dir=Path(data["sessions_dir"]) if "sessions_dir" in data else get_hermes_home() / "sessions",
  671. **{name: _coerce_bool(data.get(name), default) for name, default in _TOPLEVEL_BOOL_DEFAULTS.items()},
  672. stt_enabled=_coerce_bool(stt_setting("stt_enabled", "enabled"), True),
  673. stt_echo_transcripts=_coerce_bool(stt_setting("stt_echo_transcripts", "echo_transcripts"), True),
  674. multiplex_profiles=None if multiplex_profiles is None else _coerce_bool(multiplex_profiles, True),
  675. room_link_url=room_link_url if isinstance(room_link_url, str) else None,
  676. systemd_watchdog_seconds=systemd_watchdog_seconds,
  677. loop_watchdog=_coerce_bool(pick("loop_watchdog"), True),
  678. loop_watchdog_probe_interval_s=bounded_float("loop_watchdog_probe_interval_s", DEFAULT_LOOP_WATCHDOG_INTERVAL_S, 1.0, 3600.0),
  679. loop_watchdog_probe_timeout_s=bounded_float("loop_watchdog_probe_timeout_s", DEFAULT_LOOP_WATCHDOG_TIMEOUT_S, 1.0, 600.0),
  680. loop_watchdog_max_strikes=max_strikes,
  681. on_all_adapters_down=on_all_adapters_down,
  682. max_concurrent_sessions=max_concurrent_sessions,
  683. unauthorized_dm_behavior=_normalize_choice(data.get("unauthorized_dm_behavior"), UNAUTHORIZED_DM_BEHAVIORS, "pair"),
  684. unauthorized_dm_decline_message=str(data.get("unauthorized_dm_decline_message") or "").strip(),
  685. streaming=StreamingConfig.from_dict(data.get("streaming", {})),
  686. session_store_max_age_days=session_store_max_age_days,
  687. profile_routes=parse_profile_routes(data.get("profile_routes") or []),
  688. )
  689. def _extra_choice(self, platform: Optional[Platform], key: str, choices: set, default: str) -> Optional[str]:
  690. """Normalized ``platforms[platform].extra[key]`` when the key is present, else None."""
  691. platform_cfg = self.platforms.get(platform) if platform else None
  692. if platform_cfg and key in platform_cfg.extra:
  693. return _normalize_choice(platform_cfg.extra.get(key), choices, default)
  694. return None
  695. def get_unauthorized_dm_behavior(self, platform: Optional[Platform] = None) -> str:
  696. """Effective unauthorized-DM behavior. Email is inbox-shaped so it defaults to ``"ignore"``
  697. unless its own ``unauthorized_dm_behavior`` opts in (a global default does not)."""
  698. choice = self._extra_choice(platform, "unauthorized_dm_behavior", UNAUTHORIZED_DM_BEHAVIORS, self.unauthorized_dm_behavior)
  699. if choice is not None:
  700. return choice
  701. return "ignore" if platform == Platform.EMAIL else self.unauthorized_dm_behavior
  702. def get_notice_delivery(self, platform: Optional[Platform] = None) -> str:
  703. """Effective notice-delivery mode ("public"/"private") for a platform."""
  704. choice = self._extra_choice(platform, "notice_delivery", {"public", "private"}, "public")
  705. return "public" if choice is None else choice
  706. def load_gateway_config() -> GatewayConfig:
  707. """Load gateway configuration. Priority: env > ~/.hermes/config.yaml > legacy gateway.json > defaults."""
  708. from gateway import config_loader
  709. _home = get_hermes_home()
  710. gw_data = config_loader.load_legacy_gateway_json(_home)
  711. try:
  712. config_loader.load_yaml_layer(_home, gw_data)
  713. except Exception as e:
  714. logger.warning(
  715. # DingTalk settings → env vars: migrated to the dingtalk plugin's apply_yaml_config_fn hook
  716. # (plugins/platforms/dingtalk/adapter.py). #41112 / #3823.
  717. # Mattermost config bridge moved into plugins/platforms/mattermost/
  718. # adapter.py::_apply_yaml_config — see #25443 (apply_yaml_config_fn).
  719. # Matrix settings → env vars: migrated to the matrix plugin's apply_yaml_config_fn hook
  720. # (plugins/platforms/matrix/adapter.py). #41112 / #3823.
  721. # Feishu settings → env vars: migrated to the feishu plugin's apply_yaml_config_fn hook
  722. # (plugins/platforms/feishu/adapter.py). #41112 / #3823.
  723. "Failed to process config.yaml — falling back to .env / gateway.json values. "
  724. "Check %s for syntax errors. Error: %s",
  725. _home / "config.yaml", e,
  726. )
  727. config = GatewayConfig.from_dict(gw_data)
  728. _apply_env_overrides(config)
  729. _validate_gateway_config(config)
  730. return config
  731. def _validate_gateway_config(config: GatewayConfig) -> None:
  732. """Validate and sanitize a loaded GatewayConfig in place (after all sources are merged)."""
  733. try:
  734. # Reject known-weak placeholder tokens. Ported from openclaw/openclaw#64586: users who copy
  735. # .env.example without changing placeholder values get a clear startup error instead of a confusing
  736. # "auth failed" from the platform API.
  737. from hermes_cli.auth import has_usable_secret
  738. except ImportError:
  739. has_usable_secret = None
  740. token_platforms = [
  741. (p, c, PLATFORM_TOKEN_ENV_NAMES[p]) for p, c in config.platforms.items()
  742. if c.enabled and p in PLATFORM_TOKEN_ENV_NAMES and c.token is not None
  743. ]
  744. for platform, pconfig, env_name in token_platforms: # an empty token won't connect; say so
  745. if not pconfig.token.strip():
  746. logger.warning("%s is enabled but %s is empty. The adapter will likely fail to connect.", platform.value, env_name)
  747. if has_usable_secret is None:
  748. return
  749. for platform, pconfig, env_name in token_platforms: # reject placeholder tokens (copied .env.example)
  750. token = pconfig.token
  751. if token.strip() and not has_usable_secret(token, min_length=4):
  752. logger.error(
  753. "%s is enabled but %s is set to a placeholder value ('%s'). "
  754. "Set a real bot token before starting the gateway. "
  755. "The adapter will NOT be started.",
  756. platform.value, env_name, token.strip()[:6] + "...",
  757. )
  758. pconfig.enabled = False
  759. def _apply_env_overrides(config: GatewayConfig) -> None:
  760. """Apply environment variable overrides to config (see ``gateway.config_env``)."""
  761. from gateway.config_env import _apply_env_overrides as _impl
  762. _impl(config)