__init__.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """Context engine plugin discovery: bundled ``plugins/context_engine/<name>/`` then user
  2. ``$HERMES_HOME/plugins/<name>/`` (bundled wins on collision) → ``ContextEngine``. Separate from the
  3. general plugin system: ``context.engine`` in config.yaml names the active engine (default
  4. ``"compressor"``, the built-in ContextCompressor), so a user-installed engine needs no
  5. ``plugins.enabled`` entry to be selectable."""
  6. from __future__ import annotations
  7. import logging
  8. from pathlib import Path
  9. from typing import List, Optional, Tuple
  10. from plugins import plugin_loader as _loader
  11. logger = logging.getLogger(__name__)
  12. _CONTEXT_ENGINE_PLUGINS_DIR = Path(__file__).parent
  13. # Synthetic parent package for user-installed engines (keeps them out of the bundled namespace).
  14. _USER_NAMESPACE = "_hermes_user_context_engine"
  15. def _is_context_engine_dir(path: Path) -> bool:
  16. """Cheap text heuristic: ``__init__.py`` mentions the context engine contract."""
  17. init_file = path / "__init__.py"
  18. try:
  19. source = init_file.read_text(errors="replace", encoding="utf-8-sig")[:8192]
  20. except OSError:
  21. return False
  22. return "register_context_engine" in source or "ContextEngine" in source
  23. def _iter_engine_dirs() -> list[tuple[str, Path]]:
  24. """``(name, path)`` for bundled then user engines; bundled wins on collisions."""
  25. dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)]
  26. seen = {name for name, _ in dirs}
  27. user_dir = _loader.user_plugins_dir()
  28. if user_dir:
  29. dirs.extend((child.name, child) for child in _loader.iter_plugin_dirs(user_dir)
  30. if child.name not in seen and _is_context_engine_dir(child))
  31. return dirs
  32. def discover_context_engines() -> list[tuple[str, str, bool]]:
  33. """Return ``[(name, description, is_available), ...]`` for every bundled and user engine."""
  34. return [(name, _loader.read_plugin_description(child),
  35. _loader.probe_availability(lambda c=child: _load_engine_from_dir(c)))
  36. for name, child in _iter_engine_dirs()]
  37. def find_engine_dir(name: str) -> Optional[Path]:
  38. """Resolve an engine name to its directory (bundled first, then user-installed)."""
  39. bundled = _CONTEXT_ENGINE_PLUGINS_DIR / name
  40. if bundled.is_dir():
  41. return bundled
  42. user_dir = _loader.user_plugins_dir()
  43. user = user_dir / name if user_dir else None
  44. return user if user and user.is_dir() and _is_context_engine_dir(user) else None
  45. def load_context_engine(name: str) -> Optional[ContextEngine]:
  46. """Load a ContextEngine instance by name; None if not found or it fails to load."""
  47. engine_dir = find_engine_dir(name)
  48. if engine_dir is None:
  49. logger.debug("Context engine '%s' not found in bundled or user plugins", name)
  50. return None
  51. return _loader.load_named(
  52. name, engine_dir, _load_engine_from_dir, kind="Context engine", noun="engine", logger=logger
  53. )
  54. def _load_engine_from_dir(engine_dir: Path) -> Optional[ContextEngine]:
  55. """Import an engine module and extract its ContextEngine (register(ctx) or subclass)."""
  56. from agent.context_engine import ContextEngine
  57. name = engine_dir.name
  58. is_bundled = engine_dir.parent == _CONTEXT_ENGINE_PLUGINS_DIR
  59. module_name = f"plugins.context_engine.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}"
  60. from hermes_cli.plugin_isolation import user_plugin_host
  61. host = None if is_bundled else user_plugin_host()
  62. if host is not None:
  63. return host.load_instance(engine_dir, module_name=module_name, capture="register_context_engine",
  64. base_ref="agent.context_engine:ContextEngine")
  65. mod = _loader.load_plugin_module(
  66. module_name, engine_dir, parents=("plugins", "plugins.context_engine"), logger=logger,
  67. synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
  68. return mod and _loader.instance_from_module(
  69. mod, collector=_EngineCollector(engine_name=name), collected_attr="engine",
  70. base_cls=ContextEngine, name=name, logger=logger)
  71. class _EngineCollector(_loader.NoopPluginContext):
  72. """Captures register_context_engine; forwards register_command to the global plugin command
  73. registry so engine slash commands behave like plugin ones."""
  74. def __init__(self, engine_name: str = ""):
  75. self.engine = None
  76. self._engine_name = engine_name or "context_engine"
  77. def register_context_engine(self, engine):
  78. self.engine = engine
  79. def register_command(self, name: str, handler, description: str = "", args_hint: str = "") -> None:
  80. clean = (name or "").lower().strip().lstrip("/").replace(" ", "-")
  81. if not clean:
  82. logger.warning("Context engine '%s' tried to register a command with an empty name.",
  83. self._engine_name)
  84. return
  85. conflict = "Context engine '%s' tried to register command '/%s' which %s Skipping."
  86. try:
  87. from hermes_cli.commands import resolve_command
  88. if resolve_command(clean) is not None:
  89. logger.warning(conflict, self._engine_name, clean, "conflicts with a built-in command.")
  90. return
  91. except Exception:
  92. pass
  93. try:
  94. from hermes_cli.plugins import get_plugin_manager
  95. manager = get_plugin_manager()
  96. if clean in manager._plugin_commands:
  97. logger.warning(conflict, self._engine_name, clean, "is already registered by a plugin.")
  98. return
  99. manager._plugin_commands[clean] = {
  100. "handler": handler, "description": description or "Context engine command",
  101. "plugin": f"context-engine:{self._engine_name}", "args_hint": (args_hint or "").strip()}
  102. logger.debug("Context engine '%s' registered command: /%s", self._engine_name, clean)
  103. except Exception as exc:
  104. logger.debug("Context engine '%s' could not register /%s: %s", self._engine_name, clean, exc)