Skip to content

The agent that grows with you

fix: repair PM call sites the origin/main merges overwrote with pre-PM code

ethernet44f891a8209e
diff --git a/hermes_cli/local_runtime/binaries.py b/hermes_cli/local_runtime/binaries.py
index 4b948b7aa6a..db0a1c9d123 100644
--- a/hermes_cli/local_runtime/binaries.py
+++ b/hermes_cli/local_runtime/binaries.py
@@ -42,44 +42,6 @@ def pinned_tag(backend: str) -> str:
if version is None:
raise BinaryResolutionError(f"llama.cpp {backend} has no PM version pin")
return f"b{version}"
-def manifest_verified(manifest: Path) -> bool:
- """True when an install manifest records a verified_version (missing/damaged -> False)."""
- try:
- data = json.loads(manifest.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, OSError):
- return False
- return isinstance(data, dict) and bool(data.get("verified_version"))
-
-
-def _release_number(tag: str) -> int:
- digits = "".join(ch for ch in tag if ch.isdigit())
- return int(digits) if digits else 0
-
-
-def installed_tags() -> list[str]:
- """Tags with a verified install, newest first by release number. The boot ladder and the
- update check both read installed-ness from here — one resolver, every caller."""
- root = runtimes_root()
- if not root.exists():
- return []
- found = {entry.name for entry in root.iterdir()
- if entry.is_dir() and entry.name != "downloads"
- and any(manifest_verified(m) for m in entry.glob("*/manifest.json"))}
- return sorted(found, key=_release_number, reverse=True)
-
-
-def _host_os_arch() -> tuple[str, str]:
- """(os, arch) normalized to release-asset vocabulary. PITFALL: PROCESSOR_ARCHITECTURE lies
- under x64 emulation on ARM64 Windows, and platform.machine() reads the same env on some
- Pythons — so on Windows prefer PROCESSOR_IDENTIFIER's text when present."""
- system = platform.system().lower()
- os_name = {"windows": "win", "darwin": "macos", "linux": "ubuntu"}.get(system, system)
- arch = "arm64" if platform.machine().lower() in ("arm64", "aarch64") else "x64"
- if os_name == "win":
- ident = os.environ.get("PROCESSOR_IDENTIFIER", "").lower()
- if "armv8" in ident or "arm " in ident:
- arch = "arm64"
- return os_name, arch
def select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:
diff --git a/hermes_cli/local_runtime/endpoint.py b/hermes_cli/local_runtime/endpoint.py
index e1649d5315d..365890a36aa 100644
--- a/hermes_cli/local_runtime/endpoint.py
+++ b/hermes_cli/local_runtime/endpoint.py
@@ -136,14 +136,12 @@ def _kick_managed_boot(config: dict | None) -> None:
def _boot_in_flight(config: dict | None) -> bool:
- """True when the managed runtime is enabled and installed (a verified-manifest scan under
- runtimes_root(), NOT a bare ``server_binary()`` call — that needs an install_dir, and calling
- it bare once made this gate throw-and-return False forever, disabling the boot wait)."""
+ """True when the managed runtime is enabled and PM holds an installed engine."""
with suppress(Exception):
config = _load_config_if_none(config)
if not ((config or {}).get("local_runtime") or {}).get("enabled"):
return False
- from hermes_cli.local_runtime.binaries import manifest_verified, runtimes_root
+ from hermes_cli.local_runtime.binaries import installed_engine
- return any(manifest_verified(m) for m in runtimes_root().glob("*/*/manifest.json"))
+ return installed_engine() is not None
return False
diff --git a/hermes_cli/memory_provider_migration.py b/hermes_cli/memory_provider_migration.py
index 8e6205e7c5b..026e1dcd33e 100644
--- a/hermes_cli/memory_provider_migration.py
+++ b/hermes_cli/memory_provider_migration.py
@@ -27,8 +27,8 @@ _attempted: set[str] = set()
def configured_provider(home: Path) -> str:
"""``memory.provider`` of *home*'s effective config, or ``""``."""
- from hermes_cli.plugin_python_deps import _read_home_config
- memory = _read_home_config(home).get("memory") or {}
+ from pm.plugins_state import _read_home_config
+ memory = (_read_home_config(home) or {}).get("memory") or {}
return str(memory.get("provider") or "").strip()
@@ -93,9 +93,9 @@ def _install_into(home: Path) -> Callable[[str], dict]:
def migrate_all_homes(*, say: Callable[[str], None] = print) -> list[str]:
"""``hermes update`` hook: every profile home sharing this venv. Returns installed plugin names."""
- from hermes_cli.plugin_python_deps import dependency_homes
+ from pm.plugins_state import _all_homes
installed: list[str] = []
- for home in dependency_homes():
+ for home in _all_homes():
try:
name = migrate_home(home, install=_install_into(home), say=say)
except Exception as exc:
@@ -112,8 +112,8 @@ def recover_at_startup(name: str) -> bool:
if name in _attempted:
return False
_attempted.add(name)
- from tools.lazy_deps import _allow_lazy_installs
- if not _allow_lazy_installs():
+ from pm.ensure import lazy_installs_allowed
+ if not lazy_installs_allowed():
logger.warning("Memory provider '%s' is not installed; security.allow_lazy_installs is off — "
"run `hermes plugins install %s`.", name, name)
return False
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index ed0cf150757..ea1e94f354f 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -229,10 +229,11 @@ def cmd_validate(path: str, as_json: bool = False, install_deps: bool = False) -
from hermes_cli.plugin_validate import validate_plugin_dir
from hermes_cli.plugins_cmd import _console
if install_deps:
- from hermes_cli.plugin_python_deps import install_for_plugin_dir
- outcome = install_for_plugin_dir(Path(path))
- if outcome.status in ("failed", "invalid"):
- print(outcome.message, file=sys.stderr)
+ import pm
+ try:
+ pm.sync_venv(extra_plugin_dirs=[Path(path)])
+ except Exception as exc: # validation still runs; the probe reports what is missing
+ print(f"dependency preparation failed: {exc}", file=sys.stderr)
report = validate_plugin_dir(Path(path))
if as_json:
print(json.dumps(report.to_dict(), indent=2))
diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.py
index 3147bb5a0cd..23c93564728 100644
--- a/plugins/memory/hindsight/__init__.py
+++ b/plugins/memory/hindsight/__init__.py
@@ -34,13 +34,14 @@ from utils import read_json_or_empty
from .embedded import (
_RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,
- _check_local_runtime, _embedded_llm_api_key, _embedded_profile_env_path,
- _export_port_health_grace_timeout, _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,
+ _check_local_runtime, _embedded_profile_env_path,
+ _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,
_may_rewrite_profile_env,
)
+from .embedded_runtime import ensure_daemon_and_url as _start_sideenv_daemon
from .settings import (
_DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,
- _DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_CLIENT_VERSION, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,
+ _DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,
_PROVIDER_DEFAULT_MODELS, _VALID_BUDGETS, _daemon_llm_provider,
_normalize_observation_scopes, _normalize_retain_tags, _parse_int_setting,
_resolve_bank_id_template,
@@ -53,12 +54,10 @@ _RETAIN_CONTEXT_DEFAULT = "conversation between Hermes Agent and the User"
def _ensure_client_dependency() -> None:
- """Lazily install the Hindsight client (``tools.lazy_deps``) before importing it."""
+ """Make the pinned ``hindsight`` extra importable before the client import."""
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("memory.hindsight", prompt=False)
- except ImportError:
- pass
+ from pm import ensure_import
+ ensure_import("hindsight")
except Exception as exc:
raise ImportError(str(exc)) from exc
@@ -91,30 +90,6 @@ def _cloud_api_key(config: dict) -> str:
return config.get("apiKey") or config.get("api_key") or get_secret("HINDSIGHT_API_KEY", "")
-def _maybe_upgrade_client() -> None:
- """Auto-upgrade an outdated hindsight-client via the environment-aware lazy_deps
- installer (sealed hosted venvs redirect to the durable target)."""
- try:
- from importlib.metadata import version as pkg_version
- from packaging.version import Version
- installed = pkg_version("hindsight-client")
- if Version(installed) < Version(_MIN_CLIENT_VERSION):
- logger.warning("hindsight-client %s is outdated (need >=%s), attempting upgrade...",
- installed, _MIN_CLIENT_VERSION)
- from tools.lazy_deps import install_specs
- outcome = install_specs([f"hindsight-client>={_MIN_CLIENT_VERSION}"], timeout=120)
- if outcome.ok:
- logger.info("hindsight-client upgraded to >=%s", _MIN_CLIENT_VERSION)
- elif outcome.blocked:
- logger.warning("Auto-upgrade unavailable: %s. Run: uv pip install 'hindsight-client>=%s'",
- outcome.reason, _MIN_CLIENT_VERSION)
- else:
- logger.warning("Auto-upgrade failed: %s. Run: uv pip install 'hindsight-client>=%s'",
- (outcome.stderr or "").strip() or "install error", _MIN_CLIENT_VERSION)
- except Exception:
- pass # packaging not available or other issue — proceed anyway
-
-
# update_mode='append' capability (Hindsight >= 0.5.0), cached per (API URL, key fingerprint)
# per process so every provider on the same API+key shares one /version round trip. A failed probe
# caches False, so the key must include the credential or one profile's 401 would silently downgrade
@@ -467,25 +442,40 @@ class HindsightMemoryProvider(MemoryProvider):
return _parse_int_setting(os.environ.get(env_var, env_default) if value is None else value, default)
def _new_embedded_client(self):
- available, reason = _check_local_runtime()
- if not available:
- raise RuntimeError("Hindsight local runtime is unavailable" + (f": {reason}" if reason else ""))
- _ensure_client_dependency()
- from hindsight import HindsightEmbedded
- HindsightEmbedded.__del__ = lambda self: None
+ """HTTP client against the side-env daemon. The daemon manager runs in the
+ isolated side env (its own interpreter → its own hindsight-api binary and
+ ProfileManager port allocation); Hermes talks to it over HTTP with the
+ pinned main-env hindsight-client — no in-process HindsightEmbedded."""
cfg = self._config
+ profile = cfg.get("profile", "hermes")
llm_provider = _daemon_llm_provider(cfg.get("llm_provider", ""))
- logger.debug("Creating HindsightEmbedded client (profile=%s, provider=%s)",
- cfg.get("profile", "hermes"), llm_provider)
+ logger.debug("Creating Hindsight embedded client (profile=%s, provider=%s)", profile, llm_provider)
self._idle_timeout = self._int_setting(
"idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,
)
- kwargs = dict(profile=cfg.get("profile", "hermes"), llm_provider=llm_provider,
- llm_api_key=_embedded_llm_api_key(cfg), llm_model=cfg.get("llm_model", ""),
- idle_timeout=self._idle_timeout)
- if self._llm_base_url:
- kwargs["llm_base_url"] = self._llm_base_url
- return HindsightEmbedded(**kwargs)
+ # Starts (or reuses) the side-env daemon; the URL comes from the side env's
+ # own ProfileManager/get_url, never a hardcoded port.
+ # Fail-closed on key material: when this process holds no key (no secret
+ # scope on this thread) but the file does, a rewrite would destroy the
+ # only key copy the daemon subprocess can read — leave the file and the
+ # running daemon alone rather than restart it keyless.
+ changed = _load_simple_env(_embedded_profile_env_path(cfg)) != _build_embedded_profile_env(cfg)
+ if changed and not _may_rewrite_profile_env(cfg):
+ logger.warning(
+ "Hindsight profile env for %r holds an LLM API key this process cannot see "
+ "(no secret scope); leaving the file untouched so the daemon keeps its key.", profile)
+ changed = False
+ if changed:
+ _materialize_embedded_profile_env(cfg)
+ url = _start_sideenv_daemon(cfg, restart=changed)
+ self._api_url = url
+ _ensure_client_dependency()
+ from hindsight_client import Hindsight
+ kwargs = {"base_url": url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}
+ if self._api_key:
+ kwargs["api_key"] = self._api_key
+ logger.info("Hindsight embedded: HTTP client ready (profile=%s, url=%s)", profile, url)
+ return Hindsight(**kwargs)
def _new_cloud_client(self):
_ensure_client_dependency()
@@ -662,8 +652,7 @@ class HindsightMemoryProvider(MemoryProvider):
minted at initialize / switch time) and don't pass ``update_mode`` at all — that's the only way the
resume-overwrite fix (#6654) keeps working on legacy servers.
"""
- url = getattr(self._client, "url", None) if self._mode == "local_embedded" else None
- probe_url = str(url) if url else (self._api_url or "")
+ probe_url = self._api_url or ""
if self._session_id and _check_api_supports_update_mode_append(probe_url, self._api_key):
return self._session_id, "append"
return fallback_document_id, None
@@ -681,7 +670,6 @@ class HindsightMemoryProvider(MemoryProvider):
self._platform = str(kwargs.get("platform") or "cli")
# session_id stays in tags so processes for one session remain filterable together.
self._document_id = _mint_document_id(self._session_id)
- _maybe_upgrade_client()
self._config = cfg = _load_config()
for name in _SESSION_KWARGS:
@@ -694,8 +682,6 @@ class HindsightMemoryProvider(MemoryProvider):
if self._mode == "local": # legacy alias
self._mode = "local_embedded"
if self._mode == "local_embedded":
- # Must precede the daemon_embed_manager import, which reads it at import time.
- _export_port_health_grace_timeout(cfg)
available, reason = _check_local_runtime()
if not available:
logger.warning("Hindsight local mode disabled because its runtime could not be imported: %s.%s",
@@ -830,45 +816,14 @@ class HindsightMemoryProvider(MemoryProvider):
spawn_context_thread(self._daemon_start_worker, name="hindsight-daemon-start").start()
def _daemon_start_worker(self) -> None:
- import traceback
- log_path = get_hermes_home() / "logs" / "hindsight-embed.log"
- log_path.parent.mkdir(parents=True, exist_ok=True)
-
- def _log(text: str) -> None:
- with open(log_path, "a", encoding="utf-8") as f:
- f.write(text)
-
+ """Background daemon bring-up: ``_get_client`` syncs the profile .env, then
+ starts/reuses the side-env daemon and connects the HTTP client."""
try:
- # Rich console -> our log file (redirecting global fds would capture other threads).
- import hindsight_embed.daemon_embed_manager as dem
- from rich.console import Console
- dem.console = Console(file=open(log_path, "a", encoding="utf-8"), force_terminal=False)
-
- client = self._get_client()
- profile = self._config.get("profile", "hermes")
- # Profile .env out of sync with config -> rewrite and restart a running daemon.
- # Fail-closed on key material: when this process holds no key (no secret
- # scope on this thread) but the file does, a rewrite would destroy the
- # only key copy the daemon subprocess can read. Skip the write AND the
- # stop: restarting the daemon now would boot it keyless, which is the
- # exact outage this guards against. _get_client() above already passed
- # whatever key WAS available into the in-process client kwargs.
- if _load_simple_env(_embedded_profile_env_path(self._config)) != _build_embedded_profile_env(self._config):
- if _may_rewrite_profile_env(self._config):
- _materialize_embedded_profile_env(self._config)
- if client._manager.is_running(profile):
- _log("\n=== Config changed, restarting daemon ===\n")
- client._manager.stop(profile)
- else:
- logger.warning(
- "Hindsight profile env for %r holds an LLM API key this process cannot see "
- "(no secret scope); leaving the file untouched so the daemon keeps its key.",
- profile)
- _log("\n=== Profile env has a key this process cannot see; left untouched ===\n")
- client._ensure_started()
- _log("\n=== Daemon started successfully ===\n")
+ self._get_client()
+ logger.info("Hindsight embedded: daemon start worker finished (profile=%s)",
+ self._config.get("profile", "hermes"))
except Exception as e:
- _log(f"\n=== Daemon startup failed: {e} ===\n" + traceback.format_exc())
+ logger.warning("Hindsight embedded daemon startup failed: %s", e, exc_info=True)
def system_prompt_block(self) -> str:
mode = self._memory_mode if self._memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"
@@ -1200,19 +1155,9 @@ class HindsightMemoryProvider(MemoryProvider):
self._session_id, self._parent_session_id, reset, self._document_id)
def _close_client(self) -> None:
- if self._mode != "local_embedded":
- self._run_sync(self._client.aclose())
- return
- # HindsightEmbedded.close() closes its sync client from this thread ("attached
- # to a different loop" before aiohttp releases the session): aclose the inner
- # client on the shared loop first, then let the wrapper clean up bookkeeping.
- inner_client = getattr(self._client, "_client", None)
- if inner_client is not None and hasattr(inner_client, "aclose"):
- _run_sync(inner_client.aclose())
- with contextlib.suppress(Exception):
- self._client._client = None
- with contextlib.suppress(RuntimeError):
- self._client.close()
+ # Both modes hold a hindsight_client.Hindsight (embedded talks HTTP to the
+ # side-env daemon): close on the shared loop.
+ self._run_sync(self._client.aclose())
def shutdown(self) -> None:
logger.debug("Hindsight shutdown: stopping writer + waiting for background threads")
diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.py
index 8efacbf50cf..b0b921c5e85 100644
--- a/plugins/memory/honcho/cli.py
+++ b/plugins/memory/honcho/cli.py
@@ -583,14 +583,14 @@ def _ensure_sdk_installed() -> bool:
print(" Skipping install. Run: pip install 'honcho-ai==2.2.0'\n")
return False
print(" Installing honcho-ai...", flush=True)
- from tools.lazy_deps import install_specs # env-aware: sealed hosted venvs redirect to the data volume
- result = install_specs(["honcho-ai==2.2.0"])
- if result.ok:
+ try:
+ import pm
+ pm.sync_venv(["honcho"], explicit=True)
print(" Installed.\n")
return True
- print(f" Cannot install: {result.reason}\n" if result.blocked else
- f" Install failed:\n{(result.stderr or '').strip()}\n Run manually: uv pip install 'honcho-ai==2.2.0'\n")
- return False
+ except Exception as exc:
+ print(f" Install failed: {exc}\n Run manually: hermes pm install\n")
+ return False
def _device_login_available() -> bool:
diff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.py
index 77f61647a2d..fb078a10c68 100644
--- a/plugins/memory/mem0/__init__.py
+++ b/plugins/memory/mem0/__init__.py
@@ -170,11 +170,11 @@ class Mem0MemoryProvider(MemoryProvider):
return template.format(vs=self._config.get("oss", {}).get("vector_store", {}).get("provider", default)) if self._mode == "oss" else ""
def _create_backend(self):
- # Lazy-install the mem0 SDK before the backend imports it (honors security.allow_lazy_installs);
- # on failure the backend import raises the canonical error, captured below.
+ # Make the pinned mem0 extra importable first; on failure the backend import
+ # raises the canonical error, captured below.
with suppress(Exception):
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("memory.mem0", prompt=False)
+ from pm import ensure_import
+ ensure_import("mem0")
try:
from . import _backend
if self._mode == "oss":
diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.py
index 07dcd3a5999..dbe90e41261 100644
--- a/plugins/platforms/google_chat/adapter.py
+++ b/plugins/platforms/google_chat/adapter.py
@@ -193,17 +193,16 @@ def check_google_chat_requirements() -> bool:
def ensure_google_chat_deps() -> bool:
"""ACTIVE installer (registry ``ensure_deps_fn``).
- Routes through ``tools.lazy_deps`` so sealed hosted/Docker images write
- ``HERMES_LAZY_INSTALL_TARGET`` instead of the read-only venv. Resets the
- failed-import cache so ``create_adapter()`` can load modules after install.
- ``FeatureUnavailable`` propagates: the registry logs its ``reason`` (quarantine
- 404, no writable target, network), which is exactly what a hosted operator needs.
+ PM owns the install; a refusal (lazy installs off, unsupported platform,
+ network) propagates so the registry logs the reason. Resets the failed-import
+ cache so ``create_adapter()`` can load modules after install.
"""
global _google_modules_loaded, GOOGLE_CHAT_AVAILABLE
if GOOGLE_CHAT_AVAILABLE:
return True
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("platform.google_chat", prompt=False)
+ from pm import ensure_import
+ for extra in ("google", "google-chat"):
+ ensure_import(extra)
_google_modules_loaded = False
return _load_google_modules()
diff --git a/plugins/platforms/google_chat/oauth.py b/plugins/platforms/google_chat/oauth.py
index b0dfe0fa35b..c445d9372c5 100644
--- a/plugins/platforms/google_chat/oauth.py
+++ b/plugins/platforms/google_chat/oauth.py
@@ -39,7 +39,9 @@ _EMAIL_FS_RE = re.compile(r"[^a-z0-9._@-]+")
# subsequent messages.create; no drive.file or other scopes.
SCOPES: List[str] = ["https://www.googleapis.com/auth/chat.messages.create"]
-# Pip packages required by the Google Chat adapter and its OAuth flow.
+# Declared extras (pyproject) and the exact pins they carry; the pins double as the
+# staleness probe so a half-synced interpreter is repaired instead of trusted.
+_DEPENDENCY_EXTRAS = ["google", "google-chat"]
_REQUIRED_PACKAGES = [
"google-cloud-pubsub==2.39.0",
"google-api-python-client==2.194.0",
@@ -238,20 +240,13 @@ def install_deps() -> bool:
return True
print("Installing Google Chat dependencies...")
try:
- from tools.lazy_deps import FeatureUnavailable, ensure as _lazy_ensure
-
- # lazy_deps honors HERMES_LAZY_INSTALL_TARGET on sealed hosted images;
- # _pip_install always writes the venv and Permission-denied there.
- _lazy_ensure("platform.google_chat", prompt=False)
+ import pm
+ pm.sync_venv(_DEPENDENCY_EXTRAS, explicit=True)
remaining = _missing_required_packages()
if remaining:
raise RuntimeError("dependencies remain stale after install: " + " ".join(remaining))
- print("Dependencies installed.")
+ print("Dependencies installed. Restart Hermes to activate any new dependency environment.")
return True
- except FeatureUnavailable as exc:
- print(f"ERROR: Failed to install dependencies: {exc.reason}")
- print("Run `hermes setup` to repair the managed installation, then retry.")
- return False
except Exception as exc:
print(f"ERROR: Failed to install dependencies: {exc}")
print("Run `hermes setup` to repair the managed installation, then retry.")
diff --git a/tests/gateway/test_google_chat_oauth_dependencies.py b/tests/gateway/test_google_chat_oauth_dependencies.py
index 81ac19b91a4..c7f7c449042 100644
--- a/tests/gateway/test_google_chat_oauth_dependencies.py
+++ b/tests/gateway/test_google_chat_oauth_dependencies.py
@@ -1,10 +1,12 @@
-"""Security-floor tests for the Google Chat runtime installer."""
+"""Google Chat dependency installation crosses PM's declared-feature interface."""
from __future__ import annotations
from importlib.metadata import PackageNotFoundError
-from types import SimpleNamespace
+import pytest
+
+import pm
from plugins.platforms.google_chat import oauth
@@ -34,46 +36,26 @@ def test_stale_google_transitives_are_reported_missing(monkeypatch):
]
-def test_installer_repairs_stale_transitives(monkeypatch):
- states = iter(
- [
- [
- "google-auth==2.55.1",
- "httplib2==0.32.0",
- "pyasn1==0.6.4",
- ],
- [],
- ]
- )
+def test_installer_repairs_stale_transitives_through_pm(monkeypatch, capsys):
+ states = iter([["google-auth==2.55.1", "httplib2==0.32.0", "pyasn1==0.6.4"], []])
monkeypatch.setattr(oauth, "_missing_required_packages", lambda: next(states))
calls = []
- pip_calls = []
-
- def fake_ensure(feature, prompt=False):
- calls.append((feature, prompt))
-
- monkeypatch.setattr("tools.lazy_deps.ensure", fake_ensure)
- monkeypatch.setattr(
- "hermes_cli.tools_config._pip_install",
- lambda argv: pip_calls.append(argv) or SimpleNamespace(returncode=0, stderr=""),
- )
+ monkeypatch.setattr(pm, "sync_venv", lambda extras, **kwargs: calls.append((extras, kwargs)))
assert oauth.install_deps() is True
- assert calls == [("platform.google_chat", False)]
- assert pip_calls == []
+ assert calls == [(["google", "google-chat"], {"explicit": True})]
+ assert "restart" in capsys.readouterr().out.lower()
def test_ensure_deps_surfaces_install_reason(monkeypatch):
- """A blocked lazy install must reach the registry's log with its reason, not a bare False."""
- from tools.lazy_deps import FeatureUnavailable
- import pytest
+ """A refused install must reach the registry's log with its reason, not a bare False."""
from plugins.platforms.google_chat import adapter
monkeypatch.setattr(adapter, "GOOGLE_CHAT_AVAILABLE", False)
- def blocked(feature, prompt=False):
- raise FeatureUnavailable(feature, ("google-cloud-pubsub==2.39.0",), "lazy install target /x is not writable")
+ def blocked(extra):
+ raise RuntimeError(f"extra {extra!r}: lazy installs are disabled")
- monkeypatch.setattr("tools.lazy_deps.ensure", blocked)
- with pytest.raises(FeatureUnavailable, match="not writable"):
+ monkeypatch.setattr(pm, "ensure_import", blocked)
+ with pytest.raises(RuntimeError, match="lazy installs are disabled"):
adapter.ensure_google_chat_deps()
diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.py
index 88dcfcdd8be..0694d11db43 100644
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@ -798,16 +798,3 @@ def test_bootstrap_failure_never_raises(tmp_path, monkeypatch):
"hermes_cli.local_runtime.binaries.installed_engine", boom)
result = bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}})
assert result is None # no exception escaped
-
-
-def test_manifest_verified_tolerates_non_dict_manifest(tmp_path):
- """A parseable-but-non-object manifest used to raise AttributeError out of
- manifest_verified (the .get ran inside a try that only caught decode/OSError),
- breaking any() scans over install dirs."""
- from hermes_cli.local_runtime.binaries import manifest_verified
-
- m = tmp_path / "manifest.json"
- m.write_text('"oops"', encoding="utf-8")
- assert manifest_verified(m) is False
- m.write_text(json.dumps({"verified_version": "5015 (abc)"}), encoding="utf-8")
- assert manifest_verified(m) is True
diff --git a/tests/hermes_cli/test_local_runtime_recovery.py b/tests/hermes_cli/test_local_runtime_recovery.py
index e9ba3536f91..4f1c0ab0dd1 100644
--- a/tests/hermes_cli/test_local_runtime_recovery.py
+++ b/tests/hermes_cli/test_local_runtime_recovery.py
@@ -22,7 +22,7 @@ def _wait_for(predicate, timeout=10):
assert predicate(), "process transition did not complete"
@pytest.mark.parametrize("case", [
"modern", "legacy", "live-owner", "pid-reused", "unknown-owner", "wrong-exe",
"legacy-key", "legacy-models", "busy", "state-replaced", "wrong-parent",
@@ -37,7 +37,6 @@ def test_startup_preserves_trees_and_explicit_stop_checks_owner(tmp_path, monkey
monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
monkeypatch.setattr(bootstrap, "_presets_stale", lambda: False)
monkeypatch.setattr(bootstrap, "_detect_gpu_vendor", lambda: None)
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags", lambda: [])
# A copied native interpreter stands in for the installed server; no live model is touched.
exe = root / "test-build" / "cpu" / "llama-server.exe"
@@ -196,7 +195,7 @@ def test_shutdown_during_backoff_cannot_restart_or_remove_another_server(tmp_pat
assert json.loads(supervisor.state_path().read_text()) == other
def test_supervisor_reaps_owned_job_even_after_router_exit(tmp_path, monkeypatch):
from types import SimpleNamespace
from hermes_cli.local_runtime import supervisor
@@ -357,7 +356,7 @@ def test_explicit_stop_preserves_verified_root_incarnation(tmp_path, monkeypatch
owned_child.kill.assert_called_once_with()
def test_reparented_router_keeps_its_endpoint(tmp_path, monkeypatch):
from hermes_cli.local_runtime import endpoint, supervisor
@@ -390,7 +389,7 @@ print(json.dumps({'pid': proc.pid, 'create_time': proc.create_time(), 'executabl
owner.stdout.close()
@pytest.mark.parametrize("damage", ["valid", "birth", "exe", "bool-pid", "bool-birth", "nan", "inf", "owner-bool", "owner-nan", "parent", "partial", "list", "invalid", "unreadable"])
def test_retained_endpoint_validates_identity(tmp_path, monkeypatch, damage):
from hermes_cli.local_runtime import endpoint, recovery, supervisor
diff --git a/tests/plugins/memory/test_bom_tolerant_config_reads.py b/tests/plugins/memory/test_bom_tolerant_config_reads.py
index 93925a4fd87..5462eb3c9bd 100644
--- a/tests/plugins/memory/test_bom_tolerant_config_reads.py
+++ b/tests/plugins/memory/test_bom_tolerant_config_reads.py
@@ -29,11 +29,10 @@ def _via_supermemory(p: Path, monkeypatch) -> dict:
return _load_supermemory_config(str(p.parent))
-def _via_hindsight_runtime_deps(p: Path, monkeypatch) -> dict:
- import hermes_cli.memory_setup as ms
- monkeypatch.setattr(ms, "get_hermes_home", lambda: p.parent.parent) # <home>/hindsight/config.json
- deps = ms._provider_pip_dependencies("hindsight", ["hindsight-client"])
- return {"workspace": "bom-ws" if "hindsight-all" in deps else None, "container_tag": None}
+def _via_hindsight_config(p: Path, monkeypatch) -> dict:
+ import plugins.memory.hindsight as hs
+ monkeypatch.setattr(hs, "get_hermes_home", lambda: p.parent.parent) # <home>/hindsight/config.json
+ return hs._load_config()
def _via_honcho_client(p: Path, monkeypatch) -> dict:
@@ -46,7 +45,7 @@ def _via_honcho_client(p: Path, monkeypatch) -> dict:
("mem0.json", _via_shared_reader),
("supermemory.json", _via_supermemory),
("honcho.json", _via_honcho_client),
- ("hindsight/config.json", _via_hindsight_runtime_deps),
+ ("hindsight/config.json", _via_hindsight_config),
])
def test_plugin_config_json_tolerates_bom(tmp_path, monkeypatch, filename, loader):
target = tmp_path / filename
diff --git a/tools/skills_hub.py b/tools/skills_hub.py
index 03665784964..d3b1d788576 100644
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@ -76,17 +76,6 @@ def __getattr__(name: str):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
-def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
- target = _PLUGIN_COMPAT_LAZY.get(name)
- if target is None:
- return _plugin_compat_prev_getattr(name)
- import importlib
- from hermes_cli.plugin_compat import warn_once
- warn_once(__name__, name, *target)
- return getattr(importlib.import_module(target[0]), target[1])
-# ---- END PLUGIN-COMPAT ----
-
-
# ---------------------------------------------------------------------------
# Install-path safety + guarded HTTP
# ---------------------------------------------------------------------------
@@ -457,3 +446,14 @@ _PLUGIN_COMPAT_LAZY = {
}
_plugin_compat_prev_getattr = __getattr__
+
+
+def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
+ target = _PLUGIN_COMPAT_LAZY.get(name)
+ if target is None:
+ return _plugin_compat_prev_getattr(name)
+ import importlib
+ from hermes_cli.plugin_compat import warn_once
+ warn_once(__name__, name, *target)
+ return getattr(importlib.import_module(target[0]), target[1])
+# ---- END PLUGIN-COMPAT ----
diff --git a/tools/tirith_security.py b/tools/tirith_security.py
index 6a6a80f5c06..07613e5b093 100644
--- a/tools/tirith_security.py
+++ b/tools/tirith_security.py
@@ -7,6 +7,7 @@ import os
import shutil
import subprocess
import threading
+import time
from contextvars import copy_context
from pathlib import Path