The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): migrate the last tools.lazy_deps call sites to pm extras
ethernet52510d26fd81
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex f5dea261213..7712f571987 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -136,12 +136,12 @@ def _get_anthropic_sdk():global _anthropic_sdkif _anthropic_sdk is ...:try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("provider.anthropic", prompt=False)+ from pm import ensure_import+ ensure_import("anthropic")except ImportError:passexcept Exception:- # FeatureUnavailable — fall through to ImportError handling below+ # InstallError — fall through to ImportError handling belowpasstry:import anthropic as _sdkdiff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 5cc6cfaf63b..77fe99e715b 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -123,8 +123,8 @@ except ImportError:# running `hermes dashboard` needs fastapi+uvicorn; lazy install keeps# them out of every other install path. After install, re-import.try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("tool.dashboard", prompt=False)+ from pm import ensure_import+ ensure_import("web")from fastapi import (FastAPI, File, Form, HTTPException, Query, Request, UploadFile,WebSocket, WebSocketDisconnect,@@ -6588,52 +6588,23 @@ def _install_memory_provider_pip_dependencies(dependencies: List[str]) -> List[D_command_result(kind="pip", name=", ".join(dependencies), status="already_installed")]- # Route through the lazy-install pipeline (tools.lazy_deps.install_specs)- # instead of shelling out to pip against sys.executable directly. That- # pipeline is environment-aware: on hosted/immutable images the agent venv- # under /opt/hermes is sealed read-only, and installs must be redirected- # to the writable durable target on the data volume- # (HERMES_LAZY_INSTALL_TARGET, e.g. /opt/data/lazy-packages) — the same- # path every lazy backend already uses. A direct `pip install --python- # sys.executable` on those images fails with a permission error (NS-605).- # install_specs also activates the target on sys.path post-install so the- # availability recheck below sees the new packages without a restart.- try:- from tools.lazy_deps import install_specs-- outcome = install_specs(missing, timeout=240)- except Exception as exc:- return [- _command_result(- kind="pip",- name=", ".join(missing),- status="failed",- error=str(exc),- )- ]-- if outcome.blocked:- return [- _command_result(- kind="pip",- name=", ".join(missing),- status="failed",- command=outcome.command,- error=outcome.reason,- )- ]-+ # The old tools.lazy_deps.install_specs pipeline is gone (pm migration).+ # Arbitrary pip specs from memory-provider manifests are the legacy+ # `pip_dependencies` surface: the install path is the plugin-deps+ # workspace union (pm builds the workspace root, uv lock, uv sync+ # --frozen), which runs from `hermes plugins install` / the pm sync+ # step. Until that bridge wires THIS dashboard surface, report the+ # exact manual remedy instead of an opaque import failure.+ manual = f"uv pip install {' '.join(repr(d) for d in missing)}"return [_command_result(kind="pip",name=", ".join(missing),- 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,+ status="failed",+ error=(+ "Legacy pip_dependencies are not auto-installed from the "+ f"dashboard yet. Run this in the hermes venv, then re-check: "+ f"{manual}"),)]diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex 0a2b4ecbb06..044f12d573e 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -1461,8 +1461,8 @@ def feishu_deps_present() -> bool:if FEISHU_AVAILABLE:return Truetry:- from tools.lazy_deps import is_available- return is_available("platform.feishu")+ from pm.extras import available+ return available("feishu")except Exception: # pragma: no cover — defensivereturn False@@ -1472,10 +1472,10 @@ def check_feishu_requirements() -> bool:if FEISHU_AVAILABLE:return True- from tools.lazy_deps import ensure+ from pm import ensure_importtry:- ensure("platform.feishu", prompt=False)+ ensure_import("feishu")return Trueexcept Exception:return Falsediff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 0a771ea789c..e672affb049 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -360,7 +360,7 @@ class _NativeTaskCardStream:def check_slack_requirements() -> bool:"""Check if Slack dependencies are available.- Lazy-installs slack-bolt/slack-sdk via ``tools.lazy_deps.ensure("platform.slack")``+ Lazy-installs the ``slack`` pyproject extra via ``pm.extras.ensure_and_bind``on first call if not present. Rebinds all module-level globals on success."""if SLACK_AVAILABLE:@@ -380,9 +380,9 @@ def check_slack_requirements() -> bool:"SLACK_AVAILABLE": True,}- from tools.lazy_deps import ensure_and_bind+ from pm.extras import ensure_and_bind- return ensure_and_bind("platform.slack", _import, globals(), prompt=False)+ return ensure_and_bind("slack", _import, globals())def _collect_slack_block_mentions(blocks: list) -> list:diff --git a/plugins/platforms/wecom/callback_adapter.py b/plugins/platforms/wecom/callback_adapter.pyindex dd0b652e0c2..c29947e53f5 100644--- a/plugins/platforms/wecom/callback_adapter.py+++ b/plugins/platforms/wecom/callback_adapter.py@@ -86,7 +86,7 @@ def ensure_wecom_callback_requirements() -> bool:aiohttp/httpx ship with every messaging install) and rebinds the moduleglobals. Before this hook existed, the passive ``check_fn`` returnedFalse forever on installs without the ``wecom`` extra and the- ``platform.wecom_callback`` LAZY_DEPS entry was never exercised.+ lazy-installer entry for wecom_callback was never exercised."""if check_wecom_callback_requirements():return Truediff --git a/pm/extras.py b/pm/extras.pyindex 92001f0211e..e157558b5a8 100644--- a/pm/extras.py+++ b/pm/extras.py@@ -58,6 +58,10 @@ ANCHORS: dict[str, str | tuple[str, ...]] = {"doc-extract": "anydoc","computer-use": "mcp","trace-upload": "huggingface_hub",+ # Pillow resize recovery for vision tools (the `vision` extra is a no-op+ # back-compat alias — Pillow is core — but ensure_import("vision") must+ # still resolve an anchor so availability checks work).+ "vision": "PIL",}diff --git a/tests/pm/test_no_lazy_deps.py b/tests/pm/test_no_lazy_deps.pynew file mode 100644index 00000000000..37f3ec8092a--- /dev/null+++ b/tests/pm/test_no_lazy_deps.py@@ -0,0 +1,72 @@+"""Contract: no production code imports 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.+"""++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}"+ )diff --git a/tests/tools/test_read_file_schema_gating.py b/tests/tools/test_read_file_schema_gating.pyindex de05bdb82fa..24b2e36bbaa 100644--- a/tests/tools/test_read_file_schema_gating.py+++ b/tests/tools/test_read_file_schema_gating.py@@ -203,17 +203,22 @@ class TestNeedsOcrPath(unittest.TestCase):self.assertNotIn("ocr-and-documents", out)def test_pin_lockstep(self):- """pyproject core pin and lazy_deps self-heal pin must match."""+ """Core and doc-extract pins of firecrawl-anydoc must agree.++ tools/lazy_deps.py is gone; pyproject.toml is the single pin+ authority. The self-heal path is now pm.ensure_import("doc-extract"),+ which syncs the extra — so the remaining lockstep contract is that+ the core dependency pin and the doc-extract extra pin name the SAME+ version (a drift here means a lean install re-syncs a different+ anydoc than a full one).+ """import refrom pathlib import Path- py = Path("pyproject.toml").read_text(encoding="utf-8")- lz = Path("tools/lazy_deps.py").read_text(encoding="utf-8")- m1 = re.search(r'"firecrawl-anydoc==([\d.]+)"', py)- m2 = re.search(r'"firecrawl-anydoc==([\d.]+)"', lz)- self.assertIsNotNone(m1)- self.assertIsNotNone(m2)- self.assertEqual(m1.group(1), m2.group(1))+ py = Path("pyproject.toml").read_text(encoding="utf-8-sig")+ pins = re.findall(r'"firecrawl-anydoc==([\d.]+)"', py)+ self.assertTrue(pins, "firecrawl-anydoc pin missing from pyproject")+ self.assertEqual(len(set(pins)), 1, f"pins disagree: {pins}")if __name__ == "__main__":diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex 5113d26699f..4d9c4a47e5c 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -2720,11 +2720,11 @@ class CuaDriverBackend(ComputerUseBackend):# Lazy-install it on first use — the same pattern every other optional# backend uses — so users never hit an opaque `No module named 'mcp'`# at invoke time. Auto-install is gated by `security.allow_lazy_installs`- # (default on); when it's disabled or fails, ensure() raises- # FeatureUnavailable carrying an actionable `uv pip install mcp==…`+ # (default on); when it's disabled or fails, ensure_import() raises+ # InstallError carrying an actionable `uv pip install mcp==…`# hint, which surfaces via the backend-unavailable path in tool.py.- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("tool.computer_use", prompt=False)+ from pm import ensure_import+ ensure_import("computer-use")# A just-installed package may not be importable until the import# machinery's caches are refreshed within this process.import importlibdiff --git a/tools/read_extract.py b/tools/read_extract.pyindex 0ce217f6eb2..242b9f7f5aa 100644--- a/tools/read_extract.py+++ b/tools/read_extract.py@@ -101,10 +101,10 @@ def _anydoc() -> Optional[Any]:):return Nonetry:- from tools.lazy_deps import ensure as _lazy_ensure+ from pm import ensure_import- # prompt=False: read_file must never block on an install prompt.- _lazy_ensure("tool.doc_extract", prompt=False)+ # read_file must never block on an install prompt.+ ensure_import("doc-extract")except Exception:_anydoc_failed_at = time.monotonic()return Nonediff --git a/tools/vision_tools.py b/tools/vision_tools.pyindex f6c1852182d..7a9a6008854 100644--- a/tools/vision_tools.py+++ b/tools/vision_tools.py@@ -951,12 +951,12 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None,# offline), then re-import. If it still isn't importable, fall back to# the raw bytes and let the caller raise the size error.try:- from tools.lazy_deps import ensure as _ensure_dep- # prompt=False: never raise a blocking input() prompt mid-session.+ from pm import ensure_import+ # never raise a blocking input() prompt mid-session.# Under the interactive CLI prompt_toolkit owns stdin, so a bare# input() deadlocks the terminal (#40490). The install is already# gated by security.allow_lazy_installs, so reaching here is opt-in.- _ensure_dep("tool.vision", prompt=False)+ ensure_import("vision")from PIL import Imageimport io as _ioexcept Exception: