"""Shared directory-plugin loader for ``plugins///`` discovery packages (cron_providers, context_engine, memory): import ``__init__.py`` by path with siblings pre-registered so relative imports work, then extract the provider via ``register(ctx)`` or an ABC-subclass fallback.""" from __future__ import annotations import contextlib import importlib.machinery import importlib.util import logging import re import sys import threading import time from contextvars import ContextVar from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, List, Optional, Tuple _log = logging.getLogger(__name__) _MODULE_LOAD_LOCKS: dict[str, threading.RLock] = {} _MODULE_LOAD_LOCKS_GUARD = threading.Lock() # Inside bounded_load_wait(), how long a second caller waits for another thread's in-flight load of # the same module. Past it the module is marked stalled (a hung import) and later bounded callers # refuse at once until it finishes. Other callers (agent builds) wait for the load to finish. _CONCURRENT_LOAD_WAIT_SECS = 10.0 _BOUNDED_WAIT: ContextVar[bool] = ContextVar("plugin_load_bounded_wait", default=False) _STALLED_LOADS: set[str] = set() _LOAD_OWNERS: dict[str, int] = {} # module -> thread id running its load _LOAD_WAITERS: dict[int, str] = {} # thread id -> module whose load it waits for def _waits_for(tid: int) -> set: """Threads *tid* is blocked on: a loader lock owner, or an importlib module-lock owner.""" owners = {_LOAD_OWNERS.get(_LOAD_WAITERS.get(tid, ""))} blocked = getattr(importlib._bootstrap, "_blocking_on", {}).get(tid) # list on 3.12+, lock on 3.11 owners.update(getattr(lk, "owner", None) for lk in (blocked if isinstance(blocked, list) else [blocked])) return owners - {None} def _load_would_deadlock(me: int) -> bool: """Whether the wait graph (loader locks + importlib's module locks) leads back to *me*. importlib cannot see the loader lock in its own deadlock check, so walk both kinds here.""" seen, todo = set(), list(_waits_for(me)) while todo: tid = todo.pop() if tid == me: return True if tid not in seen: seen.add(tid) todo.extend(_waits_for(tid)) return False @contextlib.contextmanager def bounded_load_wait(): """For per-turn callers that must not stall on another thread's hung plugin import: their loads give up (None) after ``_CONCURRENT_LOAD_WAIT_SECS`` instead of waiting it out.""" token = _BOUNDED_WAIT.set(True) try: yield finally: _BOUNDED_WAIT.reset(token) def _module_load_lock(module_name: str) -> threading.RLock: with _MODULE_LOAD_LOCKS_GUARD: return _MODULE_LOAD_LOCKS.setdefault(module_name, threading.RLock()) def register_synthetic_package(name: str, search_locations: list[str]) -> None: """Register an empty package shell so ``.`` relative imports resolve.""" if name in sys.modules: return spec = importlib.machinery.ModuleSpec(name, None, is_package=True) spec.submodule_search_locations = search_locations sys.modules[name] = importlib.util.module_from_spec(spec) def user_plugins_dir() -> Optional[Path]: """Return ``$HERMES_HOME/plugins/`` or None if unavailable.""" try: from hermes_constants import get_hermes_home d = get_hermes_home() / "plugins" return d if d.is_dir() else None except Exception: return None # Names arrive from config.yaml (``memory.provider``, ``cron.provider``, ``context.engine``): # a single plain directory segment, never a path that escapes the plugin root. _PLUGIN_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$") def plugin_child_dir(root: Path, name: str) -> Optional[Path]: """``root / name`` when *name* is a plain plugin directory name, else None (treated as not found).""" return root / name if isinstance(name, str) and _PLUGIN_NAME_RE.fullmatch(name) else None def is_direct_child(path: Path, root: Path) -> bool: """Whether *path* really sits directly under *root*, both as written and resolved. Resolved, because ``Path.parents`` is lexical (``root / "../../x"`` lists *root* among its parents); as written, because a user-dir symlink into *root* must not count as bundled (it would load in-process past ``plugins.isolation: host``, and can be swapped between check and import).""" return path.parent == root and path.resolve().parent == root.resolve() def iter_plugin_dirs(root: Path) -> list[Path]: """Sorted child dirs of *root* that have an ``__init__.py`` (skips ``_``/``.`` names).""" if not root.is_dir(): return [] dirs: list[Path] = [] for child in sorted(root.iterdir()): if child.name.startswith(("_", ".")): continue try: if child.is_dir() and (child / "__init__.py").exists(): dirs.append(child) except OSError as exc: # one mode-000 / ACL-denied child must not abort the listing _log.warning("Skipping unreadable plugin directory %s: %s", child, exc) return dirs def read_plugin_description(plugin_dir: Path) -> str: """Return ``description`` from ``plugin.yaml`` (empty string if absent/unreadable).""" try: from utils import fast_safe_load with open(plugin_dir / "plugin.yaml", encoding="utf-8-sig") as f: meta = fast_safe_load(f) or {} return meta.get("description", "") except Exception: return "" @dataclass(frozen=True) class PluginChoice: """What config.yaml says about one category's user plugins, read once per listing: the provider the category key selects and the ``plugins.enabled`` / ``plugins.disabled`` lists.""" selected: str = "" enabled: frozenset = frozenset() disabled: frozenset = frozenset() def is_disabled(self, plugin_dir: Path, name: str) -> bool: """Whether ``plugins.disabled`` lists the plugin under any spelling the plugin commands write: the provider name, its directory name or its manifest ``name:`` (read without importing).""" from pm.plugins_state import plugin_spellings return bool(self.disabled and plugin_spellings(plugin_dir, name) & self.disabled) def allows_import(self, plugin_dir: Path, name: str) -> bool: """A user plugin's code may run for a listing only when it is turned on: selected for this category or in ``plugins.enabled``, and not in ``plugins.disabled``.""" from pm.plugins_state import plugin_spellings spellings = plugin_spellings(plugin_dir, name) if spellings & self.disabled: return False return name == self.selected or bool(spellings & self.enabled) def read_plugin_choice(*selection_key: str, builtin: frozenset = frozenset()) -> PluginChoice: """One config read for a listing, through the uncopied cached view (the result is never changed); *selection_key* is the category's config path (``"memory", "provider"``), none when only the plugin lists matter. A selection in *builtin* picks the category's built-in, which loads no plugin, so it selects nothing here. A config.yaml that does not parse reads as its last good copy when one was kept, else as the defaults; only a read that raises means nothing is selected, enabled or disabled.""" try: from hermes_cli.config import cfg_get, load_config_readonly config = load_config_readonly() selected = cfg_get(config, *selection_key) if selection_key else "" lists = [cfg_get(config, "plugins", key) for key in ("enabled", "disabled")] except Exception: # health: allow BLE001 -- same boundary as the memory check it replaces: a config read that raises turns nothing on or off return PluginChoice() enabled, disabled = (frozenset(v for v in value if isinstance(v, str)) if isinstance(value, list) else frozenset() for value in lists) selected = selected.strip() if isinstance(selected, str) else "" return PluginChoice("" if selected in builtin else selected, enabled, disabled) def list_category(dirs, choice: PluginChoice, is_bundled: Callable, load: Callable) -> list[tuple[str, str, bool]]: """Listing rows: a bundled or turned-on plugin is loaded and probed, any other described from its manifest.""" return [(name, read_plugin_description(child), probe_availability(lambda c=child: load(c))) if is_bundled(child) or choice.allows_import(child, name) else describe_without_import(name, child) for name, child in dirs] def describe_without_import(name: str, plugin_dir: Path) -> tuple[str, str, bool]: """A listing row for a user plugin that is not turned on: manifest description, not available.""" return name, read_plugin_description(plugin_dir), False def enable_command(name: str) -> str: """``plugins enable`` for the active home from any shell, so HERMES_HOME names that home. A profile-shaped HERMES_HOME already beats the sticky profile; any other home needs ``-p default``, which resolves to HERMES_HOME itself (:func:`hermes_cli.profiles.profile_root_for_env_home`).""" from hermes_cli.profiles import profile_root_for_env_home from hermes_constants import get_hermes_home home = get_hermes_home() selector = "" if profile_root_for_env_home(str(home), home) != home else "-p default " return f"`hermes {selector}plugins enable {name}` with HERMES_HOME set to {home}" def refused_as_disabled(name: str, plugin_dir: Path, *, bundled: bool, kind: str, logger: logging.Logger) -> bool: """True (after a warning naming the way back) when a selected NON-bundled provider is parked in ``plugins.disabled``: a turned-off plugin stays off even when a category key still names it.""" if bundled or not read_plugin_choice().is_disabled(plugin_dir, name): return False logger.warning("⚠ %s '%s' is turned off: plugins.disabled lists it. Turn it back on with %s.", kind, name, enable_command(name)) return True def _new_module(name: str, file: Path, search_locations: Optional[list[str]] = None) -> Optional[Any]: """spec -> module -> sys.modules[name] (NOT executed); None if no spec.""" spec = importlib.util.spec_from_file_location( name, str(file), submodule_search_locations=search_locations) if not spec: return None mod = importlib.util.module_from_spec(spec) sys.modules[name] = mod return mod def _exec(mod: Any, logger: Optional[logging.Logger] = None) -> bool: """Exec a ``_new_module`` module (None -> False); False + debug-log if it raised. The sys.modules entry stays on failure; callers needing a clean retry pop it themselves.""" if mod is None: return False try: mod.__spec__.loader.exec_module(mod) return True except Exception as e: if logger: logger.debug("Failed to exec_module %s: %s", mod.__name__, e) return False def _exec_parent_shell(parent: str) -> None: """Exec the ``__init__.py`` of an importable parent package that is not loaded yet.""" if parent in sys.modules: return spec = importlib.util.find_spec(parent) if spec is not None and spec.has_location and spec.submodule_search_locations: _exec(_new_module(parent, Path(spec.origin), list(spec.submodule_search_locations))) def load_plugin_module(module_name: str, plugin_dir: Path, *, parents: tuple[str, ...], logger: logging.Logger, synthetic_namespace: Optional[str] = None) -> Optional[Any]: """Import ``plugin_dir/__init__.py`` as *module_name* (reusing sys.modules when loaded); None when there is no ``__init__.py`` or the load is refused, and the package's own exception when it fails to import. Order matters: parents first (relative imports need them), then siblings as ``module_name.`` (so ``from ._x import Y`` resolves), then the module. Finally child is bound onto parent and siblings onto module — the shape normal imports produce, which monkeypatch relies on.""" init_file = plugin_dir / "__init__.py" if not init_file.exists(): return None if synthetic_namespace: # user code: never imported in-process under plugins.isolation: host from hermes_cli.plugin_isolation import in_process_import_refusal refusal = in_process_import_refusal(f"plugin {plugin_dir.name!r} (loaded as {module_name})") if refusal: logger.warning("%s", refusal) return None # _new_module publishes a package shell before executing it so sibling relative # imports work. Serialize the complete load so another thread cannot observe # that half-built shell as a loaded plugin. # The wait polls for a cross-thread cycle through importlib's module locks; in a cycle, accept the # partial module like importlib does. It is bounded only inside bounded_load_wait() (per-turn callers). lock, me = _module_load_lock(module_name), threading.get_ident() deadline = float("inf") if not _BOUNDED_WAIT.get() else time.monotonic() + ( 0 if module_name in _STALLED_LOADS else _CONCURRENT_LOAD_WAIT_SECS) _LOAD_WAITERS[me] = module_name try: while not lock.acquire(timeout=0.05): if _load_would_deadlock(me): logger.debug("Concurrent circular load of %s; using the partial module", module_name) return sys.modules.get(module_name) if time.monotonic() >= deadline: _STALLED_LOADS.add(module_name) logger.warning("Skipping plugin %s: another thread's load of it has not finished " "(import still running after %.0fs)", module_name, _CONCURRENT_LOAD_WAIT_SECS) return None finally: _LOAD_WAITERS.pop(me, None) outermost = module_name not in _LOAD_OWNERS # the RLock re-enters on this thread's recursive loads _LOAD_OWNERS.setdefault(module_name, me) try: return _load_plugin_module_locked(module_name, plugin_dir, init_file, parents, logger, synthetic_namespace) finally: if outermost: _LOAD_OWNERS.pop(module_name, None) _STALLED_LOADS.discard(module_name) lock.release() def _load_plugin_module_locked(module_name: str, plugin_dir: Path, init_file: Path, parents: tuple[str, ...], logger: logging.Logger, synthetic_namespace: Optional[str]) -> Optional[Any]: # A synthetic package shell has no __file__; only reuse modules loaded from disk. cached = sys.modules.get(module_name) if cached is not None and getattr(cached, "__file__", None): return cached for parent in parents: _exec_parent_shell(parent) if synthetic_namespace: register_synthetic_package(synthetic_namespace, []) # Reserve the name before siblings exec so their relative imports resolve. mod = _new_module(module_name, init_file, [str(plugin_dir)]) if mod is None: return None loaded_submodules = [] for sub_file in plugin_dir.glob("*.py"): full_sub_name = f"{module_name}.{sub_file.stem}" if sub_file.name == "__init__.py" or full_sub_name in sys.modules: continue sub_mod = _new_module(full_sub_name, sub_file) if _exec(sub_mod, logger): loaded_submodules.append((sub_file.stem, sub_mod)) else: sys.modules.pop(full_sub_name, None) _exec_package(mod, module_name) parent_name, child_name = module_name.rsplit(".", 1) parent_mod = sys.modules.get(parent_name) if parent_mod is not None: setattr(parent_mod, child_name, mod) for sub_name, sub_mod in loaded_submodules: setattr(mod, sub_name, sub_mod) return mod def _exec_package(mod: Any, module_name: str) -> None: """Exec the plugin's own ``__init__.py``; on failure drop it from sys.modules and re-raise, so the caller's log line names the real error (a missing core module, a bad dependency) instead of none.""" try: mod.__spec__.loader.exec_module(mod) except BaseException: sys.modules.pop(module_name, None) raise class NoopPluginContext: """Base for fake ``register(ctx)`` contexts: no-op registrations except the one a subclass overrides.""" def _noop(self, *args, **kwargs): pass register_tool = register_hook = register_cli_command = register_memory_provider = _noop def instance_from_module(mod: Any, *, collector: Any, collected_attr: str, base_cls: type, name: str, logger: logging.Logger) -> Optional[Any]: """Extract the provider instance: ``register(ctx)`` first, then any ``base_cls`` subclass.""" if hasattr(mod, "register"): try: mod.register(collector) instance = getattr(collector, collected_attr) if instance: return instance except Exception as e: logger.debug("register() failed for %s: %s", name, e) for attr_name in dir(mod): attr = getattr(mod, attr_name, None) if isinstance(attr, type) and issubclass(attr, base_cls) and attr is not base_cls: with contextlib.suppress(Exception): return attr() return None def load_named(name: str, plugin_dir: Path, load_from_dir: Callable[[Path], Optional[Any]], *, kind: str, noun: str, logger: logging.Logger) -> Optional[Any]: """Shared body of ``load_(name)``: load from *plugin_dir*, warn + None on failure.""" try: instance = load_from_dir(plugin_dir) except Exception as e: logger.warning("Failed to load %s '%s': %s", kind.lower(), name, e) return None if not instance: logger.warning("%s '%s' loaded but no %s instance found", kind, name, noun) return instance or None def probe_availability(load: Callable[[], Optional[Any]]) -> bool: """True iff *load()* returns an instance whose ``is_available()`` (if any) is truthy.""" try: instance = load() return instance is not None and (instance.is_available() if hasattr(instance, "is_available") else True) except Exception: return False