platform_registry.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. """Platform adapter registry.
  2. Adapters (built-in and plugin) self-register here so the gateway can discover and
  3. instantiate them without hardcoded if/elif chains. Plugins register via
  4. ``PluginContext.register_platform()``; ``GatewayRunner._create_adapter()`` consults the
  5. registry first, then the legacy built-in path. Plugin side: ``platform_registry
  6. .register(PlatformEntry(...))``; gateway side: ``create_adapter("irc", platform_config)``.
  7. """
  8. import contextvars
  9. import logging
  10. import sys
  11. import threading
  12. from dataclasses import dataclass, field
  13. from typing import Any, Awaitable, Callable, Optional
  14. from hermes_constants import hermes_home_key
  15. logger = logging.getLogger(__name__)
  16. _LoadKey = tuple[Optional[str], str]
  17. _Loader = Callable[[], None]
  18. def _plugin_scope_from_callable(callback: Callable) -> Optional[str]:
  19. """Infer a plugin profile from code registered outside PluginContext."""
  20. try:
  21. from tools.registry import registry as tool_registry
  22. return tool_registry.plugin_scope_for_callable(callback)
  23. except (ImportError, AttributeError):
  24. return None
  25. def _caller_plugin_scope() -> Optional[str]:
  26. try:
  27. module_name = sys._getframe(2).f_globals.get("__name__", "") or ""
  28. except Exception:
  29. return None
  30. return _plugin_scope_from_callable(type("_Caller", (), {"__module__": module_name}))
  31. @dataclass
  32. class PlatformEntry:
  33. """Metadata and factory for a single platform adapter."""
  34. name: str # config.yaml identifier (e.g. "irc")
  35. label: str # human-readable
  36. adapter_factory: Callable[[Any], Any] # PlatformConfig -> adapter (factory allows custom init)
  37. # PASSIVE dependency probe (deps importable RIGHT NOW); must be side-effect free since it
  38. # runs from status displays and the config enablement pass, which may never pip-install.
  39. check_fn: Callable[[], bool]
  40. # Optional: given a PlatformConfig, is it properly configured?
  41. # If None, the registry skips config validation and lets the adapter
  42. # fail at connect() time with a descriptive error.
  43. validate_config: Optional[Callable[[Any], bool]] = None
  44. # ACTIVE dependency installer: make the platform's dependencies available,
  45. # installing them (pm.sync_venv) if needed. Returns True once deps are
  46. # importable, False if they could not be installed. Called by
  47. # ``create_adapter()`` when ``check_fn`` returns False — i.e. exactly at
  48. # the moment the gateway is about to bring the platform up and the user
  49. # has it enabled/configured. None = no auto-install; a False ``check_fn``
  50. # is then a hard block (correct for platforms with no optional deps).
  51. #
  52. # Why two fields (#79812): when the ACTIVE installer was registered as
  53. # ``check_fn``, every status display pip-installed SDKs as a side effect
  54. # (desktop boot-loop at 94%, see gateway/config.py enablement comments);
  55. # when the PASSIVE probe was registered instead, ``create_adapter()``
  56. # returned None before ``connect()`` could lazy-install, so the deps
  57. # never installed at all (Teams deadlock). Splitting the two roles makes
  58. # both call sites correct by construction.
  59. ensure_deps_fn: Optional[Callable[[], bool]] = None
  60. # Connected/configured for this PlatformConfig (``get_connected_platforms``, setup UI);
  61. # None falls back to ``validate_config`` or ``check_fn``.
  62. is_connected: Optional[Callable[[Any], bool]] = None
  63. required_env: list = field(default_factory=list) # ``hermes setup`` display
  64. install_hint: str = "" # shown when check_fn is False
  65. setup_fn: Optional[Callable[[], None]] = None # None = _setup_standard_platform / env display
  66. source: str = "plugin" # "builtin" or "plugin"
  67. plugin_name: str = "" # owning manifest so ``hermes gateway setup`` can auto-enable it
  68. allowed_users_env: str = "" # comma-separated allowed user IDs (_is_user_authorized)
  69. allow_all_env: str = "" # truthy "allow everyone" switch
  70. max_message_length: int = 0 # smart-chunking cap; 0 = no limit
  71. pii_safe: bool = False # session descriptions redact PII (phone numbers, etc.)
  72. emoji: str = "🔌" # CLI/gateway display
  73. allow_update_command: bool = True # /update may be issued from this platform
  74. platform_hint: str = "" # injected into the system prompt; empty = none
  75. # ``() -> Optional[dict]`` of ``extra`` fields to seed when auto-enabled from env; runs in
  76. # ``_apply_env_overrides`` BEFORE adapter construction so ``gateway status`` sees it.
  77. env_enablement_fn: Optional[Callable[[], Optional[dict]]] = None
  78. # YAML->env bridge ``(yaml_cfg, platform_cfg) -> Optional[dict]`` merged into ``extra``; runs
  79. # after the shared-key loop, before ``_apply_env_overrides``. Build it with
  80. # ``gateway.platforms._shared.apply_yaml_bridge`` — it writes env only when unset (env > YAML)
  81. # and never under a multiplexed secondary's scope; a hand-rolled ``os.environ[...] =`` is
  82. # first-profile-wins. Contract: docs/developer-guide/adding-platform-adapters.md.
  83. apply_yaml_config_fn: Optional[Callable[[dict, dict], Optional[dict]]] = None
  84. cron_deliver_env_var: str = "" # home-channel env var read for cron ``deliver=<name>``
  85. # ``(target_ref) -> Optional[(chat_id, thread_id)]`` run before channel-directory
  86. # fallback so plugins can declare native target syntax; None = continue resolution.
  87. parse_target_ref_fn: Optional[Callable[[str], Optional[tuple[str, Optional[str]]]]] = None
  88. # Post-resolution validation: True accept, False reject, non-empty str = reject + diagnostic.
  89. validate_target_ref_fn: Optional[Callable[[str], bool | str]] = None
  90. # Whole-request delivery ``(args, normalized_chat_id, platform_name, pconfig)``, sync or
  91. # async; prefer standalone_sender_fn when the standard send contract suffices.
  92. send_message_handler: Optional[Callable[[dict, str, str, Any], Any]] = None
  93. # Out-of-process sender for cron without a co-resident gateway:
  94. # ``async (pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False)
  95. # -> {"success": True, "message_id": ...} | {"error": str}``.
  96. standalone_sender_fn: Optional[Callable[..., Awaitable[dict]]] = None
  97. # Every inbound event is produced by the service the adapter authenticated to with its own
  98. # credential (an event bus, not a person), so user allowlists and pairing do not apply. Never
  99. # set it for a chat platform: any sender would reach the agent. Consumer: Home Assistant.
  100. trusted_inbound: bool = False
  101. # Built-in display defaults tier ("high" | "medium" | "low" | "minimal", see
  102. # gateway/display_config.py) used below the user's display.* overrides; "" = global defaults.
  103. display_tier: str = ""
  104. # --- prompt ---
  105. # Per-key display defaults layered over ``display_tier`` (e.g. Discord ``reasoning_style``);
  106. # empty = the tier as-is. Same keys as display_config._GLOBAL_DEFAULTS.
  107. display_overrides: dict = field(default_factory=dict)
  108. # Env prefixes shared with a non-channel capability (the same plugin's tools): profile clones
  109. # strip keys under them only when the source profile runs the adapter (profile_channels.py).
  110. shared_env_prefixes: tuple = ()
  111. # --- config ---
  112. # Gateway "sufficiently configured?" verdict from the PlatformConfig ALONE (yaml + env seeding
  113. # already merged into it), for ``GatewayConfig.get_connected_platforms``. Unlike ``is_connected``
  114. # it never falls back to the env / ``.env`` (the gateway runs from the merged config, setup UIs
  115. # read the env), and it owns the ``token``/``api_key`` shortcut so a platform that needs more
  116. # than a token (Weixin: token AND account_id) can refuse it. None = ``token or api_key``, then
  117. # ``is_connected`` / ``validate_config``.
  118. config_connected_fn: Optional[Callable[[Any], bool]] = None
  119. # --- authz ---
  120. # ``<PLATFORM>_ALLOW_BOTS`` (YAML ``allow_bots`` wins): bot senders it admits ("mentions"/"all")
  121. # bypass the human allowlist, checked before the no-user-id guard. "" = bots get no bypass.
  122. allow_bots_env: str = ""
  123. # (dm_policy_env, group_policy_env) of a platform with its own dm/group policy: when enabled and
  124. # either resolves "open" without ``allow_all_env`` / GATEWAY_ALLOW_ALL_USERS, startup is refused.
  125. # A "" member = that policy is YAML-only (QQ Bot). None = no own policy, never checked.
  126. own_policy_env: Optional[tuple] = None
  127. # Env var listing group/forum CHAT ids whose traffic is authorized by chat (any sender, user_id
  128. # optional): Telegram ``TELEGRAM_GROUP_ALLOWED_CHATS``, QQ ``QQ_GROUP_ALLOWED_USERS``. "" = none.
  129. group_allowed_chats_env: str = ""
  130. # True: a configured env allowlist turns the unauthorized-DM default from "pair" into "ignore"
  131. # (the owner restricted access; unknown senders get no pairing code).
  132. allowlist_suppresses_pairing: bool = False
  133. # --- send ---
  134. # send_message native target syntax, see ``gateway.platforms.send_targets``. A hint, not an
  135. # authority like ``parse_target_ref_fn``: None / NOT_EXPLICIT fall back to core's generic id
  136. # rules / channel directory, it also re-parses channel-directory hits, and it keeps
  137. # ``pass_unresolved_references`` lenient.
  138. target_ref_syntax_fn: Optional[Callable[[str], Any]] = None
  139. # ``gateway.platforms.send_targets.StandaloneSendPolicy`` or None (generic send routing).
  140. standalone_send: Optional[Any] = None
  141. # --- dashboard ---
  142. # Channels-page card metadata (hermes_cli/web_server_messaging.py, Desktop + web dashboard).
  143. # Every field defaults to "not declared": the card then falls back to ``label`` / ``install_hint``
  144. # / ``required_env`` + prefix-discovered env vars.
  145. dashboard_label: str = "" # card title when it differs from ``label`` (status/CLI keep ``label``)
  146. dashboard_description: str = "" # human description; ``install_hint`` is a dependency note
  147. docs_url: str = "" # setup guide linked from the card
  148. dashboard_env_vars: tuple = () # card fields shown first, in this order, before discovered vars
  149. # Credentials the card treats as "configured"; None = ``required_env`` (which also drives
  150. # ``hermes setup`` and the child-env scrub, so the card may legitimately ask for a different set).
  151. dashboard_required_env: Optional[tuple] = None
  152. # ``{ENV_KEY: (accepts(value) -> bool, 400 detail)}``: the dashboard PUT rejects a non-empty value
  153. # the predicate refuses, catching credentials pasted into the wrong field.
  154. env_value_rules: dict = field(default_factory=dict)
  155. # --- env ---
  156. # Ordered ``step(GatewayConfig) -> None`` env->config bridge run by ``_apply_env_overrides`` for a
  157. # platform with activation evidence (``gateway.platform_env.EnvCred`` / ``home_step`` /
  158. # ``reply_mode_step``); () = none. Unlike ``env_enablement_fn`` it runs whether or not deps are
  159. # importable and may set token / home channel / reply mode or force-disable.
  160. env_overrides: tuple = ()
  161. # Env names whose presence drives that enable, cited by the explicit-disable WARNING and used by
  162. # ``hermes_cli.profile_channels`` as the platform's credential set; () = none declared.
  163. env_enable_credentials: tuple = ()
  164. def core_ships_platform(name: str) -> bool:
  165. """*name* is a platform core ships an adapter for: a static ``Platform`` member or a bundled
  166. ``plugins/platforms/`` plugin. A user plugin may replace such an adapter but never mark it
  167. ``trusted_inbound``: its senders are people, and that flag waives allowlists and pairing."""
  168. from gateway.config import Platform
  169. value = str(name or "").strip().lower()
  170. return value in {Platform[member].value for member in Platform._member_names_} or (
  171. value in Platform._scan_bundled_plugin_platforms()[0])
  172. class PlatformRegistry:
  173. """Central registry of platform adapters. Registrations are serialized; concurrent
  174. lazy lookups share an in-flight event while the loader runs outside the registry lock."""
  175. def __init__(self) -> None:
  176. self._lock = threading.RLock()
  177. self._entries: dict[str, PlatformEntry] = {} # process-global (e.g. the built-in relay)
  178. # Plugin adapters are isolated per resolved HERMES_HOME and overlay the
  179. # process-global entries for lookups in that profile's runtime scope.
  180. self._scoped_entries: dict[str, dict[str, PlatformEntry]] = {}
  181. # Deferred loaders: name -> callable importing the owning plugin module (which calls
  182. # register()); eagerly importing ~20 SDK-heavy adapters added seconds to every
  183. # `hermes` invocation, so the import happens only when a lookup asks for it.
  184. self._deferred: dict[str, _Loader] = {}
  185. self._scoped_deferred: dict[str, dict[str, _Loader]] = {}
  186. self._inflight: dict[_LoadKey, threading.Event] = {}
  187. self._inflight_loaders: dict[_LoadKey, _Loader] = {}
  188. # Load keys whose loader is running in the current flow; copied into plugin deadline
  189. # workers, so a nested walk from register() sees its own parent's load as recursive.
  190. self._loading: contextvars.ContextVar[frozenset[_LoadKey]] = contextvars.ContextVar(
  191. f"platform_registry_loading_{id(self)}", default=frozenset()
  192. )
  193. self._cancelled_inflight: set[_LoadKey] = set()
  194. # A failed loader is no longer discoverable, but its identity remains
  195. # until ownership teardown can CAS-restore the displaced predecessor.
  196. self._consumed_loaders: dict[_LoadKey, _Loader] = {}
  197. # Manifest-declared env names per deferred platform (``requires_env``), recorded without
  198. # importing the adapter so ``gateway.platform_activation`` can tell a configured platform
  199. # from an unconfigured one. A hint only: a stale entry costs one extra import, never a miss.
  200. self._activation_env: dict[str, frozenset[str]] = {}
  201. @staticmethod
  202. def current_scope_key() -> str:
  203. return hermes_home_key()
  204. def _scope_maps(
  205. self, scope: Optional[str], *, create: bool = False
  206. ) -> tuple[dict[str, PlatformEntry], dict[str, _Loader]]:
  207. if scope is None:
  208. return self._entries, self._deferred
  209. if create:
  210. return self._scoped_entries.setdefault(scope, {}), self._scoped_deferred.setdefault(scope, {})
  211. return self._scoped_entries.get(scope, {}), self._scoped_deferred.get(scope, {})
  212. def _registration_state(
  213. self, scope: Optional[str], name: str, *, create: bool = False
  214. ) -> tuple[Optional[PlatformEntry], Optional[_Loader]]:
  215. """(entry, loader) for *name*; the loader falls back to in-flight, then consumed."""
  216. entries, deferred = self._scope_maps(scope, create=create)
  217. entry = entries.get(name)
  218. loader = deferred.get(name)
  219. if entry is None and loader is None:
  220. loader = self._inflight_loaders.get((scope, name)) or self._consumed_loaders.get((scope, name))
  221. return entry, loader
  222. def _prune_scope(self, scope: Optional[str]) -> None:
  223. for maps in (self._scoped_entries, self._scoped_deferred) if scope is not None else ():
  224. if not maps.get(scope):
  225. maps.pop(scope, None)
  226. # -- deferred loading ----------------------------------------------------
  227. def register_deferred(self, name: str, loader: _Loader, *, scope: Optional[str] = None) -> None:
  228. """Register a lazy loader (imports the plugin module, which must call :meth:`register`);
  229. runs at most once, on first lookup; a concrete registration drops it."""
  230. with self._lock:
  231. entries, deferred = self._scope_maps(scope, create=True)
  232. self._consumed_loaders.pop((scope, name), None)
  233. if name not in entries:
  234. deferred[name] = loader
  235. def note_activation_env(self, name: str, env_names) -> None:
  236. """Record the env names a deferred platform's manifest declares (see ``_activation_env``)."""
  237. names = frozenset(str(n).strip() for n in env_names or () if str(n).strip())
  238. with self._lock:
  239. self._activation_env[name] = self._activation_env.get(name, frozenset()) | names
  240. def activation_env(self, name: str) -> frozenset[str]:
  241. with self._lock:
  242. return self._activation_env.get(name, frozenset())
  243. def snapshot_registration(
  244. self, name: str, *, scope: Optional[str] = None
  245. ) -> tuple[Optional[PlatformEntry], Optional[_Loader]]:
  246. """Concrete and deferred state for *name* without resolving it, so the plugin ledger can
  247. restore a deferred loader displaced by a concrete registration without importing it."""
  248. with self._lock:
  249. return self._registration_state(scope, name)
  250. def restore_registration(
  251. self, name: str, current: tuple[Optional[PlatformEntry], Optional[_Loader]],
  252. previous: tuple[Optional[PlatformEntry], Optional[_Loader]], *, scope: Optional[str] = None,
  253. ) -> bool:
  254. """Restore a registration if its full state is still *current* (CAS): a later
  255. registration is never removed, and deferred loaders are part of the state."""
  256. with self._lock:
  257. entry, loader = self._registration_state(scope, name, create=True)
  258. if entry is not current[0] or loader is not current[1]:
  259. return False
  260. load_key = (scope, name)
  261. for mapping, value in zip(self._scope_maps(scope), previous):
  262. if value is None:
  263. mapping.pop(name, None)
  264. else:
  265. mapping[name] = value
  266. if load_key in self._inflight:
  267. self._cancelled_inflight.add(load_key)
  268. self._consumed_loaders.pop(load_key, None)
  269. self._prune_scope(scope)
  270. return True
  271. def _resolve(self, name: str, scope: Optional[str] = None) -> None:
  272. """Run the deferred loader for *name* if one is pending."""
  273. loader: Optional[_Loader] = None
  274. is_loader = False
  275. with self._lock:
  276. active_scope = scope or self.current_scope_key()
  277. entries, deferred = self._scope_maps(active_scope)
  278. scoped_key = (active_scope, name)
  279. global_key = (None, name)
  280. event = self._inflight.get(scoped_key)
  281. load_key = scoped_key
  282. if event is None and name not in entries and self._loading.get():
  283. from hermes_cli.plugins_loader import in_plugin_load_worker
  284. if in_plugin_load_worker():
  285. return # on a deadline worker: never block on a sibling load the parent may hold the lock for; caller sees it unloaded
  286. if event is None and name not in entries:
  287. loader = deferred.pop(name, None)
  288. if event is None and loader is None and name not in entries:
  289. load_key = global_key
  290. event = self._inflight.get(global_key)
  291. if event is None:
  292. loader = self._deferred.pop(name, None)
  293. if event is None and loader is not None:
  294. event = threading.Event()
  295. self._inflight[load_key] = event
  296. self._inflight_loaders[load_key] = loader
  297. is_loader = True
  298. if event is None:
  299. return
  300. if not is_loader and load_key in self._loading.get():
  301. logger.warning("Deferred platform '%s' recursively requested while loading", name)
  302. return
  303. if not is_loader:
  304. event.wait()
  305. # Teardown may have restored an older deferred generation while cancelling the one
  306. # we waited for; resolve that predecessor instead of a one-shot false negative.
  307. self._resolve(name, active_scope)
  308. return
  309. token = self._loading.set(self._loading.get() | {load_key})
  310. try:
  311. loader()
  312. except Exception as e:
  313. logger.warning("Deferred load of platform '%s' failed: %s", name, e, exc_info=True)
  314. finally:
  315. self._loading.reset(token)
  316. with self._lock:
  317. was_cancelled = load_key in self._cancelled_inflight
  318. entries, deferred = self._scope_maps(load_key[0])
  319. if not was_cancelled and name not in entries and name not in deferred:
  320. self._consumed_loaders[load_key] = loader
  321. self._inflight.pop(load_key, None)
  322. self._inflight_loaders.pop(load_key, None)
  323. self._cancelled_inflight.discard(load_key)
  324. event.set()
  325. if was_cancelled:
  326. self._resolve(name, active_scope)
  327. def is_deferred_load_cancelled(self, name: str, *, scope: Optional[str] = None) -> bool:
  328. """Whether ownership teardown cancelled an in-flight loader."""
  329. with self._lock:
  330. return (scope, name) in self._cancelled_inflight
  331. def _pending_names(self, active_scope: str) -> list[str]:
  332. """Deferred (or in-flight) names for *active_scope*, scoped first, without loading them."""
  333. with self._lock:
  334. _entries, scoped_deferred = self._scope_maps(active_scope)
  335. scoped_names = set(scoped_deferred)
  336. global_names = set(self._deferred)
  337. for inflight_scope, name in self._inflight:
  338. if inflight_scope == active_scope:
  339. scoped_names.add(name)
  340. elif inflight_scope is None:
  341. global_names.add(name)
  342. return [*sorted(scoped_names), *sorted(global_names - scoped_names)]
  343. def _resolve_all(self, wanted: Optional[Callable[[str], bool]] = None) -> None:
  344. """Run every pending deferred loader, or only those *wanted* accepts (``all_entries`` /
  345. ``plugin_entries`` / ``configured_entries``; CLI chat never iterates the full set)."""
  346. active_scope = self.current_scope_key()
  347. # Load outside the registry lock; each name has an in-flight event so concurrent
  348. # readers wait for the same materialization.
  349. for name in self._pending_names(active_scope):
  350. if wanted is None or wanted(name):
  351. self._resolve(name, active_scope)
  352. def pending_names(self) -> list[str]:
  353. """Names registered as deferred loaders that have not been imported yet (current scope)."""
  354. return self._pending_names(self.current_scope_key())
  355. def configured_entries(self, wanted: Callable[[str], bool]) -> list[PlatformEntry]:
  356. """Loaded entries, after materializing only the deferred platforms *wanted* accepts.
  357. The gateway's config/env passes need each platform's hooks only for platforms the profile
  358. actually configures; importing every bundled adapter (~20 SDKs) just to read metadata cost
  359. every cold start ~0.5 s. *wanted* is :func:`gateway.platform_activation.has_activation_evidence`
  360. (or a test stub); entries that are already loaded are always returned."""
  361. self._resolve_all(wanted)
  362. with self._lock:
  363. return list({**self._entries, **self._scoped_entries.get(self.current_scope_key(), {})}.values())
  364. def loaded_entries(self) -> list[PlatformEntry]:
  365. """Entries already materialized (never imports a deferred adapter)."""
  366. with self._lock:
  367. return list({**self._entries, **self._scoped_entries.get(self.current_scope_key(), {})}.values())
  368. def register(self, entry: PlatformEntry, *, scope: Optional[str] = None) -> None:
  369. """Register a platform adapter entry (last writer wins on name clash)."""
  370. with self._lock:
  371. if scope is None and entry.source == "plugin":
  372. scope = (
  373. _caller_plugin_scope()
  374. or _plugin_scope_from_callable(entry.adapter_factory)
  375. or _plugin_scope_from_callable(entry.check_fn)
  376. )
  377. # A concrete registration supersedes any pending deferred loader.
  378. entries, deferred = self._scope_maps(scope, create=True)
  379. self._consumed_loaders.pop((scope, entry.name), None)
  380. deferred.pop(entry.name, None)
  381. prev = entries.get(entry.name)
  382. if prev is not None:
  383. logger.info("Platform '%s' re-registered (was %s, now %s)", entry.name, prev.source, entry.source)
  384. entries[entry.name] = entry
  385. logger.debug("Registered platform adapter: %s (%s)", entry.name, entry.source)
  386. def unregister(self, name: str, *, scope: Optional[str] = None) -> bool:
  387. """Remove a platform entry. Returns True if it existed."""
  388. with self._lock:
  389. inferred_scope = scope if scope is not None else _caller_plugin_scope()
  390. active_scope = inferred_scope or self.current_scope_key()
  391. entries, deferred = self._scope_maps(active_scope)
  392. if inferred_scope is not None or name in entries or name in deferred:
  393. deferred.pop(name, None)
  394. removed = entries.pop(name, None) is not None
  395. self._prune_scope(active_scope)
  396. return removed
  397. self._deferred.pop(name, None)
  398. return self._entries.pop(name, None) is not None
  399. def _load_pending(self, scope: str, name: str) -> bool:
  400. """True when a lookup of *name* must run/await a deferred loader (lock held)."""
  401. _entries, deferred = self._scope_maps(scope)
  402. return (
  403. name in deferred or (name not in self._entries and name in self._deferred)
  404. or (scope, name) in self._inflight or (None, name) in self._inflight
  405. )
  406. def get(self, name: str) -> Optional[PlatformEntry]:
  407. """Look up a platform entry by name."""
  408. scope = self.current_scope_key()
  409. with self._lock:
  410. entries, _deferred = self._scope_maps(scope)
  411. needs_resolve = name not in entries and self._load_pending(scope, name)
  412. if needs_resolve:
  413. self._resolve(name, scope)
  414. with self._lock:
  415. entries, _deferred = self._scope_maps(scope)
  416. return entries.get(name) or self._entries.get(name)
  417. def all_entries(self) -> list[PlatformEntry]:
  418. """Return all registered platform entries."""
  419. self._resolve_all()
  420. with self._lock:
  421. return list({**self._entries, **self._scoped_entries.get(self.current_scope_key(), {})}.values())
  422. def plugin_entries(self) -> list[PlatformEntry]:
  423. """Return only plugin-registered platform entries."""
  424. return [e for e in self.all_entries() if e.source == "plugin"]
  425. def registered_names(self) -> set[str]:
  426. """Concrete and deferred names (current profile scope AND process-global, like
  427. ``is_registered``) without loading adapters."""
  428. with self._lock:
  429. entries, deferred = self._scope_maps(self.current_scope_key())
  430. return entries.keys() | deferred.keys() | self._entries.keys() | self._deferred.keys()
  431. def required_env_names(self) -> set[str]:
  432. """``required_env`` of every loaded entry (current profile scope AND process-global) without
  433. loading deferred adapters; the child-env scrub reads this on every spawn."""
  434. with self._lock:
  435. entries, _deferred = self._scope_maps(self.current_scope_key())
  436. return {n for e in (*self._entries.values(), *entries.values())
  437. for n in e.required_env if isinstance(n, str)}
  438. def is_registered(self, name: str) -> bool:
  439. # A deferred (not-yet-imported) platform still counts as registered so cheap membership
  440. # checks (toolset resolution, webhook deliver-target checks) never trigger a heavy import.
  441. with self._lock:
  442. scope = self.current_scope_key()
  443. entries, _deferred = self._scope_maps(scope)
  444. return name in entries or name in self._entries or self._load_pending(scope, name)
  445. def create_adapter(self, name: str, config: Any) -> Optional[Any]:
  446. """Create an adapter instance for *name*; None when no entry exists, deps are missing
  447. and cannot be installed, ``validate_config`` fails, or the factory raises."""
  448. entry = self.get(name)
  449. if entry is None:
  450. return None
  451. def _probe(fn: Callable[[], Any], failure_msg: str) -> bool:
  452. try:
  453. return bool(fn())
  454. except Exception as e:
  455. logger.warning(failure_msg, entry.label, e)
  456. return False
  457. deps_ok = _probe(entry.check_fn, "Platform '%s' check_fn raised: %s")
  458. if not deps_ok and entry.ensure_deps_fn is not None:
  459. # The ONE place the active installer runs: the platform is enabled+configured
  460. # and about to connect, so an install is what the user wants.
  461. logger.info("Platform '%s' dependencies missing — attempting install...", entry.label)
  462. deps_ok = _probe(entry.ensure_deps_fn, "Platform '%s' dependency install raised: %s")
  463. if not deps_ok:
  464. hint = f" ({entry.install_hint})" if entry.install_hint else ""
  465. logger.warning("Platform '%s' requirements not met%s", entry.label, hint)
  466. return None
  467. if entry.validate_config is not None:
  468. try:
  469. if not entry.validate_config(config):
  470. logger.warning("Platform '%s' config validation failed", entry.label)
  471. return None
  472. except Exception as e:
  473. logger.warning("Platform '%s' config validation error: %s", entry.label, e)
  474. return None
  475. try:
  476. return entry.adapter_factory(config)
  477. except Exception as e:
  478. logger.error("Failed to create adapter for platform '%s': %s", entry.label, e, exc_info=True)
  479. return None
  480. # Module-level singleton
  481. platform_registry = PlatformRegistry()