The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): a plugin that fails on its new dependency still asks for a restart
Teknium57dcda137646
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 6d5f56d7978..d2e99944548 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4464,13 +4464,14 @@ export interface PluginSettingField {has_value?: boolean | null}export type PluginSettingFieldType = 'string' | 'number' | 'boolean' | 'enum' | 'secret' | 'json'-/** What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now`` kinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``locales`` (``<lang>.<surface>`` language-pack layers), ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded (``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the error) and skills, usable in every open chat of the profile from its next turn — the chats also get a note listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids) apply from the next session. */+/** What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now`` kinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``locales`` (``<lang>.<surface>`` language-pack layers), ``gateway_transforms`` / ``hooks`` (hook names), ``callbacks`` (platforms / ``slack:<action_id>``) — live in the running gateway once it reloaded (``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the error) and skills, usable in every open chat of the profile from its next turn — the chats also get a note listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids) apply from the next session. ``missing_dependencies``: the plugin's declared Python requirements the process that answered cannot import (installed after it booted, or never) — only a restart loads them. */export interface PluginActivation {name: stringkey: stringactivated_now?: Record<string, string[]>live_now?: PluginLiveNow | nulldeferred?: Record<string, string[]>+ missing_dependencies?: string[]}export interface PluginLiveNow {mcp_servers?: PluginLiveServer[]diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 039584006d6..c7d2481454d 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -27032,7 +27032,7 @@},"PluginActivation": {"additionalProperties": false,- "description": "What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now``\nkinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``locales`` (``<lang>.<surface>``\nlanguage-pack layers), ``gateway_transforms`` / ``hooks`` (hook\nnames), ``callbacks`` (platforms / ``slack:<action_id>``) \u2014 live in the running gateway once it reloaded\n(``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the\nerror) and skills, usable in every open chat of the profile from its next turn \u2014 the chats also get a\nnote listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids)\napply from the next session.",+ "description": "What a plugin loaded mid-run does NOW vs later (``hermes_cli.plugins_activation``). ``activated_now``\nkinds (``{kind: [names]}``): ``gateway_commands`` (slash names), ``locales`` (``<lang>.<surface>``\nlanguage-pack layers), ``gateway_transforms`` / ``hooks`` (hook\nnames), ``callbacks`` (platforms / ``slack:<action_id>``) \u2014 live in the running gateway once it reloaded\n(``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or the\nerror) and skills, usable in every open chat of the profile from its next turn \u2014 the chats also get a\nnote listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids)\napply from the next session. ``missing_dependencies``: the plugin's declared Python requirements the\nprocess that answered cannot import (installed after it booted, or never) \u2014 only a restart loads them.","properties": {"name": {"title": "Name",@@ -27072,6 +27072,13 @@},"title": "Deferred","type": "object"+ },+ "missing_dependencies": {+ "items": {+ "type": "string"+ },+ "title": "Missing Dependencies",+ "type": "array"}},"required": [diff --git a/gateway/run_plugin_rewire.py b/gateway/run_plugin_rewire.pyindex 1cb2dc480bd..ac4f7ea6635 100644--- a/gateway/run_plugin_rewire.py+++ b/gateway/run_plugin_rewire.py@@ -89,7 +89,7 @@ def reload_plugins_verb(runner: Any, loop: asyncio.AbstractEventLoop) -> Callabldef _handler(params: Optional[dict] = None) -> dict:from hermes_constants import get_hermes_home, hermes_home_keyfrom hermes_cli.plugins import discover_plugins, get_plugin_manager- from hermes_cli.plugins_activation import activation_summaries+ from hermes_cli.plugins_activation import activation_summaries, dependency_blocked_summariesfrom gateway.run import _profile_runtime_scopeparams = params or {}gateway_home = Path(get_hermes_home())@@ -108,7 +108,10 @@ def reload_plugins_verb(runner: Any, loop: asyncio.AbstractEventLoop) -> Callablwith scope:discover_plugins(force=True)manager = get_plugin_manager()- names, activations = sorted(manager._plugins), activation_summaries(manager)+ # A plugin that failed on a dependency this gateway booted without rides along, so the+ # enabling caller asks for the restart that loads it.+ names = sorted(manager._plugins)+ activations = activation_summaries(manager) + dependency_blocked_summaries(manager)try:rewired = asyncio.run_coroutine_threadsafe(_count_adapters(runner, profile_name), loop).result(timeout=5.0)except Exception:diff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.pyindex 97c653dc06a..d409d752f9f 100644--- a/hermes_cli/plugins_activation.py+++ b/hermes_cli/plugins_activation.py@@ -90,6 +90,22 @@ def activation_summaries(manager: Any) -> list[dict[str, Any]]:return out+def dependency_blocked_summaries(manager: Any) -> list[dict[str, Any]]:+ """Plugins that failed to load in this process while a declared Python dependency is not+ importable here, as ``{name, key, activated_now: {}, deferred: {}, missing_dependencies}``. A+ plugin importing a just-installed dependency at load time fails in a process booted before the+ install; without this entry the caller would read "loaded nothing, needs nothing" instead of+ "restart". Never part of the ``on_plugin_loaded`` payload: nothing of these plugins loaded."""+ from hermes_cli.plugins_loader import missing_python_dependencies+ out = []+ for key, loaded in list(manager._plugins.items()):+ manifest = getattr(loaded, "manifest", None)+ if getattr(loaded, "error", None) and (missing := missing_python_dependencies(manifest)):+ out.append({"name": getattr(manifest, "name", None) or key, "key": key, "activated_now": {},+ "deferred": {}, "missing_dependencies": missing})+ return out++def find_activation(summaries: Optional[list[dict[str, Any]]], name: str) -> Optional[dict[str, Any]]:"""The summary for ``name`` (manifest name, canonical key, or bare leaf of the key)."""for entry in summaries or ():@@ -168,7 +184,9 @@ def load_and_go_live(name: str) -> Optional[dict[str, Any]]:"""Force-rediscover plugins in THIS process under the caller's profile scope, connect ``name``'sMCP servers and hand them (and its skills) to this profile's open chats with a turn note. Returnsthe activation summary with ``live_now: {mcp_servers, skills}``; ``deferred`` then keeps only what- waits for the next session (Python ``tools``, ``prompt``). None when the plugin did not load."""+ waits for the next session (Python ``tools``, ``prompt``). None when the plugin did not load, except+ a load that failed on a dependency this process cannot import: that returns the+ :func:`dependency_blocked_summaries` entry, so the caller asks for a restart."""# A forced rediscovery unloads every plugin before it loads them again, which drops their server# configs, skills and liveness declarations for the length of the pass. Two installs finishing# together (one card, two rows) each go live; the second one's pass must not run while the first@@ -188,13 +206,14 @@ def _go_live(name: str) -> Optional[dict[str, Any]]:with manager._discovery_lock:manager.discover_and_load(force=True)activation = find_activation(activation_summaries(manager), name)+ blocked = None if activation else find_activation(dependency_blocked_summaries(manager), name)portable = manager.get_portable_mcp_servers()skills = plugin_skills(activation["key"]) if activation else []except Exception:logger.debug("in-process plugin reload after change to %r failed", name, exc_info=True)return Noneif activation is None:- return None+ return blockedservers = connect_plugin_mcp(activation, portable)activation["live_now"] = {"mcp_servers": servers, "skills": skills}activation["deferred"] = {k: v for k, v in (activation.get("deferred") or {}).items() if k != "mcp_servers"}@@ -255,16 +274,19 @@ 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."""+def dependency_restart_hint(missing: list[str], *, gateway: bool) -> str:+ """What to do when the running gateway / backend cannot import a plugin's dependencies. *gateway*:+ the messaging gateway answered; otherwise only the Desktop / dashboard backend did, and restarting+ a gateway that does not run would apply to nothing."""from hermes_cli.plugins_loader import installed_in_selected_environmentdeps = ", ".join(missing)+ restart = (" hermes gateway restart" if gateway+ else " quit and reopen the Hermes desktop app (or restart hermes dashboard)")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")+ f"load the plugin:\n{restart}")+ return f"Its Python dependencies ({deps}) are not installed. Run hermes pm repair, then restart:\n{restart}"def report_activation(console, name: str) -> None:@@ -287,7 +309,7 @@ def activation_hint(result: dict[str, Any]) -> str: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)])+ return "\n".join([*lines, dependency_restart_hint(missing, gateway=bool(result.get("gateway_reloaded")))])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 9f326675b18..65ba8ad9c93 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -201,18 +201,25 @@ 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."""+def _dist_installed(req: str, path: Optional[list[str]] = None) -> Optional[bool]:+ """Best-effort probe: a distribution the requirement accepts is installed (on ``path`` when given,+ else this process's ``sys.path``); ``None`` when unprobeable. The version counts: a running+ process holding ``x 1.2`` cannot serve a plugin that now requires ``x>=1.3``."""dist = _dist_name(req)if not dist:return Nonetry:- importlib.metadata.version(dist)- return True- except importlib.metadata.PackageNotFoundError:- return False+ found = next(iter(importlib.metadata.distributions(name=dist, path=path) if path+ else importlib.metadata.distributions(name=dist)), None)except Exception:return None+ if found is None:+ return False+ try:+ from packaging.requirements import Requirement+ return Requirement(req).specifier.contains(found.version, prereleases=True)+ except (ImportError, ValueError): # no packaging, or an unparseable requirement/version: presence decides+ return Truedef missing_python_dependencies(manifest: Any) -> list[str]:@@ -250,9 +257,7 @@ def installed_in_selected_environment(requirements: list[str]) -> bool:from pm.paths import repo_rootsite = 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)+ return bool(requirements) and all(_dist_installed(req, [site]) for req in requirements)except (OSError, RuntimeError, ValueError): # unreadable or invalid selection recordreturn Falsediff --git a/tests/hermes_cli/test_plugin_dependency_restart.py b/tests/hermes_cli/test_plugin_dependency_restart.pyindex 10d05736fbc..7d7f17e2e1f 100644--- a/tests/hermes_cli/test_plugin_dependency_restart.py+++ b/tests/hermes_cli/test_plugin_dependency_restart.py@@ -10,9 +10,12 @@ logged "run hermes pm repair" — on a hosted container the terminal backend thefrom __future__ import annotations+import asyncioimport jsonimport logging+import threadingfrom pathlib import Path+from types import SimpleNamespaceimport pytest@@ -23,7 +26,13 @@ DIST = "hermes-depprobe-fixture"REQ = f"{DIST}>=1.0,<2"-def _select_generation(home: Path, *, with_dist: bool) -> Path:+def _dist_info(site: Path, version: str) -> None:+ info = site / f"{DIST.replace('-', '_')}-{version}.dist-info"+ info.mkdir(parents=True)+ (info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {DIST}\nVersion: {version}\n", encoding="utf-8")+++def _select_generation(home: Path, *, with_dist: bool, version: str = "1.0") -> 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_packagesfrom pm.paths import repo_root@@ -34,9 +43,7 @@ def _select_generation(home: Path, *, with_dist: bool) -> Path: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")+ _dist_info(site, version)facts = runtime_facts_path(repo_root())facts.write_text(json.dumps({"schema": 1, "packages": {"venv": {"environment": str(venv)}}}),encoding="utf-8")@@ -156,3 +163,48 @@ def test_a_dependency_excluded_by_its_marker_is_never_missing():excluded = f"{DIST}>=1.0,<2; python_version < '3.0'"manifest = PluginManifest(name="depprobe", python_dependencies=[excluded, REQ])assert missing_python_dependencies(manifest) == [REQ]+++def test_a_plugin_importing_its_new_dependency_at_load_still_asks_for_a_restart(home, monkeypatch):+ """The common shape: ``import <dep>`` at module top. In a gateway booted before the install the+ load fails, so the plugin has no activation summary; the reload answer must still carry what+ blocked it, or enable reports "nothing of this plugin needs a session or restart"."""+ from gateway.run_plugin_rewire import reload_plugins_verb+ from hermes_cli import plugins+ from tui_gateway.contracts.tools_mcp_plugins import PluginActivation++ _select_generation(home, with_dist=True)+ (home / "plugins" / "depprobe" / "__init__.py").write_text(+ "import hermes_depprobe_fixture\n\ndef register(ctx):\n pass\n", encoding="utf-8")+ loop = asyncio.new_event_loop()+ threading.Thread(target=loop.run_forever, daemon=True).start()+ try:+ answer = reload_plugins_verb(SimpleNamespace(adapters={}), loop)() # the gateway's real verb+ finally:+ loop.call_soon_threadsafe(loop.stop)+ plugins._reset_plugin_managers_for_tests()+ monkeypatch.setattr("gateway.control_socket.reload_gateway_plugins",+ lambda target, *, profile_home=None, timeout=30.0: answer)+ monkeypatch.setattr(plugins_activation, "notify_serve_backend", lambda name, home: None)++ result = plugins_activation.activate_plugin_now("depprobe", in_process=False)++ assert result["restart_required"] is True+ assert result["activation"]["missing_dependencies"] == [REQ]+ assert "nothing of this plugin needs" not in plugins_activation.activation_hint(result)+ PluginActivation.model_validate(result["activation"]) # the plugins.manage wire accepts it+++def test_an_installed_version_the_requirement_rejects_is_missing(home, monkeypatch, tmp_path):+ """``plugins update`` raising a floor: the running process holds 1.0, the selected generation+ 1.7. A name-only probe called that satisfied and asked for no restart."""+ _select_generation(home, with_dist=True, version="1.7")+ running = tmp_path / "running-site"+ _dist_info(running, "1.0")+ monkeypatch.syspath_prepend(str(running))+ from hermes_cli.plugins import PluginManifest++ raised = f"{DIST}>=1.5,<2"+ assert missing_python_dependencies(PluginManifest(name="depprobe", python_dependencies=[raised])) == [raised]+ assert installed_in_selected_environment([raised]) is True+ assert installed_in_selected_environment([f"{DIST}>=1.8"]) is Falsediff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 0ff35281711..035c92306d5 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -744,13 +744,15 @@ class PluginActivation(Result):(``gateway_reloaded``). ``live_now``: the plugin's MCP servers (connected, with their tools, or theerror) and skills, usable in every open chat of the profile from its next turn — the chats also get anote listing them. ``deferred`` kinds: ``tools`` (Python tool names) and ``prompt`` (section ids)- apply from the next session."""+ apply from the next session. ``missing_dependencies``: the plugin's declared Python requirements the+ process that answered cannot import (installed after it booted, or never) — only a restart loads them."""name: strkey: stractivated_now: dict[str, list[str]] = Field(default_factory=dict)live_now: PluginLiveNow | None = Nonedeferred: dict[str, list[str]] = Field(default_factory=dict)+ missing_dependencies: list[str] = Field(default_factory=list)class OnboardingCatalogPlugin(Result):