The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): rescan a secondary profile for a missed plugin off the event loop
unsupportedpastels182ba5982ab9
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 50eb4d543bd..b4607df0c71 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -427,7 +427,7 @@ async def _plugin_api_runtime_gate(request: Request, call_next):or _has_valid_query_token(request, path)):with plugin_request_scope(request.scope): # a secondary profile's plugins run in its host- if _plugin_api_request_refused(plugin_name):+ if await _plugin_api_request_refused(plugin_name):return JSONResponse(status_code=404, content={"detail": "Plugin not found"})hosted = await forward_secondary_plugin_request(request, plugin_name)if hosted is not None:diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex b7d2ba355de..354d7662c3a 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -857,7 +857,7 @@ def _plugin_api_name(scope) -> str:return parts[3] if path.startswith("/api/plugins/") and len(parts) >= 4 else ""-def _plugin_api_request_refused(name: str) -> bool:+async def _plugin_api_request_refused(name: str) -> bool:"""The runtime gate for one ``/api/plugins/<name>/`` request, HTTP and WebSocket alike.:func:`_mount_plugin_api_routes` gates at import time; a plugin disabled while the server runs@@ -869,7 +869,7 @@ def _plugin_api_request_refused(name: str) -> bool:plugin = next((p for p in _get_dashboard_plugins() if p.get("name") == name), None)home = secondary_profile_home()if plugin is None and home is not None: # installed since the last scan (rate-limited per name)- plugin = rescanned_plugin(home, name)+ plugin = await asyncio.to_thread(rescanned_plugin, home, name) # a disk scan: off the event loopreturn _plugin_consent_withheld(plugin or {"name": name, "source": "user"})@@ -898,7 +898,7 @@ class PluginApiWebSocketGate:await self.app(scope, receive, send)returnwith _native_ws_scope(scope) as admitted, plugin_request_scope(scope):- if admitted and not _plugin_api_request_refused(name):+ if admitted and not await _plugin_api_request_refused(name):if not await refuse_secondary_plugin_socket(scope, receive, send, name):await self.app(scope, receive, send)return@@ -949,7 +949,7 @@ async def _plugin_route_secret_scope(conn: HTTPConnection, profile: Optional[strwith _config_profile_scope(profile):# The plugin must not run on a profile that disabled it (#134889), and this router is the# launch profile's copy: a secondary profile reaches it only for bundled plugins (PLG-3).- if (not _is_current_profile(profile) and _plugin_api_request_refused(name)) or in_process_router_refused(name):+ if (not _is_current_profile(profile) and await _plugin_api_request_refused(name)) or in_process_router_refused(name):if conn.scope["type"] == "websocket":raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)raise HTTPException(status_code=404, detail="Plugin not found")diff --git a/hermes_cli/web_server_plugin_profiles.py b/hermes_cli/web_server_plugin_profiles.pyindex 1e62e9fa24d..cc1ccc63a3d 100644--- a/hermes_cli/web_server_plugin_profiles.py+++ b/hermes_cli/web_server_plugin_profiles.py@@ -39,6 +39,9 @@ _GATEWAY_CREDENTIAL_HEADERS = frozenset({_GATEWAY_QUERY_KEYS = frozenset({"token", "ticket", "internal", "display_ticket", "attach", "profile"})_profile_plugins: dict[str, list] = {}+# Bumped by each explicit rescan of a profile: a scan begun before it publishes neither its list nor a miss.+_profile_rescans: dict[str, int] = {}+# Guards these module dicts only; disk scans run without it, so a scan never blocks another caller._profile_plugins_lock = threading.Lock()# Requests forwarded to a profile's plugin host wait on that profile's own threads, not the gateway's@@ -62,28 +65,42 @@ def secondary_profile_home() -> Optional[Path]:return None if hermes_home_key(home) == hermes_home_key(get_process_hermes_home()) else Path(home)-def profile_dashboard_plugins(home: Path, force_rescan: bool = False, keep_misses: bool = False) -> list:- """Dashboard plugins of the profile at ``home``, cached per home like the launch profile's list:- its own ``plugins/``, then the root's (as a standalone ``hermes --profile <name> serve`` scanned- them; the profile's own copy wins a same-name conflict), then the bundled ones. An explicit- rescan also forgets the profile's cached misses; ``keep_misses`` (a miss-driven rescan) keeps them."""+def _scan_profile_plugins(home: Path) -> list:+ """The profile at ``home``'s dashboard plugins, read from disk: its own ``plugins/``, then the+ root's (as a standalone ``hermes --profile <name> serve`` scanned them; the profile's own copy+ wins a same-name conflict), then the bundled ones."""from hermes_cli.plugins import get_bundled_plugins_dirfrom hermes_cli.profiles import _get_default_hermes_homefrom hermes_cli.web_server_dashboard import _discover_dashboard_plugins+ bundled, own = get_bundled_plugins_dir(), Path(home) / "plugins"+ dirs = [own] + [r for r in [_get_default_hermes_home() / "plugins"]+ if r.resolve(strict=False) != own.resolve(strict=False)]+ return _discover_dashboard_plugins(+ [(d, "user") for d in dirs] + [(bundled / "memory", "bundled"), (bundled, "bundled")])+++def _published(key: str, rescans: int, plugins: list) -> list:+ """Cache ``plugins`` for ``key`` unless an explicit rescan began after this scan did; return them."""+ with _profile_plugins_lock:+ if _profile_rescans.get(key, 0) == rescans:+ _profile_plugins[key] = plugins+ return plugins+++def profile_dashboard_plugins(home: Path, force_rescan: bool = False) -> list:+ """Dashboard plugins of the profile at ``home`` (:func:`_scan_profile_plugins`), cached per home+ like the launch profile's list. An explicit rescan also forgets the profile's cached misses."""from hermes_constants import hermes_home_keykey = hermes_home_key(home)with _profile_plugins_lock:- if force_rescan and not keep_misses:+ if force_rescan:+ _profile_rescans[key] = _profile_rescans.get(key, 0) + 1for unknown in [k for k in _unknown_plugins if k[0] == key]:del _unknown_plugins[unknown]- cached = _profile_plugins.get(key)- if cached is None or force_rescan or any(not Path(p["_dir"]).is_dir() for p in cached):- bundled, own = get_bundled_plugins_dir(), Path(home) / "plugins"- dirs = [own] + [r for r in [_get_default_hermes_home() / "plugins"]- if r.resolve(strict=False) != own.resolve(strict=False)]- cached = _profile_plugins[key] = _discover_dashboard_plugins(- [(d, "user") for d in dirs] + [(bundled / "memory", "bundled"), (bundled, "bundled")])- return cached+ cached, rescans = _profile_plugins.get(key), _profile_rescans.get(key, 0)+ if cached is None or force_rescan or any(not Path(p["_dir"]).is_dir() for p in cached):+ cached = _published(key, rescans, _scan_profile_plugins(home))+ return cacheddef _named(plugins: list, name: str) -> Optional[dict]:@@ -92,21 +109,25 @@ def _named(plugins: list, name: str) -> Optional[dict]:def rescanned_plugin(home: Path, name: str) -> Optional[dict]:"""The profile at ``home``'s entry for ``name`` after a rescan, or None; a name found missing- within the last :data:`_UNKNOWN_PLUGIN_RESCAN_SECS` is answered without one."""+ within the last :data:`_UNKNOWN_PLUGIN_RESCAN_SECS` is answered without one. Blocking: the+ request gate runs it on a worker thread."""from hermes_constants import hermes_home_key- key, now = (hermes_home_key(home), name), time.monotonic()+ home_key, now = hermes_home_key(home), time.monotonic()+ key = (home_key, name)with _profile_plugins_lock:if _unknown_plugins.get(key, now) > now:return None- # Other names' unexpired misses survive this rescan, so probes alternating names can't defeat them.- plugin = _named(profile_dashboard_plugins(home, force_rescan=True, keep_misses=True), name)+ rescans = _profile_rescans.get(home_key, 0)+ # Not an explicit rescan: other names' unexpired misses survive it, so probes alternating names+ # can't defeat them.+ plugin = _named(_published(home_key, rescans, _scan_profile_plugins(home)), name)with _profile_plugins_lock:for expired in [k for k, until in _unknown_plugins.items() if until <= now]:del _unknown_plugins[expired]- if plugin is None:- _unknown_plugins[key] = now + _UNKNOWN_PLUGIN_RESCAN_SECS- else:+ if plugin is not None:_unknown_plugins.pop(key, None)+ elif _profile_rescans.get(home_key, 0) == rescans: # an explicit rescan since may have found it+ _unknown_plugins[key] = now + _UNKNOWN_PLUGIN_RESCAN_SECSreturn plugindiff --git a/tests/hermes_cli/test_plugin_secondary_profile_host.py b/tests/hermes_cli/test_plugin_secondary_profile_host.pyindex 199432cc574..1b472b557f1 100644--- a/tests/hermes_cli/test_plugin_secondary_profile_host.py+++ b/tests/hermes_cli/test_plugin_secondary_profile_host.py@@ -649,3 +649,54 @@ def test_alternating_unknown_names_each_rescan_once_per_window(daemon, monkeypatassert status("absent-a") == 404 # cached until the window endsclock[0] += 60assert status("absent-a") == 200+++def test_a_miss_rescan_reads_the_disk_off_the_event_loop_and_unlocked(daemon, monkeypatch):+ """The rescan a missed name triggers runs on a worker thread, without the lock every plugin lookup+ takes, so it stalls neither the gateway's event loop nor other requests' plugin lookups."""+ from hermes_cli import web_server_dashboard, web_server_plugin_profiles+ _beta_plugin(daemon)+ selected = {"params": {"profile": "beta"}, "headers": daemon.owner}+ assert daemon.client.get(PING, **selected).status_code == 200+ scans, discover = [], web_server_dashboard._discover_dashboard_plugins++ def observed(*args, **kwargs):+ try:+ on_loop = asyncio.get_running_loop() is not None+ except RuntimeError:+ on_loop = False+ scans.append({"on_loop": on_loop, "locked": web_server_plugin_profiles._profile_plugins_lock.locked()})+ return discover(*args, **kwargs)++ monkeypatch.setattr(web_server_dashboard, "_discover_dashboard_plugins", observed)++ assert daemon.client.get("/api/plugins/absent/ping", **selected).status_code == 404+ assert scans == [{"on_loop": False, "locked": False}]+++def test_a_miss_rescan_overtaken_by_an_explicit_rescan_caches_nothing_stale(daemon, monkeypatch):+ """Scans no longer hold the lock, so an explicit rescan can finish inside a miss rescan's scan:+ the miss rescan's older list and its miss are then dropped, and the plugin answers at once."""+ from hermes_cli import web_server_dashboard, web_server_plugin_profiles+ _beta_plugin(daemon)+ _plugins(daemon.beta, enabled=[NAME, "late"])+ overtook = []+ selected = {"params": {"profile": "beta"}, "headers": daemon.owner}+ status = lambda name: daemon.client.get(f"/api/plugins/{name}/ping", **selected).status_code+ assert status(NAME) == 200+ discover = web_server_dashboard._discover_dashboard_plugins++ def overtaken(*args, **kwargs): # the miss rescan's view predates the install+ found = discover(*args, **kwargs)+ monkeypatch.setattr(web_server_dashboard, "_discover_dashboard_plugins", discover)+ _install(daemon.beta, "late")+ web_server_plugin_profiles.profile_dashboard_plugins(daemon.beta, force_rescan=True)+ overtook.append(1)+ return found++ monkeypatch.setattr(web_server_dashboard, "_discover_dashboard_plugins", overtaken)++ # The forward reads the explicit rescan's list, not the miss rescan's older one.+ assert status("late") == 200 and overtook == [1]+ assert not [k for k in web_server_plugin_profiles._unknown_plugins if k[1] == "late"]+ assert status("late") == 200