The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): read a parked profile's config without importing its plugins (#123386, salvage #123397)
JoaoMarcos44d5672e4f554f
diff --git a/hermes_cli/gateway_migrate.py b/hermes_cli/gateway_migrate.pyindex d97355d982e..45358686208 100644--- a/hermes_cli/gateway_migrate.py+++ b/hermes_cli/gateway_migrate.py@@ -416,10 +416,20 @@ def _write_multiplex_flag(default_home: Path, value: bool) -> None:def _profile_gateway_config(home: Path):"""This profile's ``GatewayConfig`` read exactly the way the multiplexer reads it: under theprofile's own secret scope with multiplexing active, so a missing token stays missing instead of- borrowing the CLI process's ``os.environ`` (which holds the launch profile's ``.env``)."""+ borrowing the CLI process's ``os.environ`` (which holds the launch profile's ``.env``).++ A PARKED profile stays in the inventory and the duplicate-credential guard (parking must not hide+ a conflict), but it is inert for the host: its config is read without discovering its plugins,+ whose ``register()`` would otherwise run in the live gateway on every boot (#123386). Only its+ plugin-defined platforms fall out of the guard — their credentials cannot be evaluated without+ importing the plugin; builtin bot tokens still collide.+ """from gateway.config import load_gateway_configfrom gateway.run import _profile_runtime_scope- with _profile_runtime_scope(home):+ from hermes_cli.plugins_discovery import suppress_plugin_discovery+ from hermes_cli.profiles import profile_is_parked+ scope = suppress_plugin_discovery() if profile_is_parked(home) else contextlib.nullcontext()+ with _profile_runtime_scope(home), scope:return load_gateway_config()diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex bba82a3b4b0..189174ee86e 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -43,7 +43,8 @@ from hermes_cli.plugins_manifest import ( # noqa: F401 — re-exported)from hermes_cli.plugins_discovery import ( # noqa: F401 — re-exportedENTRY_POINTS_GROUP, _get_disabled_plugins, _get_enabled_plugins, collect_directory_manifests,- discover_entrypoint_manifests, gate_manifest, resolve_manifest_winners, scan_directory,+ discover_entrypoint_manifests, gate_manifest, plugin_discovery_suppressed, resolve_manifest_winners,+ scan_directory,)from hermes_cli.plugins_loader import (PluginLoaderMixin, _BARE_MODULE_SCOPE, _MODULE_NAMESPACE_LOCK, _NS_PARENT, _evict_modules,@@ -1302,6 +1303,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):def discover_and_load(self, force: bool = False) -> None:"""Scan all plugin sources and load each plugin found; ``force`` unloads first so configchanges / new bundled backends become visible in long-lived sessions."""+ if plugin_discovery_suppressed():+ return # a config-only read of a profile this process must not load plugins forif self._discovered and not force and in_plugin_load_worker():# A plugin whose register() re-enters discovery (importing model_tools does) runs on a# deadline worker that cannot re-acquire the sweep's RLock; the flag is already set for thediff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.pyindex e9645e51f0e..a2f5642e538 100644--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@ -6,6 +6,8 @@ Split out of :mod:`hermes_cli.plugins`. Names that tests patch on the originfrom __future__ import annotations+import contextlib+import contextvarsimport importlib.metadataimport loggingfrom dataclasses import dataclass@@ -34,6 +36,29 @@ _FOREIGN_HARNESS_MANIFEST_DIRS = frozenset({".claude-plugin", ".codex-plugin", ".cursor-plugin", ".devin-plugin", ".kimi-plugin",})+# Set while a caller reads a profile's config WITHOUT wanting that profile's plugins in this process:+# the multiplex preflight loads a PARKED profile's gateway config for the duplicate-credential guard,+# and ``load_gateway_config`` discovers plugins in the scope it runs under. Importing them runs their+# ``register()`` (threads, DB handles) for a profile the operator took out of the host (#123386).+# A contextvar, not an env flag: it must not leak to other threads or outlive the read.+_discovery_suppressed: contextvars.ContextVar[bool] = contextvars.ContextVar(+ "hermes_plugin_discovery_suppressed", default=False)+++def suppress_plugin_discovery():+ """``discover_plugins()`` is a no-op inside; the scope's manager stays undiscovered, so the+ first real consumer after the block still loads its plugins."""+ token = _discovery_suppressed.set(True)+ try:+ yield+ finally:+ _discovery_suppressed.reset(token)+++def plugin_discovery_suppressed() -> bool:+ return _discovery_suppressed.get()+def _select_entry_point_group(entry_points: Any, group: str) -> list:"""Return one metadata entry-point group across supported Python APIs."""diff --git a/tests/hermes_cli/test_gateway_migrate_multiplex.py b/tests/hermes_cli/test_gateway_migrate_multiplex.pyindex a317291ab55..cfadf680e75 100644--- a/tests/hermes_cli/test_gateway_migrate_multiplex.py+++ b/tests/hermes_cli/test_gateway_migrate_multiplex.py@@ -178,6 +178,33 @@ def test_parked_profile_remains_in_migration_inventory(fleet):assert any("'coder'" in reason and "credential" in reason for reason in blocked.blockers)+def test_preflight_never_imports_a_parked_profiles_plugins(fleet):+ """A parked profile stays in the inventory and the duplicate-credential guard (above), but+ loading its gateway config must not run its plugins' ``register()`` in the host process (#123386)."""+ from hermes_cli.plugins import _reset_plugin_managers_for_tests++ home = fleet.root / "profiles/coder"+ (home / "gateway.parked").touch()+ (home / "config.yaml").write_text("plugins:\n enabled: [p1]\n", encoding="utf-8")+ marker = fleet.root / "p1-registered"+ plugin = home / "plugins/p1"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: p1\n", encoding="utf-8")+ (plugin / "__init__.py").write_text(+ f"from pathlib import Path\n\ndef register(ctx):\n Path({str(marker)!r}).write_text('imported')\n",+ encoding="utf-8",+ )+ _reset_plugin_managers_for_tests()+ try:+ plan = gm.build_migration_plan()+ assert "coder" in {p.name for p in plan.standalone_secondaries}+ assert not marker.exists(), "migration preflight imported a parked profile's plugin"+ gm.duplicate_credential_findings() # doctor / gateway status read the same homes+ assert not marker.exists()+ finally:+ _reset_plugin_managers_for_tests()++def test_migration_removes_parked_footprint_without_waiting_for_it_to_serve(fleet, monkeypatch):home = fleet.root / "profiles/coder"(home / "gateway.parked").touch()