platform_activation.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Which deferred platform adapters a gateway config/env pass must import.
  2. Bundled platform plugins register lazily (``PlatformRegistry.register_deferred``); importing all
  3. ~20 of them costs every cold gateway start about half a second (discord, telegram, google_chat
  4. SDKs, telegram's i18n catalog) although a fresh profile configures none. The config passes in
  5. ``gateway.config_loader`` / ``gateway.config_env`` only need a platform's hooks
  6. (``apply_yaml_config_fn``, ``env_enablement_fn``, ``is_connected``) when the profile could be
  7. configuring that platform, so they materialize only names with *activation evidence*:
  8. * a config block for it (top-level ``<name>:``, ``platforms.<name>``, ``gateway.platforms.<name>``,
  9. ``gateway.<name>``, or a legacy ``gateway.json`` row) — including a sibling block such as
  10. ``wecom_callback`` (registered by the ``wecom`` plugin);
  11. * an env var (process env, the profile ``.env``, or the active secret scope) under the platform's
  12. prefix (``TELEGRAM_*``, ``GOOGLE_CHAT_*``) or named in its manifest ``requires_env``
  13. (``TWILIO_*`` for sms);
  14. * a credential-pool record for it in the profile ``auth.json`` (Photon stores project creds there).
  15. The rule over-approximates on purpose: a false positive costs one import, a false negative would
  16. leave a configured platform down. Any lookup by name (``platform_registry.get``) still imports a
  17. deferred adapter on demand.
  18. """
  19. from __future__ import annotations
  20. import json
  21. import logging
  22. import os
  23. from pathlib import Path
  24. from typing import Any, Callable, Iterable, Optional
  25. logger = logging.getLogger(__name__)
  26. def _yaml_block_names(yaml_cfg: Any) -> set[str]:
  27. """Keys of every mapping a platform block may live in (``platform_section`` /
  28. ``merge_platform_sections`` read the same places): ``<name>:``, ``platforms.<name>``,
  29. ``gateway.<name>``, ``gateway.platforms.<name>``."""
  30. if not isinstance(yaml_cfg, dict):
  31. return set()
  32. gateway: dict = yaml_cfg["gateway"] if isinstance(yaml_cfg.get("gateway"), dict) else {}
  33. parents = (yaml_cfg, yaml_cfg.get("platforms"), gateway, gateway.get("platforms"))
  34. return {str(k) for parent in parents if isinstance(parent, dict)
  35. for k, v in parent.items() if isinstance(v, dict)}
  36. def _env_names(home: Optional[Path]) -> set[str]:
  37. names = {k for k, v in os.environ.items() if str(v).strip()}
  38. try:
  39. from agent.secret_scope import current_secret_scope, load_env_file
  40. scope = current_secret_scope()
  41. if scope is not None:
  42. names.update(k for k, v in scope.items() if str(v).strip())
  43. if home is not None:
  44. names.update(k for k, v in load_env_file(home / ".env").items() if str(v).strip())
  45. # Values an external secret source (Bitwarden, 1Password) resolved for this home, and
  46. # the administrator-managed .env: both feed the profile scope the adapters read.
  47. from hermes_cli.env_loader import get_secret_source_values
  48. names.update(k for k, v in get_secret_source_values(home).items() if str(v).strip())
  49. from hermes_cli.managed_scope import load_managed_env
  50. names.update(k for k, v in load_managed_env().items() if str(v).strip())
  51. except Exception:
  52. logger.debug("platform activation: env scan degraded", exc_info=True)
  53. return names
  54. def _credential_pool_names(home: Optional[Path]) -> set[str]:
  55. if home is None:
  56. return set()
  57. try:
  58. with open(home / "auth.json", encoding="utf-8-sig") as handle:
  59. pool = (json.load(handle) or {}).get("credential_pool") or {}
  60. return {str(k) for k in pool} if isinstance(pool, dict) else set()
  61. except FileNotFoundError:
  62. return set()
  63. except Exception:
  64. logger.debug("platform activation: auth.json unreadable", exc_info=True)
  65. return set()
  66. def _matches(name: str, candidates: Iterable[str]) -> bool:
  67. lowered = name.lower()
  68. return any(c.lower() == lowered or c.lower().startswith(lowered + "_") for c in candidates)
  69. def _legacy_gateway_json_names(home: Path) -> set[str]:
  70. try:
  71. with open(home / "gateway.json", encoding="utf-8-sig") as handle:
  72. rows = (json.load(handle) or {}).get("platforms") or {}
  73. return {str(k) for k in rows} if isinstance(rows, dict) else set()
  74. except FileNotFoundError:
  75. return set()
  76. except (OSError, ValueError, AttributeError):
  77. # Unreadable or not a {"platforms": {...}} document: the YAML/env/pool evidence still applies.
  78. logger.debug("platform activation: gateway.json unreadable", exc_info=True)
  79. return set()
  80. def activation_predicate(
  81. *, yaml_cfg: Any = None, platform_names: Iterable[str] = (), home: Optional[Path] = None,
  82. registry: Any = None,
  83. ) -> Callable[[str], bool]:
  84. """``name -> bool``: does this profile show evidence of configuring platform *name*?
  85. *yaml_cfg* is the loaded config.yaml layer (read from *home* when omitted), *platform_names*
  86. any already-merged platform keys (``GatewayConfig.platforms``). *home* defaults to the active
  87. Hermes home.
  88. """
  89. if home is None:
  90. from hermes_constants import get_hermes_home
  91. home = get_hermes_home()
  92. if yaml_cfg is None and home is not None:
  93. try:
  94. from gateway.config_loader import read_yaml_layers
  95. yaml_cfg = read_yaml_layers(home)
  96. except Exception:
  97. logger.debug("platform activation: config.yaml unreadable", exc_info=True)
  98. blocks = _yaml_block_names(yaml_cfg) | {str(getattr(n, "value", n)) for n in platform_names}
  99. if home is not None:
  100. blocks |= _legacy_gateway_json_names(home)
  101. env = _env_names(home)
  102. upper_env = {e.upper() for e in env}
  103. pools = _credential_pool_names(home)
  104. def has_evidence(name: str) -> bool:
  105. if _matches(name, blocks) or _matches(name, pools):
  106. return True
  107. prefix = name.upper().replace("-", "_") + "_"
  108. if any(e.startswith(prefix) for e in upper_env):
  109. return True
  110. declared = registry.activation_env(name) if registry is not None else frozenset()
  111. return any(d.upper() in upper_env for d in declared)
  112. return has_evidence
  113. def configured_plugin_entries(registry: Any, **evidence: Any) -> list:
  114. """Plugin entries for platforms this profile configures (see module docstring); already-loaded
  115. entries are always included. Never imports an adapter with no activation evidence."""
  116. if registry is None:
  117. return []
  118. wanted = activation_predicate(registry=registry, **evidence)
  119. return [e for e in registry.configured_entries(wanted) if e.source == "plugin"]