Skip to content

The agent that grows with you

fix: resolve user-installed context engines from $HERMES_HOME/plugins/<name>

teknium1913c045c5380
diff --git a/plugins/context_engine/__init__.py b/plugins/context_engine/__init__.py
index dee2c5da372..9468a3827f0 100644
--- a/plugins/context_engine/__init__.py
+++ b/plugins/context_engine/__init__.py
@@ -1,6 +1,8 @@
-"""Context engine plugin discovery: ``plugins/context_engine/<name>/`` → ``ContextEngine``.
-Engines ship in the repo, separate from the general plugin system; only one is active
-(``context.engine`` in config.yaml; default ``"compressor"``, the built-in ContextCompressor)."""
+"""Context engine plugin discovery: bundled ``plugins/context_engine/<name>/`` then user
+``$HERMES_HOME/plugins/<name>/`` (bundled wins on collision) → ``ContextEngine``. Separate from the
+general plugin system: ``context.engine`` in config.yaml names the active engine (default
+``"compressor"``, the built-in ContextCompressor), so a user-installed engine needs no
+``plugins.enabled`` entry to be selectable."""
from __future__ import annotations
@@ -13,20 +15,53 @@ from plugins import plugin_loader as _loader
logger = logging.getLogger(__name__)
_CONTEXT_ENGINE_PLUGINS_DIR = Path(__file__).parent
+# Synthetic parent package for user-installed engines (keeps them out of the bundled namespace).
+_USER_NAMESPACE = "_hermes_user_context_engine"
+
+
+def _is_context_engine_dir(path: Path) -> bool:
+ """Cheap text heuristic: ``__init__.py`` mentions the context engine contract."""
+ init_file = path / "__init__.py"
+ try:
+ source = init_file.read_text(errors="replace", encoding="utf-8")[:8192]
+ except OSError:
+ return False
+ return "register_context_engine" in source or "ContextEngine" in source
+
+
+def _iter_engine_dirs() -> List[Tuple[str, Path]]:
+ """``(name, path)`` for bundled then user engines; bundled wins on collisions."""
+ dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)]
+ seen = {name for name, _ in dirs}
+ user_dir = _loader.user_plugins_dir()
+ if user_dir:
+ dirs.extend((child.name, child) for child in _loader.iter_plugin_dirs(user_dir)
+ if child.name not in seen and _is_context_engine_dir(child))
+ return dirs
def discover_context_engines() -> List[Tuple[str, str, bool]]:
- """Return ``[(name, description, is_available), ...]`` for every bundled engine."""
- return [(child.name, _loader.read_plugin_description(child),
+ """Return ``[(name, description, is_available), ...]`` for every bundled and user engine."""
+ return [(name, _loader.read_plugin_description(child),
_loader.probe_availability(lambda c=child: _load_engine_from_dir(c)))
- for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)]
+ for name, child in _iter_engine_dirs()]
+
+
+def find_engine_dir(name: str) -> Optional[Path]:
+ """Resolve an engine name to its directory (bundled first, then user-installed)."""
+ bundled = _CONTEXT_ENGINE_PLUGINS_DIR / name
+ if bundled.is_dir():
+ return bundled
+ user_dir = _loader.user_plugins_dir()
+ user = user_dir / name if user_dir else None
+ return user if user and user.is_dir() and _is_context_engine_dir(user) else None
def load_context_engine(name: str) -> Optional["ContextEngine"]: # noqa: F821
"""Load a ContextEngine instance by name; None if not found or it fails to load."""
- engine_dir = _CONTEXT_ENGINE_PLUGINS_DIR / name
- if not engine_dir.is_dir():
- logger.debug("Context engine '%s' not found in %s", name, _CONTEXT_ENGINE_PLUGINS_DIR)
+ engine_dir = find_engine_dir(name)
+ if engine_dir is None:
+ logger.debug("Context engine '%s' not found in bundled or user plugins", name)
return None
return _loader.load_named(
name, engine_dir, _load_engine_from_dir, kind="Context engine", noun="engine", logger=logger
@@ -37,9 +72,11 @@ def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]: # noq
"""Import an engine module and extract its ContextEngine (register(ctx) or subclass)."""
from agent.context_engine import ContextEngine
name = engine_dir.name
+ is_bundled = engine_dir.parent == _CONTEXT_ENGINE_PLUGINS_DIR
+ module_name = f"plugins.context_engine.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}"
mod = _loader.load_plugin_module(
- f"plugins.context_engine.{name}", engine_dir,
- parents=("plugins", "plugins.context_engine"), logger=logger)
+ module_name, engine_dir, parents=("plugins", "plugins.context_engine"), logger=logger,
+ synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
return mod and _loader.instance_from_module(
mod, collector=_EngineCollector(engine_name=name), collected_attr="engine",
base_cls=ContextEngine, name=name, logger=logger)
diff --git a/tests/plugins/test_context_engine_user_dir.py b/tests/plugins/test_context_engine_user_dir.py
new file mode 100644
index 00000000000..1206cd277b7
--- /dev/null
+++ b/tests/plugins/test_context_engine_user_dir.py
@@ -0,0 +1,44 @@
+"""``context.engine: <name>`` names the active engine, so an engine dropped into
+``$HERMES_HOME/plugins/<name>/`` loads without a ``plugins.enabled`` entry and never trips the
+"Context engine 'X' not found — falling back to built-in compressor" warning (#61839)."""
+
+import logging
+from pathlib import Path
+from textwrap import dedent
+
+_ENGINE_SRC = dedent('''
+ from agent.context_engine import ContextEngine
+
+ class Demo(ContextEngine):
+ @property
+ def name(self):
+ return "ctx_demo"
+ def update_from_response(self, usage):
+ pass
+ def should_compress(self, prompt_tokens=None):
+ return False
+ def compress(self, messages, current_tokens=None):
+ return messages
+
+ def register(ctx):
+ ctx.register_context_engine(Demo())
+''')
+
+
+def test_user_installed_engine_is_selected_by_name(tmp_path: Path, monkeypatch, caplog):
+ engine_dir = tmp_path / "plugins" / "ctx_demo"
+ engine_dir.mkdir(parents=True)
+ (engine_dir / "__init__.py").write_text(_ENGINE_SRC)
+ (tmp_path / "plugins" / "notes").mkdir() # unrelated user plugin: never treated as an engine
+ (tmp_path / "plugins" / "notes" / "__init__.py").write_text("def register(ctx): pass\n")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+
+ from agent.agent_init import _select_context_engine
+ from plugins.context_engine import discover_context_engines, load_context_engine
+
+ assert load_context_engine("notes") is None
+ assert "ctx_demo" in {name for name, _, _ in discover_context_engines()}
+ with caplog.at_level(logging.WARNING, logger="run_agent"):
+ engine = _select_context_engine({"context": {"engine": "ctx_demo"}})
+ assert engine is not None and engine.name == "ctx_demo"
+ assert "not found" not in caplog.text
diff --git a/website/docs/developer-guide/context-engine-plugin.md b/website/docs/developer-guide/context-engine-plugin.md
index 6403818a258..d124ce46d9b 100644
--- a/website/docs/developer-guide/context-engine-plugin.md
+++ b/website/docs/developer-guide/context-engine-plugin.md
@@ -191,7 +191,7 @@ Engine tools are injected into the agent's tool list at startup and dispatched a
### Via directory (recommended)
-Place your engine in `plugins/context_engine/<name>/`. The `__init__.py` must export a `ContextEngine` subclass. The discovery system finds and instantiates it automatically.
+Place your engine in `plugins/context_engine/<name>/` (bundled) or `~/.hermes/plugins/<name>/` (user-installed; `$HERMES_HOME/plugins/<name>/`). The `__init__.py` must export a `ContextEngine` subclass or a `register(ctx)` that calls `ctx.register_context_engine(...)`. Setting `context.engine: <name>` is the activation — a user-installed engine does not need a `plugins.enabled` entry. Bundled names win on collision.
### Via general plugin system