Skip to content

The agent that grows with you

fix(runtime): route remaining feature consumers through pm

ethernetaf8212b1f6a9
diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.py
index 2e63135fe21..5980190ded0 100644
--- a/hermes_cli/update_cmd_deps.py
+++ b/hermes_cli/update_cmd_deps.py
@@ -172,10 +172,10 @@ def _upgrade_pip_before_lazy_refresh(
def _capture_active_lazy_features() -> list[str]:
- """Snapshot active lazy backends before a managed runtime is replaced."""
+ """Snapshot the venv's enabled extras before a managed runtime is replaced."""
try:
- from tools import lazy_deps
- return lazy_deps.active_features()
+ import pm
+ return pm.enabled_extras()
except Exception as exc:
logger.debug("Could not snapshot active lazy features: %s", exc)
return []
@@ -259,84 +259,16 @@ def _clip(reason: str, limit: int = 200) -> str:
def _refresh_active_lazy_features(
install_cmd_prefix: list[str] | None = None, *, env: dict[str, str] | None = None,
features: list[str] | None = None) -> bool:
- """Refresh previously-activated lazy backends (cold ones untouched): the core install never
- touches them, so a bumped :data:`LAZY_DEPS` pin would leave them stale forever. Returns True
- when the venv is safe (refreshed / nothing active / import repair succeeded), False when a
- failed lazy install left broken core imports repair couldn't fix. Never raises.
-
- See #57828.
- """
- from hermes_cli.update_cmd import _m
try:
- from tools import lazy_deps
- except Exception as exc:
- logger.debug("Lazy refresh skipped (import failed): %s", exc)
- return True
+ from pm.ensure import sync_venv
- active = features
- if active is None:
- try:
- active = lazy_deps.active_features()
- except Exception as exc:
- logger.debug("Lazy refresh skipped (active_features failed): %s", exc)
- return True
- if not active:
+ sync_venv(features, explicit=True)
return True
-
- print()
- print(f"→ Refreshing {len(active)} active lazy backend(s)...")
-
- unexpected_failure = False
- try:
- results = (
- lazy_deps.refresh_active_features(prompt=False) if features is None
- else lazy_deps.restore_features(active))
except Exception as exc:
- # refresh_active_features is never-raise by contract; defend anyway.
- print(f" ⚠ Lazy refresh failed unexpectedly: {exc}")
- results = {}
- unexpected_failure = True
-
- refreshed = [f for f, s in results.items() if s in {"refreshed", "restored"}]
- current = [f for f, s in results.items() if s == "current"]
- failed = [(f, s) for f, s in results.items() if s.startswith("failed:")]
- skipped = [(f, s) for f, s in results.items() if s.startswith("skipped:")]
-
- if refreshed:
- print(f" ↑ {len(refreshed)} refreshed: {', '.join(refreshed)}")
- if current:
- print(f" ✓ {len(current)} already current")
- if skipped:
- # Usually security.allow_lazy_installs=false; informational, not an error.
- names = ", ".join(f for f, _ in skipped)
- reason = skipped[0][1].split(": ", 1)[-1]
- print(f" · {len(skipped)} skipped ({reason}): {names}")
-
- if not failed and not unexpected_failure:
- return True
-
- for feature, status in failed:
- print(f" ⚠ {feature} failed to refresh: {_clip(status.split(': ', 1)[-1])}")
-
- if install_cmd_prefix is None:
- print(" ⚠ Lazy refresh failed; rerun `hermes update` once resolved.")
+ print(f" ⚠ Extra re-sync failed: {exc}")
+ print(" Rerun `hermes update` (or `hermes pm install`) once resolved.")
return False
- # Import-based recovery: metadata-only verifiers miss dist-info intact but import files
- # wiped. Unavailable probes are indeterminate, not healthy — keep the lazy marker.
- # See #57828.
- status = _m()._repair_venv_via_import_probes(install_cmd_prefix, env=env)
- if status == "repaired":
- print(" Lazy backend(s) keep their previous version until refresh succeeds.")
- return True
- if status == "healthy":
- print(" Lazy backend(s) keep their previous version; probed packages look intact.")
- print(" Rerun `hermes update` once the upstream issue is resolved.")
- return True
- if status == "indeterminate":
- print(" ⚠ Leaving `.lazy-refresh-incomplete` until import probes can confirm health.")
- return False
-
def _refresh_active_memory_provider_dependencies() -> None:
"""Refresh pip deps for the configured external memory provider: its bridge packages live in
@@ -1026,10 +958,10 @@ def _sync_python_dependencies_after_pull(
# Stale pip can fail source builds and leave partially-written packages.
# See #57828.
_write_lazy_refresh_incomplete_marker()
- _m()._upgrade_pip_before_lazy_refresh(install_prefix, env=lazy_env)
+ _upgrade_pip_before_lazy_refresh(install_prefix, env=lazy_env)
# Clear the lazy marker only when refresh/repair is confirmed healthy.
- if _m()._refresh_active_lazy_features(install_prefix, env=lazy_env, features=active_lazy_features):
+ if _refresh_active_lazy_features(install_prefix, env=lazy_env, features=active_lazy_features):
_m()._clear_lazy_refresh_incomplete_marker()
else:
print(
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index fe7434ad722..814a803ab9e 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -23,7 +23,7 @@ from hermes_cli.update_cmd_common import _best_effort
logger = logging.getLogger("hermes_cli.update_cmd")
-_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "tools.lazy_deps"
+_UPDATE_RUNTIME_RELOAD_MODULES = "hermes_constants", "tools.environments.local", "pm.extras"
#: Package prefixes whose cached modules go stale when the checkout changes under this
#: process; purged (not reloaded) so any LATER import chain resolves against fresh source.
@@ -862,7 +862,7 @@ def _sweep_bytecode_after_update(branch: str) -> None:
from hermes_cli.update_cmd import _m
# The update process is still the old Python interpreter process. Run one final cache/module refresh
# immediately before lazy backend refresh, which imports newly-pulled modules that may depend on fresh
- # symbols in hermes_constants or lazy_deps. The dependency install above may also have regenerated
+ # symbols in hermes_constants or pm.extras. The dependency install above may also have regenerated
# bytecode from build-cache copies — this second sweep catches those stragglers (#60242, #65240).
removed = _m()._clear_bytecode_cache(_m().PROJECT_ROOT)
if removed:
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py
index 11485d22926..07a3a5aa930 100644
--- a/hermes_cli/web_routers/memory_providers.py
+++ b/hermes_cli/web_routers/memory_providers.py
@@ -329,29 +329,56 @@ def _command_result(
}
-def _install_memory_provider_pip_dependencies(dependencies: List[str]) -> List[Dict[str, Any]]:
- if not dependencies:
- return []
+def _install_memory_provider_pip_dependencies(name: str, dependencies: List[str]) -> List[Dict[str, Any]]:
+ extra = str(_memory_provider_manifest(name).get("extra") or "").strip()
missing = [dep for dep in dependencies if not _dependency_importable(dep)]
+ need_sync, already = bool(missing), False
if not missing:
+ if not dependencies and not extra:
+ return [] # nothing declared, nothing pm owns
+ if extra:
+ # The pm extra may still be un-synced on this machine even when
+ # every declared pip name imports (fresh checkout, rebuilt venv).
+ try:
+ import pm
+ already = pm.available(extra)
+ except Exception:
+ already = False
+ need_sync = not already
+ if already and not dependencies:
+ return [] # extra healthy and nothing declared to report on
+ else:
+ already = True # declared deps all importable and no extra
+ if not need_sync:
return [_command_result(kind="pip", name=", ".join(dependencies), status="already_installed")]
- # Route through the lazy-install pipeline rather than pip against
- # sys.executable: on hosted/immutable images the agent venv is sealed
- # read-only and installs must go to HERMES_LAZY_INSTALL_TARGET, which
- # install_specs also activates on sys.path so the recheck sees the packages.
- name = ", ".join(missing)
+ # Route through pm's venv sync of the provider's declared extra (NS-605
+ # lineage): pm owns HOW (uv sync inside the venv package), so installs
+ # honor the sealed/managed-venv policy. A direct
+ # ``pip install --python sys.executable`` would corrupt a sealed venv.
+ display = ", ".join(missing) or extra
+ command = "hermes pm install"
try:
- from tools.lazy_deps import install_specs
- outcome = install_specs(missing, timeout=240)
+ import pm
+ extra = str(_memory_provider_manifest(name).get("extra") or "").strip()
+ if extra:
+ pm.sync_venv([extra], explicit=True)
+ else:
+ # No ``extra:`` — the legacy third-party shape. Bridge the
+ # declared pip_dependencies into the pm workspace union (a
+ # generated pyproject.toml member) and sync the venv; the
+ # member stamp picks the specs up on the next apply.
+ from pathlib import Path as _Path
+ from plugins.memory import find_provider_dir
+ from pm.workspace import materialize_legacy_pyproject
+ plugin_dir = find_provider_dir(name)
+ if plugin_dir is not None:
+ materialize_legacy_pyproject(_Path(plugin_dir))
+ pm.sync_venv(explicit=True)
except Exception as exc:
- return [_command_result(kind="pip", name=name, status="failed", error=str(exc))]
- if outcome.blocked:
- return [_command_result(kind="pip", name=name, status="failed", command=outcome.command, error=outcome.reason)]
+ return [_command_result(kind="pip", name=display, status="failed", command=command, error=str(exc))]
return [_command_result(
- kind="pip", name=name, status="installed" if outcome.ok else "failed", command=outcome.command,
- completed=subprocess.CompletedProcess(
- args=outcome.command, returncode=0 if outcome.ok else 1, stdout=outcome.stdout, stderr=outcome.stderr,
- ),
+ kind="pip", name=display, status="installed", command=command,
+ completed=subprocess.CompletedProcess(args=command, returncode=0),
)]
@@ -396,7 +423,7 @@ def _install_memory_provider_setup(name: str) -> Dict[str, Any]:
if provider is None and not manifest:
raise _unknown_provider(name)
setup = _memory_provider_setup_manifest(name)
- results = _install_memory_provider_pip_dependencies(setup["pip_dependencies"])
+ results = _install_memory_provider_pip_dependencies(name, setup["pip_dependencies"])
results.extend(_install_memory_provider_external_dependencies(setup["external_dependencies"]))
if not results:
results.append(_command_result(kind="setup", name=name, status="no_declared_steps"))
diff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.py
index 8f736751cce..f087773c1da 100644
--- a/plugins/memory/mem0/__init__.py
+++ b/plugins/memory/mem0/__init__.py
@@ -150,11 +150,12 @@ 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.
+ # Lazy-install the mem0 SDK before the backend imports it (pm honors
+ # security.allow_lazy_installs); 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 as _lazy_ensure
+ _lazy_ensure("mem0")
try:
from . import _backend
if self._mode == "oss":
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index 6fc3cda0e51..05070be6b7b 100644
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@ -100,8 +100,8 @@ def ensure_dingtalk_deps() -> bool:
if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:
return True
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("platform.dingtalk", prompt=False)
+ from pm import ensure_import as _lazy_ensure
+ _lazy_ensure("dingtalk")
import dingtalk_stream as _ds, httpx as _httpx # noqa: E401
from dingtalk_stream import ChatbotMessage as _CM
from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 50c9a33b8b8..e8524bd1c28 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -2958,7 +2958,7 @@ def interactive_setup() -> None:
print_info(f" Error: {exc}")
except ImportError:
try:
- _lazy_ensure("platform.matrix", prompt=False)
+ _lazy_ensure("matrix")
print_success(f"{matrix_pkg} installed")
except Exception as exc:
print_warning(
diff --git a/plugins/web/_common.py b/plugins/web/_common.py
index 3576c399bcd..1aed751b7e1 100644
--- a/plugins/web/_common.py
+++ b/plugins/web/_common.py
@@ -168,11 +168,11 @@ def titled_rows(raw_results: List[Dict[str, Any]], description_key: str) -> List
def lazy_ensure(feature: str) -> None:
- """Best-effort ``tools.lazy_deps.ensure``: its own ImportError is benign and swallowed;
+ """Best-effort ``pm.ensure_import``: its own ImportError is benign and swallowed;
an install hint (any other error) is re-raised as ImportError."""
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure(feature, prompt=False)
+ from pm import ensure_import as _lazy_ensure
+ _lazy_ensure(feature)
except ImportError:
pass
except Exception as exc: # noqa: BLE001
diff --git a/plugins/web/exa/provider.py b/plugins/web/exa/provider.py
index f6d4dc753ba..fad5bea3b54 100644
--- a/plugins/web/exa/provider.py
+++ b/plugins/web/exa/provider.py
@@ -26,7 +26,7 @@ def _get_exa_client() -> Any:
client.headers["x-exa-integration"] = "hermes-agent"
return client
- return cached_sdk_client("_exa_client", "EXA_API_KEY", _MISSING_KEY, "search.exa", _factory)
+ return cached_sdk_client("_exa_client", "EXA_API_KEY", _MISSING_KEY, "exa", _factory)
class ExaWebSearchProvider(BaseWebSearchProvider):
diff --git a/plugins/web/parallel/provider.py b/plugins/web/parallel/provider.py
index b69647da57b..c35b7009a78 100644
--- a/plugins/web/parallel/provider.py
+++ b/plugins/web/parallel/provider.py
@@ -38,7 +38,7 @@ def _client(slot: str, cls_name: str) -> Any:
pass
except Exception as exc: # noqa: BLE001 — surface install hint as ImportError
raise ImportError(str(exc))
- return cached_sdk_client(slot, "PARALLEL_API_KEY", _MISSING_KEY, "search.parallel", _factory)
+ return cached_sdk_client(slot, "PARALLEL_API_KEY", _MISSING_KEY, "parallel-web", _factory)
def _get_sync_client() -> Any:
diff --git a/tests/conftest.py b/tests/conftest.py
index 8ffabdfe710..ae8c6209d96 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -90,6 +90,10 @@ def _hermes_home_points_at_production(value: str) -> bool:
if _hermes_home_points_at_production(os.environ.get("HERMES_HOME", "")):
_SESSION_HERMES_HOME = tempfile.mkdtemp(prefix="hermes-test-home-")
os.environ["HERMES_HOME"] = _SESSION_HERMES_HOME
+ # Marker for re-imported conftest module bodies (xdist workers exec this
+ # file more than once): the second import sees the already-redirected
+ # sandbox in the env and must not register it as a guarded "real" root.
+ os.environ["HERMES_TEST_SANDBOX_HOME"] = _SESSION_HERMES_HOME
atexit.register(shutil.rmtree, _SESSION_HERMES_HOME, True)
# PYTHONPYCACHEPREFIX is a bytecode-mirror escape hatch: when set (the
@@ -1876,6 +1880,11 @@ def _capture_real_hermes_root() -> list[Path]:
):
try:
custom = Path(_PRE_SANDBOX_HERMES_HOME).expanduser().resolve()
+ # The live session sandbox is test-owned, never a guarded root
+ # (a re-imported conftest body sees it as _PRE_SANDBOX_HERMES_HOME).
+ sandbox = os.environ.get("HERMES_TEST_SANDBOX_HOME", "")
+ if sandbox and custom == Path(sandbox).expanduser().resolve():
+ return roots
if custom not in roots:
roots.append(custom)
except Exception:
diff --git a/tests/hermes_cli/test_lazy_refresh_venv_repair.py b/tests/hermes_cli/test_lazy_refresh_venv_repair.py
index 21387cb10ca..c6f846860f9 100644
--- a/tests/hermes_cli/test_lazy_refresh_venv_repair.py
+++ b/tests/hermes_cli/test_lazy_refresh_venv_repair.py
@@ -90,55 +90,56 @@ def test_repair_runs_force_reinstall_with_pyproject_pins(
assert detect_calls["count"] == 1
-def test_refresh_repairs_venv_after_lazy_failure(tmp_path, monkeypatch, capsys):
- import tools.lazy_deps as lazy_deps_mod
+def test_refresh_resyncs_enabled_extras_via_pm(monkeypatch, capsys):
+ """The post-rebuild refresh is one explicit pm sync of the enabled extras."""
+ import importlib
- monkeypatch.setattr(lazy_deps_mod, "active_features", lambda: ["platform.matrix"])
+ pm_ensure = importlib.import_module("pm.ensure")
+
+ sync_calls: list[tuple[list[str] | None, bool]] = []
monkeypatch.setattr(
- lazy_deps_mod,
- "refresh_active_features",
- lambda **kw: {"platform.matrix": "failed: pip install failed"},
- )
+ pm_ensure, "sync_venv", lambda extras=None, *, explicit=False: sync_calls.append((extras, explicit)))
- repair_calls: list[list[str]] = []
+ ok = m._refresh_active_lazy_features(["platform.telegram"])
- def fake_repair(prefix, packages, *, env=None):
- repair_calls.append(packages)
- return True
+ assert ok is True
+ assert sync_calls == [(["platform.telegram"], True)]
+ assert "Extra re-sync failed" not in capsys.readouterr().out
- monkeypatch.setattr(main_install_repair, "_detect_broken_lazy_refresh_imports", lambda *a, **k: ["PyYAML"])
- monkeypatch.setattr(main_install_repair, "_repair_broken_lazy_refresh_imports", fake_repair)
- ok = m._refresh_active_lazy_features(["uv", "pip"], env={"VIRTUAL_ENV": str(tmp_path)})
- out = capsys.readouterr().out
+def test_refresh_reports_failure_and_stays_unsafe(monkeypatch, capsys):
+ """A failed re-sync must not read as a healthy venv."""
+ import importlib
- assert ok is True
- assert repair_calls == [["PyYAML"]]
- assert "Venv repair succeeded" in out
- assert "import probes" in out
- assert "Backends keep their previously-installed version" not in out
+ pm_ensure = importlib.import_module("pm.ensure")
+
+ def broken_sync(extras=None, *, explicit=False):
+ raise RuntimeError("uv sync failed")
+
+ monkeypatch.setattr(pm_ensure, "sync_venv", broken_sync)
+
+ assert m._refresh_active_lazy_features(["platform.telegram"]) is False
+ assert "Extra re-sync failed" in capsys.readouterr().out
def test_refresh_uses_pre_rebuild_snapshot_when_provided(monkeypatch):
- """Replacement runtimes must not re-detect features after packages vanish."""
- import tools.lazy_deps as lazy_deps_mod
+ """Replacement runtimes must not re-detect enabled extras after packages vanish."""
+ import importlib
+
+ pm_ensure = importlib.import_module("pm.ensure")
monkeypatch.setattr(
- lazy_deps_mod,
- "active_features",
+ pm_ensure, "enabled_extras",
lambda: pytest.fail("post-rebuild detection must not run"),
)
- restored = []
+ synced = []
monkeypatch.setattr(
- lazy_deps_mod,
- "restore_features",
- lambda features: restored.append(features) or {"platform.telegram": "restored"},
+ pm_ensure, "sync_venv",
+ lambda extras=None, *, explicit=False: synced.append((extras, explicit)),
)
- assert m._refresh_active_lazy_features(
- ["uv", "pip"], features=["platform.telegram"]
- ) is True
- assert restored == [["platform.telegram"]]
+ assert m._refresh_active_lazy_features(["platform.telegram"]) is True
+ assert synced == [(["platform.telegram"], True)]
def test_capture_active_tool_dependencies_uses_tools_status_probes(monkeypatch):
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 18fd456f8f0..07bc417cc66 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -1273,10 +1273,8 @@ class TestWebServerEndpoints:
# .install_method stamp of 'apt' now resolves to 'unknown' (see
# detect_install_method) and gets the generic "hermes update"
# guidance instead of Termux-specific refusal.
- import hermes_cli.web_server as web_server
-
- monkeypatch.setattr(web_server, "_dashboard_local_update_managed_externally", lambda: False)
- monkeypatch.setattr(web_server, "detect_install_method", lambda _root: "unknown")
+ monkeypatch.setattr(_web_server_files, "_dashboard_local_update_managed_externally", lambda: False)
+ monkeypatch.setattr(_cfg_mod, "detect_install_method", lambda _root: "unknown")
check = self.client.get("/api/hermes/update/check")
assert check.status_code == 200
diff --git a/tests/pm/test_no_lazy_deps.py b/tests/pm/test_no_lazy_deps.py
index 37f3ec8092a..ce18cca59d7 100644
--- a/tests/pm/test_no_lazy_deps.py
+++ b/tests/pm/test_no_lazy_deps.py
@@ -1,72 +1,115 @@
-"""Contract: no production code imports the deleted tools.lazy_deps.
+"""Behavioral contract: the lazy-install surface is pm, not the deleted tools.lazy_deps.
tools/lazy_deps.py was deleted by the pm migration; pm.extras (available /
-ensure_import / ensure_and_bind) is the only lazy-install surface. A new
-``from tools.lazy_deps import ...`` in production code is a crash at call
-time (ImportError), so this contract keeps the migration complete.
-
-Exclusions, each load-bearing:
-- ``scripts/release.py`` — a contributor-credit COMMENT referencing a
- historical PR title; not an import, harmless.
-- ``tests/`` — tests may reference lazy_deps to assert it is gone.
+ensure_import) is the only lazy-install surface. The migrated real modules
+keep working call paths — verified here through their public functions with
+the pm seam monkeypatched (DI at the real boundary, no source scanning).
+
+Callers pass the pm extra (pyproject extra name) directly — there is no
+legacy feature-id translation layer.
"""
from __future__ import annotations
-from pathlib import Path
-
-# Directories that are not production source, or that mirror it.
-_EXCLUDED_DIRS = {
- "node_modules",
- ".venv",
- "venv",
- "build",
- "dist",
- "release",
- "__pycache__",
- "agent-payload",
- ".git",
-}
-
-# Files allowed to mention lazy_deps (see docstring for why).
-_ALLOWED = {
- # historical contributor-credit comment (PR #26294 in the credit map)
- "scripts/release.py",
- # the dashboard's legacy-pip-deps surface documents the old pipeline
- # it replaced until the workspace bridge wires it (see plugin-deps plan).
- "hermes_cli/web_server.py",
-}
-
-
-def _production_python_files(repo_root: Path):
- for path in repo_root.rglob("*.py"):
- rel = path.relative_to(repo_root).as_posix()
- if not rel.startswith("tests/") and rel not in _ALLOWED:
- if not any(part in _EXCLUDED_DIRS for part in path.parts):
- yield rel, path
-
-
-def test_no_production_imports_of_lazy_deps():
- """Every production .py must be free of tools.lazy_deps imports."""
- repo_root = Path(__file__).resolve().parents[2]
- offenders: list[str] = []
- pattern = "tools.lazy_deps"
- try:
- candidates = list(_production_python_files(repo_root))
- except OSError:
- # rglob can raise FileNotFoundError on a dangling worktree junction
- # (WinError 3) mid-walk on Windows — not this contract's business.
- candidates = []
- for rel, path in candidates:
- try:
- text = path.read_text(encoding="utf-8-sig")
- except (OSError, UnicodeDecodeError):
- # Broken junctions/dangling links raise on read.
- continue
- if pattern in text:
- offenders.append(rel)
- assert not offenders, (
- "production code references tools.lazy_deps (deleted module — "
- "ImportError at call time). Migrate to pm.ensure_import / "
- f"pm.extras: {offenders}"
- )
+import pytest
+
+
+def pm_seam(monkeypatch):
+ """Patch the pm module attributes the migrated modules import at call time."""
+ import pm
+
+ seen: list[str] = []
+ monkeypatch.setattr(pm, "ensure_import", lambda extra: seen.append(extra))
+ monkeypatch.setattr(pm, "sync_venv", lambda extras=None, explicit=False: seen.extend(extras or ()))
+ monkeypatch.setattr(pm, "available", lambda extra: False)
+ monkeypatch.setattr(pm, "lazy_installs_allowed", lambda: True)
+ return seen
+
+
+def test_web_common_lazy_ensure_passes_extra_through(pm_seam):
+ from plugins.web import _common
+
+ _common.lazy_ensure("exa")
+ _common.lazy_ensure("parallel-web")
+ assert pm_seam == ["exa", "parallel-web"]
+
+
+def test_web_common_lazy_ensure_swallows_import_error(monkeypatch):
+ import pm
+ from plugins.web import _common
+
+ def _boom(extra):
+ raise ImportError("nope")
+
+ monkeypatch.setattr(pm, "ensure_import", _boom)
+ _common.lazy_ensure("exa") # must not raise
+
+
+def test_web_common_lazy_ensure_reraises_other_failures_as_import_error(monkeypatch):
+ import pm
+ from plugins.web import _common
+
+ def _blocked(extra):
+ raise RuntimeError("lazy installs disabled")
+
+ monkeypatch.setattr(pm, "ensure_import", _blocked)
+ with pytest.raises(ImportError):
+ _common.lazy_ensure("exa")
+
+
+def test_remote_common_ensures_declared_extras(pm_seam):
+ from tools.environments import remote_common
+
+ remote_common.ensure_lazy_dep("modal")
+ remote_common.ensure_lazy_dep("daytona")
+ assert pm_seam == ["modal", "daytona"]
+
+
+def test_remote_common_reraises_failure_as_import_error(monkeypatch):
+ from tools.environments import remote_common
+
+ def _blocked(extra):
+ raise RuntimeError("not supported on this platform")
+
+ import pm
+ monkeypatch.setattr(pm, "ensure_import", _blocked)
+ with pytest.raises(ImportError):
+ remote_common.ensure_lazy_dep("modal")
+
+
+def test_transcription_common_quietly_ensures(pm_seam):
+ from tools import transcription_common
+
+ transcription_common._lazy_ensure_quietly("silk")
+ transcription_common._lazy_ensure_quietly("mistral")
+ assert pm_seam == ["silk", "mistral"]
+
+
+def test_transcription_common_swallows_all_failures(monkeypatch):
+ import pm
+ from tools import transcription_common
+
+ def _boom(extra):
+ raise RuntimeError("offline")
+
+ monkeypatch.setattr(pm, "ensure_import", _boom)
+ transcription_common._lazy_ensure_quietly("silk") # must not raise
+
+
+def test_tts_lifecycle_warms_through_pm_extras(pm_seam, monkeypatch):
+ from tools import tts_tool_lifecycle
+
+ result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})
+ assert result == {"provider": "edge", "warmed": True, "action": "installed"}
+ assert pm_seam == ["edge-tts"]
+
+
+def test_tts_lifecycle_feature_map_targets_declared_extras():
+ """Every mapped pm extra must be a real pyproject extra with an anchor."""
+ from pm.extras import ANCHORS
+ from tools import tts_tool_lifecycle
+
+ assert tts_tool_lifecycle._LAZY_SDK_FEATURES
+ for extra in tts_tool_lifecycle._LAZY_SDK_FEATURES.values():
+ assert extra in ANCHORS, extra
diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.py
index e9d7b50b326..35fc5afe1bd 100644
--- a/tests/tools/test_transcription_tools.py
+++ b/tests/tools/test_transcription_tools.py
@@ -1203,12 +1203,14 @@ class TestRunCommandSttIdleTimeout:
from tools.transcription_command import _run_command_stt
script = tmp_path / "progress_then_exit.py"
+ # Ticks span >2s so the idle deadline MUST be reset by progress: a
+ # one-shot timeout of 2.0s would kill the child before it exits.
script.write_text(
"\n".join([
"import sys, time",
- "for idx in range(4):",
+ "for idx in range(6):",
" print(f'tick {idx}', file=sys.stderr, flush=True)",
- " time.sleep(0.04)",
+ " time.sleep(0.5)",
"print('done', flush=True)",
]),
encoding="utf-8",
@@ -1216,7 +1218,10 @@ class TestRunCommandSttIdleTimeout:
result = _run_command_stt(
self._shell_command(sys.executable, "-u", str(script)),
- timeout=0.1,
+ # The idle window must dwarf process startup on every host: a
+ # fresh Windows spawn can take far longer than 0.1s to emit its
+ # first byte, which is startup latency, not an idle stall.
+ timeout=2.0,
)
assert result.returncode == 0
diff --git a/tests/tools/test_tts_lifecycle_leases.py b/tests/tools/test_tts_lifecycle_leases.py
index 41a75c04da0..09906d58e85 100644
--- a/tests/tools/test_tts_lifecycle_leases.py
+++ b/tests/tools/test_tts_lifecycle_leases.py
@@ -9,6 +9,8 @@ resident local models.
from __future__ import annotations
+import os
+import subprocess
import threading
import pytest
@@ -116,30 +118,27 @@ def test_warm_is_noop_for_cloud_provider_without_lazy_sdk(monkeypatch):
def test_warm_lazy_sdk_provider_reports_cached_when_installed(monkeypatch):
- import types
+ import pm
- fake = types.SimpleNamespace(
- is_available=lambda feature: feature == "tts.edge",
- ensure=lambda *a, **k: pytest.fail("ensure must not run when the SDK is present"),
+ monkeypatch.setattr(pm, "available", lambda extra: extra == "edge-tts")
+ monkeypatch.setattr(
+ pm, "ensure_import",
+ lambda extra: pytest.fail("ensure_import must not run when the SDK is present"),
)
- monkeypatch.setitem(__import__("sys").modules, "tools.lazy_deps", fake)
result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})
assert result["warmed"] is True
assert result["action"] == "cached"
def test_warm_lazy_sdk_provider_installs_when_missing(monkeypatch):
- import types
+ import pm
calls = []
- fake = types.SimpleNamespace(
- is_available=lambda feature: False,
- ensure=lambda feature, prompt: calls.append((feature, prompt)),
- )
- monkeypatch.setitem(__import__("sys").modules, "tools.lazy_deps", fake)
+ monkeypatch.setattr(pm, "available", lambda extra: False)
+ monkeypatch.setattr(pm, "ensure_import", lambda extra: calls.append(extra))
result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})
assert result["action"] == "installed"
- assert calls == [("tts.edge", False)]
+ assert calls == ["edge-tts"]
# --------------------------------------------------------------------------
@@ -302,4 +301,13 @@ def test_command_provider_runs_warm_and_release_commands(monkeypatch):
done.clear()
tts_tool_lifecycle.release_tts_lease("desktop:read-aloud")
assert done.wait(5)
- assert ran == ["curl -s localhost:5002/load?model='kokoro v1'", "curl -s localhost:5002/unload"]
+ # Native platform-as-data: the placeholder renderer quotes for the HOST
+ # shell — POSIX shlex (single quotes) vs Windows list2cmdline (double
+ # quotes) — so the expected string is built with the same native contract
+ # instead of freezing one platform's quoting.
+ if os.name == "nt":
+ expected_model = subprocess.list2cmdline(["kokoro v1"])
+ else:
+ import shlex
+ expected_model = shlex.quote("kokoro v1")
+ assert ran == [f"curl -s localhost:5002/load?model={expected_model}", "curl -s localhost:5002/unload"]
diff --git a/tools/browser_tool_install.py b/tools/browser_tool_install.py
index f4df1d2f4a9..2681e3f272c 100644
--- a/tools/browser_tool_install.py
+++ b/tools/browser_tool_install.py
@@ -254,8 +254,8 @@ def _maybe_autoinstall_chromium() -> bool:
_bt._chromium_autoinstall_attempted = True
if _running_in_docker():
return False
- from tools.lazy_deps import _allow_lazy_installs
- if not _allow_lazy_installs():
+ from pm import lazy_installs_allowed
+ if not lazy_installs_allowed():
return False
try:
browser_cmd = _find_agent_browser()
diff --git a/tools/environments/daytona.py b/tools/environments/daytona.py
index 678becda4c3..b96d70de36a 100644
--- a/tools/environments/daytona.py
+++ b/tools/environments/daytona.py
@@ -34,7 +34,7 @@ class DaytonaEnvironment(BaseEnvironment):
memory: int = 5120, disk: int = 10240, persistent_filesystem: bool = True,
task_id: str = "default"):
super().__init__(cwd=cwd, timeout=timeout)
- ensure_lazy_dep("terminal.daytona")
+ ensure_lazy_dep("daytona")
from daytona import Daytona, CreateSandboxFromImageParams, DaytonaError, Resources, SandboxState
try:
diff --git a/tools/environments/modal.py b/tools/environments/modal.py
index 94aa2de3aa9..0b5316328e9 100644
--- a/tools/environments/modal.py
+++ b/tools/environments/modal.py
@@ -62,7 +62,7 @@ def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> Non
def _resolve_modal_image(image_spec: Any) -> Any:
"""Convert registry references or snapshot ids into Modal image objects. Registry images
get pip repaired (ensurepip) before Modal's bootstrap; ubuntu/debian also get python3."""
- ensure_lazy_dep("terminal.modal")
+ ensure_lazy_dep("modal")
import modal as _modal
if not isinstance(image_spec, str):
@@ -146,7 +146,7 @@ class ModalEnvironment(BaseEnvironment):
_get_snapshot_restore_candidate(self._task_id) if self._persistent else (None, False))
if restored_snapshot_id:
logger.info("Modal: restoring from snapshot %s", restored_snapshot_id[:20])
- ensure_lazy_dep("terminal.modal")
+ ensure_lazy_dep("modal")
import modal as _modal
cred_mounts = []
try:
diff --git a/tools/environments/remote_common.py b/tools/environments/remote_common.py
index 17783dc0ed4..343bc79237c 100644
--- a/tools/environments/remote_common.py
+++ b/tools/environments/remote_common.py
@@ -20,12 +20,12 @@ def bash_argv(cmd_string: str, login: bool = False) -> list[str]:
def ensure_lazy_dep(feature: str) -> None:
- """Lazy-install an optional SDK via ``tools.lazy_deps`` (idempotent). Missing ``tools.lazy_deps``
+ """Lazy-install an optional SDK via ``pm.ensure_import`` (idempotent). Missing ``pm``
is tolerated (the SDK import that follows fails with its own message); any other failure
surfaces as ``ImportError``."""
try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure(feature, prompt=False)
+ from pm import ensure_import as _lazy_ensure
+ _lazy_ensure(feature)
except ImportError:
pass
except Exception as e:
diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.py
index d138135b8c4..991e00bd971 100644
--- a/tools/environments/vercel_sandbox.py
+++ b/tools/environments/vercel_sandbox.py
@@ -25,8 +25,6 @@ from hermes_constants import get_hermes_home
from tools.environments.base import BaseEnvironment, _load_json_store, _save_json_store
from tools.environments.base_output import _ThreadedProcessHandle
from tools.environments.file_sync import FileSyncManager, iter_sync_files, quoted_rm_command
-from tools.environments.remote_common import ensure_lazy_dep
-
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
diff --git a/tools/transcription_audio.py b/tools/transcription_audio.py
index 45658e01b4e..a77e547e9eb 100644
--- a/tools/transcription_audio.py
+++ b/tools/transcription_audio.py
@@ -121,7 +121,7 @@ def _prepare_audio_for_transcription(file_path: str) -> tuple[Optional[str], Opt
return file_path, None, None
if not _HAS_PILK:
# pilk is a tiny silk-v3 codec binding — lazy-installed on first .silk voice note.
- _lazy_ensure_quietly("stt.silk")
+ _lazy_ensure_quietly("silk")
if not _safe_find_spec("pilk"):
return None, None, _error_result(
"Unsupported format: .silk. Install the optional 'pilk' dependency to enable WeChat voice transcription."
diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.py
index 21cfbb36495..ff487dc86d6 100644
--- a/tools/transcription_cloud.py
+++ b/tools/transcription_cloud.py
@@ -174,7 +174,7 @@ def _transcribe_mistral(
if not api_key:
return _error_result("MISTRAL_API_KEY not set")
try:
- _lazy_ensure_quietly("stt.mistral")
+ _lazy_ensure_quietly("mistral")
from mistralai.client import Mistral
with Mistral(api_key=api_key) as client, open(file_path, "rb") as audio_file:
# Language: hook override > stt.mistral.language > stt.language > env > auto.
diff --git a/tools/transcription_common.py b/tools/transcription_common.py
index 95b491e3ce3..a1e0903bab8 100644
--- a/tools/transcription_common.py
+++ b/tools/transcription_common.py
@@ -58,12 +58,12 @@ def _ok_result(transcript: str, provider: str) -> Dict[str, Any]:
def _lazy_ensure_quietly(dep: str) -> None:
- """Best-effort ``tools.lazy_deps.ensure(dep, prompt=False)``; failures are swallowed.
- prompt=False: a bare input() deadlocks under the interactive CLI where prompt_toolkit owns
- stdin; installs are gated by ``security.allow_lazy_installs``."""
+ """Best-effort ``pm.ensure_import`` (callers pass the pm extra directly); failures are
+ swallowed. Installs are gated by ``security.allow_lazy_installs``; the old
+ ``prompt=False`` semantics carry over (pm never prompts)."""
try:
- from tools.lazy_deps import ensure
- ensure(dep, prompt=False)
+ from pm import ensure_import
+ ensure_import(dep)
except Exception:
pass
diff --git a/tools/transcription_local.py b/tools/transcription_local.py
index 1dfd606db5e..c4cd0c4d94d 100644
--- a/tools/transcription_local.py
+++ b/tools/transcription_local.py
@@ -58,11 +58,10 @@ def _normalize_local_model(model_name: Optional[str]) -> str:
def _try_lazy_install_stt() -> bool:
"""Lazy-install faster-whisper and re-check dynamically so it's usable without a restart."""
try:
- from tools.lazy_deps import ensure
- # prompt=False: a bare input() deadlocks under the interactive CLI where prompt_toolkit
- # owns stdin; the install is already gated by security.allow_lazy_installs.
- # prompt=False: never raise a blocking input() prompt mid-session. See #40490.
- ensure("stt.faster_whisper", prompt=False)
+ from pm import ensure_import
+ # pm never prompts mid-session (installs are gated by
+ # security.allow_lazy_installs). See #40490.
+ ensure_import("stt-whisper")
if _ilu.find_spec("faster_whisper"):
return True
logger.warning("faster-whisper was installed but importlib still cannot find it (may require Python restart)")
diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.py
index d454c0e0c4d..ee435322f2d 100644
--- a/tools/tts_tool_lifecycle.py
+++ b/tools/tts_tool_lifecycle.py
@@ -38,8 +38,8 @@ def _local_tts_warmers() -> Dict[str, Callable[[Dict[str, Any]], Any]]:
"kittentts": lambda cfg: _load_kittentts_model_for_config(cfg)[0]}
-# tools.lazy_deps feature key for providers whose SDK installs on first use.
-_LAZY_SDK_FEATURES = {"edge": "tts.edge", "elevenlabs": "tts.elevenlabs", "mistral": "tts.mistral"}
+# pm extra installed on first use, per provider whose SDK lazy-installs.
+_LAZY_SDK_FEATURES = {"edge": "edge-tts", "elevenlabs": "tts-premium", "mistral": "mistral"}
def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str) -> Optional[str]:
@@ -111,11 +111,11 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Opt
feature = _LAZY_SDK_FEATURES.get(name)
if feature is not None:
try:
- from tools.lazy_deps import ensure, is_available
- if is_available(feature):
+ from pm import available as _pm_available, ensure_import as _pm_ensure_import
+ if _pm_available(feature):
result.update(warmed=True, action="cached")
else:
- ensure(feature, prompt=False)
+ _pm_ensure_import(feature)
result.update(warmed=True, action="installed")
except Exception as exc:
logger.debug("[TTS] SDK warm-up for %s skipped: %s", name, exc)
diff --git a/tools/wake_word.py b/tools/wake_word.py
index 0189fd7c0dc..ffb821298c7 100644
--- a/tools/wake_word.py
+++ b/tools/wake_word.py
@@ -42,12 +42,12 @@ _DEFAULT_CONFIRMATION_FRAMES = 3
_SILENCE_PEAK = 10
_SILENCE_ALERT_SECONDS = 10
-# provider alias -> (engine class name on this module, lazy_deps feature).
+# provider alias -> (engine class name on this module, pm extra).
# Unknown providers probe as openwakeword but fail to build.
_PROVIDERS: Dict[str, tuple[str, str]] = {
- "porcupine": ("_PorcupineEngine", "wake.porcupine"),
- **{k: ("_SherpaKwsEngine", "wake.sherpa") for k in ("sherpa", "sherpa-onnx", "kws", "open")},
- **{k: ("_OpenWakeWordEngine", "wake.openwakeword") for k in ("openwakeword", "oww", "local")},
+ "porcupine": ("_PorcupineEngine", "wake-porcupine"),
+ **{k: ("_SherpaKwsEngine", "wake-sherpa") for k in ("sherpa", "sherpa-onnx", "kws", "open")},
+ **{k: ("_OpenWakeWordEngine", "wake-openwakeword") for k in ("openwakeword", "oww", "local")},
}
@@ -779,7 +779,7 @@ def check_wake_word_requirements(cfg: Optional[Dict[str, Any]] = None) -> Dict[s
# Ordered remediation ladder: first true predicate wins.
ladder = (
(not key_ok, lambda: "Set PORCUPINE_ACCESS_KEY (free key at https://console.picovoice.ai)."),
- (not deps_ok and not lazy_ok, lambda: lazy_deps.feature_install_command(feature) or ""),
+ (not deps_ok and not lazy_ok, lambda: f"uv sync --frozen --extra {feature}"),
(not tflite_ok,
lambda: "The wake word needs the tflite runtime on this Mac: pip install ai-edge-litert"),
(deps_ok and not audio_ok and capture_mode == "local",
diff --git a/tools/wake_word_engines.py b/tools/wake_word_engines.py
index 2a9e623433d..d98c4916471 100644
--- a/tools/wake_word_engines.py
+++ b/tools/wake_word_engines.py
@@ -21,13 +21,14 @@ def _ww():
def _ensure_dep(feature: str) -> None:
- from tools import lazy_deps
- lazy_deps.ensure(feature, prompt=False)
+ # pm never prompts mid-session (installs are gated by security.allow_lazy_installs).
+ import pm
+ pm.ensure_import(feature)
class _Engine:
"""Minimal hotword-engine contract: feed int16 frames, get a bool. Subclasses set ``feature``
- (lazy_deps name, ensured before ``_build``) and their own ``cfg`` sub-section ``section``."""
+ (pm extra, ensured before ``_build``) and their own ``cfg`` sub-section ``section``."""
feature: str = ""
section: str = ""
@@ -68,7 +69,7 @@ class _OpenWakeWordEngine(_Engine):
``sensitivity`` IS the raw 0..1 threshold (higher = stricter). A real utterance holds the score
high across frames while a stray phoneme spikes one, so ``confirmation_frames`` hits are required."""
- feature, section = "wake.openwakeword", "openwakeword"
+ feature, section = "wake-openwakeword", "openwakeword"
frame_length = 1280 # openWakeWord recommends 80 ms frames.
def _build(self, cfg, sub, ww) -> None:
@@ -168,7 +169,7 @@ class _SherpaKwsEngine(_Engine):
"""sherpa-onnx open-vocabulary keyword spotting — any typed phrase, zero training. ``wake_word.phrase``
is BPE-tokenized at runtime against the model's vocabulary: DETECTION config, not a cosmetic label."""
- feature, section = "wake.sherpa", "sherpa"
+ feature, section = "wake-sherpa", "sherpa"
frame_length = 1280 # streaming zipformer accepts any chunk; match capture path.
def _build(self, cfg, sub, ww) -> None:
@@ -247,7 +248,7 @@ class _SherpaKwsEngine(_Engine):
class _PorcupineEngine(_Engine):
"""Picovoice Porcupine — premium, on-device, needs an access key."""
- feature, section = "wake.porcupine", "porcupine"
+ feature, section = "wake-porcupine", "porcupine"
def _build(self, cfg, sub, ww) -> None:
import pvporcupine