The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): say restart when a running process cannot import new plugin deps
Ben Barclaydc1f72689d52
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 8593c209e60..6d5f56d7978 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4390,7 +4390,7 @@ export interface PluginsManageParams {names?: string[] | null}export type PluginsAction = 'list' | 'toggle' | 'install' | 'update' | 'remove' | 'settings' | 'onboarding' | 'presence'-/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is live now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities`` — or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` / ``scan_findings`` (retry a caution verdict with ``force``); ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */+/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the running gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is live now vs deferred, so ``restart_required`` is True only when no gateway answered or the running gateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities`` — or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` / ``scan_findings`` (retry a caution verdict with ``force``); ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */export interface PluginsManageResult {plugins?: AgentPluginRow[] | nulluser_count?: number | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 682d5f53a13..039584006d6 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27693,7 +27693,7 @@},"PluginsManageResult": {"additionalProperties": false,- "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities`` \u2014 or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` /\n``scan_findings`` (retry a caution verdict with ``force``); ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.",+ "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered or the running\ngateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities`` \u2014 or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` /\n``scan_findings`` (retry a caution verdict with ``force``); ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.","properties": {"plugins": {"anyOf": [diff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.pyindex 80639ed26be..97c653dc06a 100644--- a/hermes_cli/plugins_activation.py+++ b/hermes_cli/plugins_activation.py@@ -71,7 +71,13 @@ def plugin_activation_summary(manager: Any, plugin_key: str) -> dict[str, Any]:s for s, owner in manager._portable_mcp_server_plugins.items() if owner == plugin_key})if servers:deferred["mcp_servers"] = servers- return {"name": name, "key": plugin_key, "activated_now": now, "deferred": deferred}+ summary = {"name": name, "key": plugin_key, "activated_now": now, "deferred": deferred}+ # Read in the process that loaded the plugin (for a gateway answer, the gateway): a dependency+ # installed after it booted is not importable there until it restarts.+ from hermes_cli.plugins_loader import missing_python_dependencies+ if missing := missing_python_dependencies(manifest):+ summary["missing_dependencies"] = missing+ return summarydef activation_summaries(manager: Any) -> list[dict[str, Any]]:@@ -103,17 +109,25 @@ def activate_plugin_now(name: str, *, in_process: bool = True) -> dict[str, Any]Returns ``{"gateway_reloaded": bool, "activation": summary | None, "restart_required": bool}``.``activation.live_now`` lists what is usable in open chats now; ``activation.deferred`` what waits- for the next session. ``restart_required`` is True only when no gateway answered (old gateway, not- running)."""+ for the next session. ``restart_required`` is True when no gateway answered (old gateway, not+ running), or when this process or the gateway cannot import the plugin's Python dependencies+ (``activation.missing_dependencies``): a running process never switches to the dependency+ generation an enable just installed, so only a restart loads them."""from hermes_constants import get_hermes_homeactivation: Optional[dict[str, Any]] = load_and_go_live(name) if in_process else Noneif not in_process:activation = (notify_serve_backend(name, Path(get_hermes_home())) or {}).get("activation")answer = reload_running_gateway()reloaded = bool(answer and answer.get("reloaded"))+ gateway_activation = find_activation((answer or {}).get("activations"), name) if reloaded else Noneif reloaded and activation is None:- activation = find_activation((answer or {}).get("activations"), name)- return {"gateway_reloaded": reloaded, "activation": activation, "restart_required": not reloaded}+ activation = gateway_activation+ missing = sorted({*((activation or {}).get("missing_dependencies") or ()),+ *((gateway_activation or {}).get("missing_dependencies") or ())})+ if missing:+ activation = {**(activation or {"name": name, "key": name}), "missing_dependencies": missing}+ return {"gateway_reloaded": reloaded, "activation": activation,+ "restart_required": not reloaded or bool(missing)}def reload_running_gateway() -> Optional[dict[str, Any]]:@@ -241,6 +255,18 @@ def _gateway_present() -> bool:or _installed_service_kind() is not None)+def dependency_restart_hint(missing: list[str]) -> str:+ """What to do when the running gateway / backend cannot import a plugin's dependencies."""+ from hermes_cli.plugins_loader import installed_in_selected_environment+ deps = ", ".join(missing)+ if installed_in_selected_environment(missing):+ return (f"Its Python dependencies ({deps}) were installed after the running gateway or dashboard "+ "started, and a running process never switches dependency environments. Restart them to "+ "load the plugin:\n hermes gateway restart")+ return (f"Its Python dependencies ({deps}) are not installed. Run hermes pm repair, then restart:\n"+ " hermes gateway restart")++def report_activation(console, name: str) -> None:"""After a CLI install/enable: load *name* where it can go live now (:func:`activate_plugin_now`)and print :func:`activation_hint`, or nothing when there is nothing to say."""@@ -260,6 +286,8 @@ def activation_hint(result: dict[str, Any]) -> str:lines.append(f"Live in open chats now: {tools} MCP tools, {len(live.get('skills') or ())} skills.")lines.extend(f"MCP server {s['name']} not connected: {s.get('error') or 'unknown error'}"for s in live.get("mcp_servers") or () if not s.get("connected"))+ if missing := act.get("missing_dependencies"):+ return "\n".join([*lines, dependency_restart_hint(missing)])if not result.get("gateway_reloaded"):# Live in open chats, or no gateway runs or is installed for this profile (first-time setup):# a messaging gateway that starts later loads it at boot, so a restart applies to nothing.diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 0a9e8e50bbd..ab54065d995 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -197,9 +197,13 @@ def _load_error_text(exc: BaseException) -> str:return str(exc)+def _dist_name(req: str) -> str:+ return re.split(r"[<>=!~\[;\s]", req, maxsplit=1)[0].strip()++def _dist_installed(req: str) -> Optional[bool]:"""Best-effort presence probe on a requirement's distribution name; ``None`` when unprobeable."""- dist = re.split(r"[<>=!~\[;\s]", req, maxsplit=1)[0].strip()+ dist = _dist_name(req)if not dist:return Nonetry:@@ -211,6 +215,31 @@ def _dist_installed(req: str) -> Optional[bool]:return None+def missing_python_dependencies(manifest: Any) -> list[str]:+ """The plugin's declared ``python_dependencies`` this process cannot import."""+ return [req for req in getattr(manifest, "python_dependencies", None) or ()+ if _dist_installed(req) is False]+++def installed_in_selected_environment(requirements: list[str]) -> bool:+ """Whether every one of *requirements* is in the dependency environment PM currently selects.++ Activation is a boot decision (``pm.environments.activate_dependencies``): a gateway or dashboard+ that was running when ``hermes plugins enable`` committed a new generation keeps the old one. A+ requirement it cannot import that the selected generation carries therefore needs a restart, not+ a repair. False when unknown."""+ try:+ from pm.environments import selected_venv, site_packages+ from pm.paths import repo_root++ site = str(site_packages(selected_venv(repo_root())))+ return bool(requirements) and all(+ next(iter(importlib.metadata.distributions(name=_dist_name(req), path=[site])), None) is not None+ for req in requirements)+ except (OSError, RuntimeError, ValueError): # unreadable or invalid selection record+ return False++class PluginLoaderMixin:def on_plugin_loaded(self, callback: Callable[[list[dict[str, Any]]], Any]) -> Callable[[], None]:"""Subscribe to "a discovery sweep loaded plugins this process did not have": fires from INSIDE@@ -434,8 +463,15 @@ class PluginLoaderMixin:if not deps:returnkey = manifest_key(manifest)- missing = [req for req in deps if _dist_installed(req) is False]- if missing:+ missing = missing_python_dependencies(manifest)+ if missing and installed_in_selected_environment(missing):+ logger.warning(+ "Plugin %s's Python dependencies were installed after this process started: %s. "+ "A running process never switches dependency environments; restart Hermes "+ "(hermes gateway restart for the gateway) to load them.",+ key, ", ".join(missing),+ )+ elif missing:logger.warning("Plugin %s declares Python dependencies that are not ""installed: %s. For an enabled plugin, run hermes pm repair, "diff --git a/tests/hermes_cli/test_plugin_dependency_restart.py b/tests/hermes_cli/test_plugin_dependency_restart.pynew file mode 100644index 00000000000..7136b9c9e62--- /dev/null+++ b/tests/hermes_cli/test_plugin_dependency_restart.py@@ -0,0 +1,148 @@+"""A plugin whose Python dependencies were installed after a process booted needs a restart there.++``hermes plugins enable`` commits a new dependency generation and nudges the running gateway to+reload its plugins. Activation is a boot decision, so that gateway (and a running dashboard) keeps+the generation it booted with and cannot import the new dependencies. Enable used to report+"Gateway reloaded plugins; nothing of this plugin needs a session or restart", and discovery+logged "run hermes pm repair" — on a hosted container the terminal backend then failed with+``No module named '<dep>'`` until something restarted the gateway. The honest answer is: restart.+"""++from __future__ import annotations++import json+import logging+from pathlib import Path++import pytest++from hermes_cli import plugins_activation+from hermes_cli.plugins_loader import installed_in_selected_environment, missing_python_dependencies++DIST = "hermes-depprobe-fixture"+REQ = f"{DIST}>=1.0,<2"+++def _select_generation(home: Path, *, with_dist: bool) -> Path:+ """Commit a PM selection for this checkout under *home*, the way a sync leaves it."""+ from pm.environments import install_state_dir, runtime_facts_path, site_packages+ from pm.paths import repo_root++ venv = install_state_dir(repo_root()) / "environments" / "gen1" / "venv"+ venv.mkdir(parents=True)+ (venv / "pyvenv.cfg").write_text("home = /nonexistent\n", encoding="utf-8")+ site = site_packages(venv)+ site.mkdir(parents=True)+ if with_dist:+ info = site / f"{DIST.replace('-', '_')}-1.0.dist-info"+ info.mkdir()+ (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {DIST}\nVersion: 1.0\n", encoding="utf-8")+ facts = runtime_facts_path(repo_root())+ facts.write_text(json.dumps({"schema": 1, "packages": {"venv": {"environment": str(venv)}}}),+ encoding="utf-8")+ return site+++def home(tmp_path, monkeypatch):+ hermes_home = tmp_path / "hermes-home"+ plugin = hermes_home / "plugins" / "depprobe"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text(+ f"name: depprobe\nversion: '1.0'\npython_dependencies:\n - '{REQ}'\n", encoding="utf-8")+ (plugin / "__init__.py").write_text("def register(ctx):\n pass\n", encoding="utf-8")+ (hermes_home / "config.yaml").write_text("plugins:\n enabled: [depprobe]\n disabled: []\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ return hermes_home+++def _discover(caplog):+ from hermes_cli import plugins++ plugins._reset_plugin_managers_for_tests()+ caplog.clear()+ with caplog.at_level(logging.WARNING, logger="hermes_cli.plugins"):+ plugins.discover_plugins(force=True)+ manager = plugins.get_plugin_manager()+ messages = [r.getMessage() for r in caplog.records if "depprobe" in r.getMessage()]+ return manager, messages+++def test_discovery_says_restart_when_the_selected_generation_has_the_dependency(home, caplog):+ _select_generation(home, with_dist=True)+ try:+ manager, messages = _discover(caplog)+ assert any("installed after this process started" in m and "restart" in m for m in messages), messages+ assert not any("pm repair" in m for m in messages), messages+ summary = plugins_activation.plugin_activation_summary(manager, "depprobe")+ assert summary["missing_dependencies"] == [REQ]+ finally:+ from hermes_cli import plugins+ plugins._reset_plugin_managers_for_tests()+++def test_discovery_keeps_the_repair_remedy_when_nothing_installed_it(home, caplog):+ _select_generation(home, with_dist=False)+ try:+ _manager, messages = _discover(caplog)+ assert any("not installed" in m and "pm repair" in m for m in messages), messages+ finally:+ from hermes_cli import plugins+ plugins._reset_plugin_managers_for_tests()+++def test_an_importable_dependency_is_not_reported(home, monkeypatch):+ site = _select_generation(home, with_dist=True)+ monkeypatch.syspath_prepend(str(site))+ from hermes_cli.plugins import PluginManifest++ manifest = PluginManifest(name="depprobe", python_dependencies=[REQ])+ assert missing_python_dependencies(manifest) == []+++def _gateway_answers(monkeypatch, activations):+ monkeypatch.setattr("gateway.control_socket.reload_gateway_plugins",+ lambda target, *, profile_home=None, timeout=30.0:+ {"reloaded": True, "plugins": ["depprobe"], "activations": activations})+ monkeypatch.setattr(plugins_activation, "notify_serve_backend", lambda name, home: None)+++def test_enable_reports_restart_when_the_running_gateway_cannot_import_the_dependency(home, monkeypatch):+ """The live symptom: the gateway reloaded, but it booted before the dependency existed."""+ _select_generation(home, with_dist=True)+ _gateway_answers(monkeypatch, [{"name": "depprobe", "key": "depprobe", "activated_now": {},+ "deferred": {}, "missing_dependencies": [REQ]}])++ result = plugins_activation.activate_plugin_now("depprobe", in_process=False)+ hint = plugins_activation.activation_hint(result)++ assert result["gateway_reloaded"] is True+ assert result["restart_required"] is True+ assert result["activation"]["missing_dependencies"] == [REQ]+ assert "nothing of this plugin needs" not in hint+ assert "installed after the running gateway" in hint and "hermes gateway restart" in hint+++def test_enable_reports_repair_when_the_dependency_was_never_installed(home, monkeypatch):+ _select_generation(home, with_dist=False)+ _gateway_answers(monkeypatch, [{"name": "depprobe", "key": "depprobe", "activated_now": {},+ "deferred": {}, "missing_dependencies": [REQ]}])++ hint = plugins_activation.activation_hint(plugins_activation.activate_plugin_now("depprobe", in_process=False))++ assert "pm repair" in hint+++def test_enable_needs_no_restart_when_the_gateway_imports_everything(home, monkeypatch):+ _select_generation(home, with_dist=True)+ _gateway_answers(monkeypatch, [{"name": "depprobe", "key": "depprobe", "activated_now": {},+ "deferred": {}}])++ result = plugins_activation.activate_plugin_now("depprobe", in_process=False)++ assert result["restart_required"] is False+ assert "nothing of this plugin needs" in plugins_activation.activation_hint(result)+++def test_selected_generation_probe_is_false_without_a_selection(home):+ assert installed_in_selected_environment([REQ]) is Falsediff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 594e757c708..0ff35281711 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -795,7 +795,8 @@ class PluginsManageResult(Result):(the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'sok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (therunning gateway picked it up and re-wired its handlers) and ``activation`` — the honest split of what is- live now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the+ live now vs deferred, so ``restart_required`` is True only when no gateway answered or the running+ gateway/backend cannot import the plugin's Python dependencies (``activation.missing_dependencies``); ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until theclient retries with ``accept_capabilities`` — or ``ok=false`` + ``scan_blocked`` with ``scan_verdict`` /``scan_findings`` (retry a caution verdict with ``force``); ``remove`` → ``ok``/``name`` plus