The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(pm): expose Python operations instead of uv binaries
ethernetcc4818522072
diff --git a/pm/__init__.py b/pm/__init__.pyindex 76630203f37..801d1e997be 100644--- a/pm/__init__.py+++ b/pm/__init__.py@@ -21,7 +21,12 @@ from pm.ensure import (installed_package,lazy_installs_allowed,)-from pm.client import ensure, sync_venv, uv+from pm.client import (+ ensure, sync_venv, build_environment, lock_project, stage_manager_runtime,+ ensure_environment, ensure_python_tool, venv_is_current,+ check_project_lock, export_requirements, build_requirements_environment, prune_cache,+)+from pm.operations import environment_python, python_toolfrom pm.extras import available, ensure_importfrom pm.lock import Facts, Lockfilefrom pm.package import InstallError, Package, Runner, compose_env@@ -41,8 +46,18 @@ __all__ = ["ensure_import","enabled_extras","lazy_installs_allowed",- # NOTE: pm.uv is importable but deliberately not in __all__ — it is the- # marked transitional bridge for update/repair and must not spread.+ "build_environment",+ "lock_project",+ "stage_manager_runtime",+ "ensure_environment",+ "environment_python",+ "ensure_python_tool",+ "python_tool",+ "venv_is_current",+ "check_project_lock",+ "export_requirements",+ "build_requirements_environment",+ "prune_cache","Facts","Lockfile","InstallError",diff --git a/pm/build_env.py b/pm/build_env.pynew file mode 100644index 00000000000..649b79bda4a--- /dev/null+++ b/pm/build_env.py@@ -0,0 +1,92 @@+"""Build and inspect explicit Python dependency environments through PM."""+from __future__ import annotations++import argparse+from collections.abc import Sequence+from pathlib import Path+import sys+++def main(argv: Sequence[str] | None = None) -> int:+ import pm++ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--source", type=Path)+ parser.add_argument("--out", type=Path)+ parser.add_argument("--python", type=Path)+ parser.add_argument("--cache", type=Path)+ parser.add_argument("--extra", dest="extras", action="append", default=[])+ parser.add_argument("--group", dest="groups", action="append", default=[])+ parser.add_argument("--all-extras", action="store_true")+ parser.add_argument("--no-install-project", action="store_true")+ parser.add_argument("--resolve", action="store_true", help="resolve the source lock before building")+ operation = parser.add_mutually_exclusive_group()+ operation.add_argument("--lock-only", action="store_true")+ operation.add_argument("--check-lock", action="store_true")+ operation.add_argument("--export-requirements", type=Path)+ operation.add_argument("--prune-cache", action="store_true")+ operation.add_argument("--manager-runtime", action="store_true")+ parser.add_argument("--upgrade", action="store_true")+ parser.add_argument("--ci", action="store_true")+ parser.add_argument("--sealed", action="store_true")+ parser.add_argument("--offline", action="store_true")+ parser.add_argument("--explicit", action="store_true", help="CLI builds are always explicit requests")+ parser.add_argument("--wheelhouse", type=Path)+ parser.add_argument("--requirements", type=Path)+ parser.add_argument("--requirement", action="append", default=[])+ args = parser.parse_args(argv)+ requirements = list(args.requirement)+ if args.requirements is not None:+ requirements.extend(line.strip() for line in args.requirements.read_text(encoding="utf-8").splitlines()+ if line.strip() and not line.lstrip().startswith("#"))+ if args.prune_cache:+ if args.cache is None:+ parser.error("--prune-cache requires --cache")+ elif not requirements and args.source is None:+ parser.error("--source is required for project operations")+ build = not (args.lock_only or args.check_lock or args.export_requirements or args.prune_cache)+ if build and args.out is None:+ parser.error("--out is required when building an environment")+ if args.manager_runtime and args.python is None:+ parser.error("--manager-runtime requires the target --python")+ try:+ if args.prune_cache:+ pm.prune_cache(args.cache, ci=args.ci)+ return 0+ if args.check_lock:+ pm.check_project_lock(args.source, python=args.python, cache=args.cache,+ offline=args.offline, explicit=True)+ return 0+ if args.export_requirements:+ pm.export_requirements(args.source, args.export_requirements, extras=args.extras,+ python=args.python, cache=args.cache, explicit=True)+ return 0+ if args.lock_only:+ pm.lock_project(args.source, upgrade=args.upgrade, python=args.python,+ cache=args.cache, offline=args.offline, explicit=True)+ return 0+ if args.manager_runtime:+ executable = pm.stage_manager_runtime(python=args.python, destination=args.out,+ project=args.source, cache=args.cache,+ offline=args.offline, wheelhouse=args.wheelhouse)+ elif requirements:+ executable = pm.build_requirements_environment(+ requirements, out=args.out, python=args.python, cache=args.cache,+ wheelhouse=args.wheelhouse, offline=args.offline, sealed=args.sealed, explicit=True,+ )+ else:+ executable = pm.build_environment(+ source=args.source, out=args.out, python=args.python, cache=args.cache,+ extras=args.extras, groups=args.groups, all_extras=args.all_extras,+ no_install_project=args.no_install_project, frozen=not args.resolve,+ sealed=args.sealed, offline=args.offline, explicit=True,+ )+ except (pm.InstallError, OSError, ValueError) as exc:+ print(f"python environment: {exc}", file=sys.stderr)+ return 1+ print(executable)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/pm/cli.py b/pm/cli.pyindex 66790aa4804..8eac1026c59 100644--- a/pm/cli.py+++ b/pm/cli.py@@ -12,7 +12,7 @@ import threadingfrom pathlib import Pathfrom pm.ensure import _facts, _lockfile, _store, ensure, stage_only-from pm.ensure import uv as pm_uv+from pm.operations import lock_projectfrom pm.package import InstallErrorfrom pm.paths import repo_rootfrom pm.registry import get_package@@ -357,13 +357,10 @@ def cmd_update(args) -> int:print("pm update: nothing to update")if args.uv:- uv_bin, env = pm_uv(realize=False)- if uv_bin is None:- print("✗ uv: not installed")- return 1- code, tail = _run_live([uv_bin, "lock", "--upgrade"], cwd=str(repo_root()), env=env)- if code != 0:- print(f"✗ uv lock --upgrade failed:\n{tail}")+ try:+ lock_project(repo_root(), upgrade=True, explicit=True)+ except InstallError as exc:+ print(f"✗ Python lock refresh failed: {exc}")return 1print("✓ uv.lock refreshed")try:diff --git a/pm/client.py b/pm/client.pyindex 07ff403ac26..1900a88a342 100644--- a/pm/client.py+++ b/pm/client.py@@ -1,7 +1,7 @@"""Synchronous PM mutations in an isolated interpreter, never the app's imports."""from __future__ import annotations-from collections.abc import Mapping+from collections.abc import Mapping, Sequenceimport jsonimport osfrom pathlib import Path@@ -33,7 +33,7 @@ def _missing_or_refuse(name):return missing-def _request(operation, arguments, *, callbacks=None, pause_event=None):+def _request(operation, arguments, *, callbacks=None, pause_event=None, project_root=None):from pm import receiptfrom pm.ensure import lazy_installs_allowedfrom pm.registry import get_package, package_definitions@@ -42,17 +42,25 @@ def _request(operation, arguments, *, callbacks=None, pause_event=None):update_id = receipt._ambient_update_id()callbacks = callbacks or {}names = ([arguments["name"]] if operation in ("ensure", "stage_only") else- {"uv": ["uv"], "sync_venv": ["venv"]}.get(operation, []))+ {"sync_venv": ["venv"], "venv_is_current": ["venv"],+ "build_environment": ["uv"], "lock_project": ["uv"],+ "ensure_environment": ["uv"], "ensure_python_tool": ["uv"],+ "stage_manager_runtime": ["uv"], "check_project_lock": ["uv"],+ "export_requirements": ["uv"], "build_requirements_environment": ["uv"],+ "prune_cache": ["uv"]}.get(operation, []))message = {"id": request_id, "operation": operation, "arguments": arguments,"update_id": update_id,"callbacks": list(callbacks),"packages": package_definitions(names),- "context": {"repo": str(paths.repo_root()), "lockfile": str(paths.lockfile_path())},+ "context": {"repo": str(Path(project_root).absolute() if project_root is not None else paths.repo_root()),+ "lockfile": str(paths.lockfile_path())},}worker = Path(__file__).with_name("worker.py").resolve()environment = runtime_environment()- state_sync = operation == "sync_venv" or (+ state_sync = operation in ("sync_venv", "build_environment", "lock_project",+ "ensure_environment", "ensure_python_tool", "check_project_lock",+ "export_requirements", "build_requirements_environment") or (operation == "ensure" and isinstance(get_package(arguments["name"]), StatePackage))if (state_sync and not arguments.get("explicit") and not arguments.get("repair")and not lazy_installs_allowed()):@@ -69,6 +77,8 @@ def _request(operation, arguments, *, callbacks=None, pause_event=None):receipt.finalize("failed", 1, token=token)raiseenvironment["HERMES_DISABLE_LAZY_INSTALLS"] = "1"+ elif operation == "venv_is_current":+ command = runtime_command(worker, bootstrap=False)else:command = runtime_command(worker)callback_error = None@@ -139,8 +149,9 @@ def _request(operation, arguments, *, callbacks=None, pause_event=None):if error["type"] == "DownloadPaused":from pm.downloader import DownloadPausedraise DownloadPaused(error["message"])- kind = {"ValueError": ValueError, "TypeError": TypeError,- "KeyError": KeyError, "OSError": OSError}.get(error["type"], RuntimeError)+ kind = {"ValueError": ValueError, "TypeError": TypeError, "KeyError": KeyError,+ "OSError": OSError, "FileExistsError": FileExistsError,+ "FileNotFoundError": FileNotFoundError, "PermissionError": PermissionError}.get(error["type"], RuntimeError)raise kind(error["message"])return response["result"]finally:@@ -176,8 +187,10 @@ def ensure(name, *, base_env=None, explicit=False, progress=None, pause_event=Noreturn Runner(name, env_for(name, base_env=base_env))-def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None, repair=False) -> None:- if is_runtime():+def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, before_publish=None, repair=False,+ project_root: Path | None = None) -> None:+ foreign = project_root is not None and Path(project_root).resolve() != paths.repo_root().resolve()+ if is_runtime() and not foreign:from pm.ensure import sync_venv as directreturn direct(extras, explicit=explicit, plugin_dirs=plugin_dirs,before_publish=before_publish, repair=repair)@@ -197,7 +210,7 @@ def sync_venv(extras=None, *, explicit=False, plugin_dirs=None, before_publish=Nreturn {"undo": publication is not None, "finish": hasattr(publication, "finish")}callbacks["before_publish"] = publish_request("sync_venv", {"extras": extras, "explicit": explicit, "repair": repair,- "plugin_dirs": members}, callbacks=callbacks)+ "plugin_dirs": members}, callbacks=callbacks, project_root=project_root)def stage_only(name, target, *, progress=None) -> Path:@@ -208,17 +221,124 @@ def stage_only(name, target, *, progress=None) -> Path:return Path(_request("stage_only", {"name": name, "target": target}, callbacks=callbacks))-def uv(command="uv", *, venv=None, realize=True, explicit=False, base_env=None):- if command not in ("uv", "uvx"):- raise ValueError(f"unknown uv executable: {command}")- if not realize or is_runtime():- from pm.ensure import uv as direct- return direct(command, venv=venv, realize=realize, explicit=explicit, base_env=base_env)- if not explicit:- _missing_or_refuse("uv")- binary, environment = _request("uv", {- "command": command, "venv": str(venv) if venv is not None else None,- "realize": realize, "explicit": explicit,- "base_env": dict(os.environ if base_env is None else base_env),+def _python_operation(operation: str, arguments: dict):+ from pm import operations+ implementation = getattr(operations, operation, None)+ if implementation is None:+ from pm import build_operations+ implementation = getattr(build_operations, operation)+ if is_runtime():+ return implementation(**arguments)+ payload = {key: str(value.absolute()) if isinstance(value, Path) else value+ for key, value in arguments.items()}+ return _request(operation, payload)+++def build_environment(+ *, source: Path, out: Path, python: Path | None = None,+ cache: Path | None = None, env: Mapping[str, str] | None = None,+ extras: Sequence[str] = (), groups: Sequence[str] = (),+ all_extras: bool = False, no_install_project: bool = False,+ frozen: bool = True, sealed: bool = False, offline: bool = False,+ explicit: bool = False, timeout: int = 1800,+) -> Path:+ """Build a validated Python environment without exposing install machinery."""+ return Path(_python_operation("build_environment", {+ "source": Path(source), "out": Path(out), "python": python, "cache": cache,+ "env": dict(env) if env is not None else None, "extras": list(extras), "groups": list(groups),+ "all_extras": all_extras, "no_install_project": no_install_project,+ "frozen": frozen, "sealed": sealed, "offline": offline,+ "explicit": explicit, "timeout": timeout,+ }))+++def lock_project(+ source: Path, *, upgrade: bool = False, python: Path | None = None,+ env: Mapping[str, str] | None = None, cache: Path | None = None,+ offline: bool = False, explicit: bool = False,+) -> None:+ """Resolve a project's lock without creating or selecting an environment."""+ _python_operation("lock_project", {+ "source": Path(source), "upgrade": upgrade, "python": python,+ "env": dict(env) if env is not None else None, "cache": cache,+ "offline": offline, "explicit": explicit,})- return binary, environment+++def stage_manager_runtime(+ *, python: Path, destination: Path, project: Path | None = None,+ offline: bool = False, wheelhouse: Path | None = None, cache: Path | None = None,+) -> Path:+ return Path(_python_operation("stage_manager_runtime", {+ "python": Path(python), "destination": Path(destination), "project": project,+ "offline": offline, "wheelhouse": wheelhouse, "cache": cache,+ }))+++def ensure_environment(+ name: str, requirements: Sequence[str], *, root: Path | None = None,+ explicit: bool = False, timeout: int = 1800,+) -> Path:+ """Select a complete isolated dependency generation, retaining the previous one."""+ if isinstance(requirements, str):+ raise TypeError("requirements must be a sequence, not a string")+ return Path(_python_operation("ensure_environment", {+ "name": name, "requirements": list(requirements), "root": root,+ "explicit": explicit, "timeout": timeout,+ }))+++def ensure_python_tool(+ name: str, requirements: Sequence[str], executable: str, *, root: Path | None = None,+ explicit: bool = False, timeout: int = 1800,+) -> Path:+ """Install an isolated tool and return its validated executable, not uv/uvx."""+ if isinstance(requirements, str):+ raise TypeError("requirements must be a sequence, not a string")+ return Path(_python_operation("ensure_python_tool", {+ "name": name, "requirements": list(requirements), "executable": executable,+ "root": root, "explicit": explicit, "timeout": timeout,+ }))+++def venv_is_current(*, project_root: Path | None = None) -> bool:+ from pm.ensure import venv_is_current as direct++ return direct(project_root=project_root)+++def check_project_lock(source: Path, *, python: Path | None = None, cache: Path | None = None,+ env: Mapping[str, str] | None = None, offline: bool = False,+ explicit: bool = False) -> None:+ _python_operation("check_project_lock", {+ "source": Path(source), "python": python, "cache": cache,+ "env": dict(env) if env is not None else None, "offline": offline, "explicit": explicit,+ })+++def export_requirements(source: Path, out: Path, *, extras: Sequence[str] = (),+ python: Path | None = None, cache: Path | None = None,+ env: Mapping[str, str] | None = None, explicit: bool = False) -> None:+ _python_operation("export_requirements", {+ "source": Path(source), "out": Path(out), "extras": list(extras),+ "python": python, "cache": cache, "env": dict(env) if env is not None else None,+ "explicit": explicit,+ })+++def build_requirements_environment(requirements: Sequence[str], *, out: Path,+ python: Path | None = None, cache: Path | None = None,+ env: Mapping[str, str] | None = None, wheelhouse: Path | None = None,+ offline: bool = False, sealed: bool = False,+ explicit: bool = False) -> Path:+ if isinstance(requirements, str):+ raise TypeError("requirements must be a sequence, not a string")+ return Path(_python_operation("build_requirements_environment", {+ "requirements": list(requirements), "out": Path(out), "python": python, "cache": cache,+ "env": dict(env) if env is not None else None, "wheelhouse": wheelhouse,+ "offline": offline, "sealed": sealed, "explicit": explicit,+ }))+++def prune_cache(cache: Path, *, ci: bool = False) -> None:+ _python_operation("prune_cache", {"cache": Path(cache), "ci": ci})diff --git a/pm/ensure.py b/pm/ensure.pyindex 696211274e6..c17ddb71d66 100644--- a/pm/ensure.py+++ b/pm/ensure.py@@ -491,13 +491,13 @@ def env_for(*names: str, base_env: Optional[dict] = None) -> dict[str, str]:return compose_env(diffs, base=base_env)-def _runtime_state_matches(fact: dict, stamp: str) -> bool:+def _runtime_state_matches(fact: dict, stamp: str, *, project_root: Path | None = None) -> bool:if not isinstance(fact, dict) or fact.get("stamp") != stamp:return Falsefrom hermes_cli.runtime_paths import selected_venvtry:- environment = selected_venv(paths.repo_root())+ environment = selected_venv(paths.repo_root() if project_root is None else project_root)except (OSError, RuntimeError, ValueError):return Falserecorded = fact.get("environment")@@ -506,9 +506,14 @@ def _runtime_state_matches(fact: dict, stamp: str) -> bool:return (environment / "pyvenv.cfg").is_file()-def venv_is_current() -> bool:- """Use the recorded PM inputs and the boot-time environment selection."""- fact = Facts(paths.runtime_facts_path(), strict=True).get("venv")+def venv_is_current(*, project_root: Path | None = None) -> bool:+ """Use recorded inputs without starting PM or downloading prerequisites."""+ from hermes_cli.runtime_paths import runtime_facts_path+ from pm.packages import Venv++ root = paths.repo_root() if project_root is None else Path(project_root).absolute()+ package = get_package("venv") if project_root is None else Venv(root)+ fact = Facts(runtime_facts_path(root), strict=True).get("venv")if fact is None:fact = Facts(paths.facts_path(), strict=True).get("venv")if fact is None:@@ -517,7 +522,7 @@ def venv_is_current() -> bool:or not isinstance(fact.get("extras"), list)or any(not isinstance(extra, str) for extra in fact["extras"])):raise ValueError("invalid recorded dependency state")- return _runtime_state_matches(fact, get_package("venv").expected_stamp(fact["extras"]))+ return _runtime_state_matches(fact, package.expected_stamp(fact["extras"]), project_root=root)def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plugin_dirs=None, before_publish=None, repair: bool = False) -> None:@@ -553,6 +558,13 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False, plutry:if repair and (extras is not None or plugin_dirs is not None or before_publish is not None):raise ValueError("repair restores the recorded environment; it cannot change features or plugins")+ if extras:+ from pm.extras import extra_supported+ unsupported = [extra for extra in extras+ if not extra_supported(extra, importable=lambda _: False)]+ if unsupported:+ raise InstallError("venv", f"extras {unsupported} are not supported by this Python/platform",+ "choose a supported provider; no dependency environment was changed")frozen = read_features() if repair or not lazy_installs_allowed() else Noneif frozen is not None and extras:outside = sorted(set(extras) - set(frozen))diff --git a/pm/operations.py b/pm/operations.pynew file mode 100644index 00000000000..50f731a7753--- /dev/null+++ b/pm/operations.py@@ -0,0 +1,246 @@+"""Python dependency operations executed by the isolated package manager.++Callers describe a dependency graph and its lifetime, never a uv command.+Only the private environment engine knows how to obtain or invoke uv.+"""+from __future__ import annotations++from collections.abc import Mapping, Sequence+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import sys+import uuid++from pm.package import InstallError+++def build_environment(+ *, source: Path, out: Path, python: Path | None = None,+ cache: Path | None = None, env: Mapping[str, str] | None = None,+ extras: Sequence[str] = (), groups: Sequence[str] = (),+ all_extras: bool = False, no_install_project: bool = False,+ frozen: bool = True, sealed: bool = False, offline: bool = False,+ explicit: bool = False, timeout: int = 1800,+) -> Path:+ """Build and validate a fresh destination; never overwrite an existing tree.++ A build has no profile/plugin discovery or application selection side effects.+ Failure removes only the destination exclusively created by this invocation.+ Sealed builds prune only the .pth files that refer to build-time state.+ """+ from pm.environment import managed_environment, prune_site_pth++ source, out = Path(source).absolute(), Path(out).absolute()+ if not (source / "pyproject.toml").is_file():+ raise InstallError("venv", f"project manifest is missing: {source}")+ if frozen and not (source / "uv.lock").is_file():+ raise InstallError("venv", f"frozen build requires a lock: {source / 'uv.lock'}")+ if out.exists() or out.is_symlink():+ raise FileExistsError(f"environment destination already exists: {out}")+ environment = managed_environment(+ out, python=Path(python) if python is not None else None,+ cache=Path(cache) if cache is not None else None, env=env,+ offline=offline, explicit=explicit, output=sys.stderr,+ )+ out.mkdir(parents=True)+ try:+ environment.create()+ environment.sync(source, extras=extras, groups=groups, all_extras=all_extras,+ no_install_project=no_install_project, frozen=frozen, timeout=timeout)+ environment.check()+ if sealed:+ prune_site_pth(out)+ except BaseException:+ shutil.rmtree(out, ignore_errors=True)+ raise+ return environment.executable+++def lock_project(+ source: Path, *, upgrade: bool = False, python: Path | None = None,+ env: Mapping[str, str] | None = None, cache: Path | None = None,+ offline: bool = False, explicit: bool = False,+) -> None:+ """Refresh the project's resolution without creating or selecting a venv."""+ from pm.environment import managed_environment++ source = Path(source).absolute()+ if not (source / "pyproject.toml").is_file():+ raise InstallError("venv", f"project manifest is missing: {source}")+ environment = managed_environment(+ source / ".venv", python=Path(python) if python is not None else None,+ cache=Path(cache) if cache is not None else None, env=env,+ offline=offline, explicit=explicit, output=sys.stderr,+ )+ environment.lock(source, upgrade=upgrade)+++def stage_manager_runtime(+ *, python: Path, destination: Path, project: Path | None = None,+ offline: bool = False, wheelhouse: Path | None = None, cache: Path | None = None,+) -> Path:+ """Stage PM's independent dependency graph using its private toolchain."""+ from pm.environment import managed_environment+ from pm.runtime_stage import stage_runtime++ destination, python = Path(destination).absolute(), Path(python).absolute()+ if destination.exists() or destination.is_symlink():+ raise FileExistsError(f"environment destination already exists: {destination}")+ environment = managed_environment(destination, python=python,+ cache=Path(cache) if cache is not None else None, explicit=True,+ offline=offline, output=sys.stderr)+ return stage_runtime(environment.uv, python, destination,+ project=Path(project) if project is not None else None,+ offline=offline, wheelhouse=Path(wheelhouse) if wheelhouse is not None else None,+ cache=Path(cache) if cache is not None else None)+++def _environment_root(name: str, root: Path | None) -> Path:+ if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", name):+ raise ValueError("environment name must be a simple package name")+ if root is not None:+ return Path(root).absolute()+ from hermes_constants import get_hermes_home+ return get_hermes_home() / "environments" / name+++def _python(environment: Path) -> Path:+ return environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+++def _selection(root: Path) -> dict:+ try:+ record = json.loads((root / "active.json").read_text(encoding="utf-8"))+ except FileNotFoundError:+ return {}+ except (OSError, ValueError) as exc:+ raise InstallError("venv", f"cannot read environment selection: {root}") from exc+ if (not isinstance(record, dict) or not isinstance(record.get("generation"), str)+ or not re.fullmatch(r"gen-[0-9a-f]{32}", record["generation"])):+ raise InstallError("venv", f"invalid environment selection: {root}")+ return record+++def environment_python(name: str, *, root: Path | None = None) -> Path | None:+ """Read the selected interpreter without acquiring tools or writing state."""+ root = _environment_root(name, root)+ selected = _selection(root)+ if not selected:+ return None+ environment = root / selected["generation"] / "venv"+ if not environment.resolve().is_relative_to(root.resolve()):+ raise InstallError(name, "selected environment escapes its root")+ python = _python(environment)+ return python if python.is_file() and (environment / "pyvenv.cfg").is_file() else None+++def _tool(python: Path, executable: str) -> Path | None:+ if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", executable):+ raise ValueError("tool executable must be a filename, not a path")+ directory = python.parent+ suffixes = (".exe", ".cmd", "") if os.name == "nt" else ("",)+ return next((directory / (executable + suffix) for suffix in suffixes+ if (directory / (executable + suffix)).is_file()), None)+++def python_tool(name: str, executable: str, *, root: Path | None = None) -> Path | None:+ """Return a selected tool entrypoint, never an installer executable."""+ python = environment_python(name, root=root)+ return _tool(python, executable) if python is not None else None+++def _requirements(requirements: Sequence[str]) -> list[str]:+ from packaging.requirements import InvalidRequirement, Requirement++ if isinstance(requirements, str) or not requirements:+ raise ValueError("an isolated environment needs a nonempty sequence of requirements")+ try:+ return sorted({str(Requirement(requirement)) for requirement in requirements})+ except (InvalidRequirement, TypeError) as exc:+ raise ValueError(f"invalid environment requirement: {exc}") from exc+++def ensure_environment(+ name: str, requirements: Sequence[str], *, root: Path | None = None,+ explicit: bool = False, timeout: int = 1800,+ executable: str | None = None,+) -> Path:+ """Make an isolated dependency set current, then atomically select it.++ Build at the final path: Windows launchers and scripts embed that path.+ The prior generation survives both successful replacement and failed builds.+ An optional tool entrypoint is validated before publication, not afterwards.+ """+ from hermes_cli.runtime_state import _lock+ from pm.ensure import _refuse_lazy, lazy_installs_allowed+ from pm.lock import Lockfile, _write+ from pm import paths+ from pm.store import current_target++ root = _environment_root(name, root)+ requirements = _requirements(requirements)+ if executable is not None:+ _tool(Path("unused/python"), executable) # Validate before any write.+ lock = Lockfile(paths.lockfile_path())+ target = current_target()+ inputs = {"requirements": requirements, "python": lock.version("python"), "target": target,+ "artifacts": [item["sha256"] for item in lock.artifacts("python", target)]}+ identity = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()++ def current() -> Path | None:+ record = _selection(root)+ python = environment_python(name, root=root)+ if (record.get("inputs") == identity and python is not None+ and (executable is None or _tool(python, executable) is not None)):+ return python+ return None++ existing = current()+ if existing is not None:+ return existing+ if not explicit and not lazy_installs_allowed():+ raise _refuse_lazy(name, "isolated Python environment is missing or outdated")+ root.mkdir(parents=True, exist_ok=True)+ with (root / ".install.lock").open("a+b") as mutex:+ _lock(mutex.fileno(), wait=True)+ existing = current()+ if existing is not None:+ return existing+ generation = root / f"gen-{uuid.uuid4().hex}"+ generation.mkdir()+ try:+ (generation / "pyproject.toml").write_text(+ '[project]\nname = "hermes-side-environment"\nversion = "0"\n'+ 'requires-python = ">=3.11"\ndependencies = '+ + json.dumps(requirements) + '\n[tool.uv]\npackage = false\n', encoding="utf-8",+ )+ previous = _selection(root)+ if previous:+ seed = root / previous["generation"] / "uv.lock"+ if seed.is_file():+ shutil.copyfile(seed, generation / "uv.lock")+ python = build_environment(source=generation, out=generation / "venv", frozen=False,+ explicit=explicit, timeout=timeout)+ if executable is not None and _tool(python, executable) is None:+ raise InstallError(name, f"installed requirements do not provide {executable!r}")+ _write(root / "active.json", {"generation": generation.name, "inputs": identity,+ "requirements": requirements})+ except BaseException:+ shutil.rmtree(generation, ignore_errors=True)+ raise+ return python+++def ensure_python_tool(+ name: str, requirements: Sequence[str], executable: str, *,+ root: Path | None = None, explicit: bool = False, timeout: int = 1800,+) -> Path:+ python = ensure_environment(name, requirements, root=root, explicit=explicit,+ timeout=timeout, executable=executable)+ tool = _tool(python, executable)+ assert tool is not None # Validated under the publication lock above.+ return tooldiff --git a/pm/packages.py b/pm/packages.pyindex fdf430b1dbc..8b8f550fd84 100644--- a/pm/packages.py+++ b/pm/packages.py@@ -363,10 +363,13 @@ class Venv(StatePackage):name = "venv"deps = ("uv",)+ def __init__(self, project_root: Path | None = None):+ self._project_root = project_root+def project_root(self) -> Path:from pm.paths import repo_root- return repo_root()+ return repo_root() if self._project_root is None else self._project_rootdef venv_dir(self) -> Path:from hermes_cli.runtime_paths import selected_venvdiff --git a/pm/worker.py b/pm/worker.pyindex 0dceecfbf46..90b1f51dad3 100644--- a/pm/worker.py+++ b/pm/worker.py@@ -114,15 +114,25 @@ def main():with receipt.worker_context(request.get("update_id")):try:load_package_definitions(request.get("packages", []))+ from pm import operations as pythonoperations = {"ensure": engine.ensure, "sync_venv": sync_venv,- "stage_only": engine.stage_only, "uv": engine.uv}+ "stage_only": engine.stage_only, "venv_is_current": engine.venv_is_current,+ "build_environment": python.build_environment, "lock_project": python.lock_project,+ "stage_manager_runtime": python.stage_manager_runtime,+ "ensure_environment": python.ensure_environment,+ "ensure_python_tool": python.ensure_python_tool}arguments = request["arguments"]if request["operation"] == "ensure":arguments["pause_event"] = pausefor name in ("progress", "download_progress"):if name in request["callbacks"]:arguments[name] = lambda *args, name=name: callback(name, *args)- result = operations[request["operation"]](**arguments)+ if request["operation"] in ("check_project_lock", "export_requirements",+ "build_requirements_environment", "prune_cache"):+ from pm import build_operations+ result = getattr(build_operations, request["operation"])(**arguments)+ else:+ result = operations[request["operation"]](**arguments)if request["operation"] == "ensure":result = None # Runner is reconstructed from the caller's base env.if isinstance(result, Path):diff --git a/tests/pm/test_update_failure_status.py b/tests/pm/test_update_failure_status.pyindex 52fe1d954e1..ecf3ee5e7a1 100644--- a/tests/pm/test_update_failure_status.py+++ b/tests/pm/test_update_failure_status.py@@ -40,7 +40,7 @@ def prepare(tmp_path, monkeypatch, packages):def forbidden(*args, **kwargs):pytest.fail("lookup-only result reached a mutation or dependency refresh")- for name in ("_pin_artifacts", "_install_names", "_run_live", "pm_uv"):+ for name in ("_pin_artifacts", "_install_names", "_run_live", "lock_project"):monkeypatch.setattr(cli, name, forbidden)monkeypatch.setattr(importlib.import_module("pm.ensure"), "sync_venv", forbidden)return lockdiff --git a/tests/pm/test_worker.py b/tests/pm/test_worker.pyindex 5e181ac32c7..b6a79895fb6 100644--- a/tests/pm/test_worker.py+++ b/tests/pm/test_worker.py@@ -54,35 +54,44 @@ def test_isolated_worker_preserves_install_error(client, monkeypatch):assert not paths.facts_path().exists()-def test_realized_uv_returns_worker_selected_binaries_and_caller_env(client, tmp_path):- from pm.lock import Facts, Lockfile- from pm.registry import get_package- from pm.store import current_target+def test_worker_build_owns_creation_and_preserves_parent_environment(client, tmp_path, monkeypatch, isolated_python):+ import json+ from pm import operations- target = current_target()- lock = Lockfile(paths.lockfile_path())- facts = Facts(paths.facts_path())- binaries = {}- for name in ("python", "uv"):- package = get_package(name)- entry = paths.store_root() / package.store_entry("1", target)- binary = package.binary(entry, target)- assert binary is not None- binary.parent.mkdir(parents=True, exist_ok=True)- binary.write_bytes(b"installed binary fixture")- if name == "uv":- binary = binary.with_name("uvx" + binary.suffix)- binary.write_bytes(b"installed uvx fixture")- binaries[name] = str(binary)- digest = "a" * 64- lock.set_pin(name, "1", {target: {"url": "https://unused.invalid/archive", "sha256": digest}})- facts.record(name, "1", entry.name, {}, paths.store_root(), target=target, artifacts=[digest])- lock.save()- binary, env = client.uv("uvx", venv=tmp_path / "project-env", base_env={"KEEP": "caller", "PYTHONPATH": "bad"})- assert binary == binaries["uv"]- assert env["UV_PYTHON"] == binaries["python"] and env["KEEP"] == "caller"- assert env["VIRTUAL_ENV"] == str(tmp_path / "project-env")- assert "PYTHONPATH" not in env+ uv = shutil.which("uv")+ assert uv+ worker = Path(client.__file__).with_name("worker.py")+ script = (+ "import runpy, sys; "+ f"sys.path.insert(0, {str(worker.parent.parent)!r}); "+ "import pm._uv; "+ f"pm._uv._toolchain = lambda **kwargs: (__import__('pathlib').Path({uv!r}), "+ f"__import__('pathlib').Path({sys.executable!r})); "+ f"runpy.run_path({str(worker)!r}, run_name='__main__')"+ )+ monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])+ monkeypatch.setattr(operations, "build_environment", lambda **kwargs: pytest.fail("build ran in caller"))+ source = tmp_path / "project with spaces"+ source.mkdir()+ (source / "pyproject.toml").write_text(+ '[project]\nname="worker-proof"\nversion="1"\nrequires-python=">=3.11"\n'+ '[tool.uv]\npackage=false\n', encoding="utf-8",+ )+ monkeypatch.setenv("UV_PYTHON", "/not-the-interpreter")+ monkeypatch.setenv("UV_PROJECT_ENVIRONMENT", str(tmp_path / "wrong-environment"))+ monkeypatch.setenv("VIRTUAL_ENV", str(tmp_path / "wrong-environment"))+ before = dict(os.environ)+ python = client.build_environment(source=source, out=tmp_path / "dependency tree",+ frozen=False, offline=True, explicit=True)+ result = subprocess.run([str(python), "-I", "-c", "import json,sys; print(json.dumps(sys.prefix))"],+ capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert Path(json.loads(result.stdout)) == python.parent.parent+ assert not (tmp_path / "wrong-environment").exists()+ assert dict(os.environ) == before+ with pytest.raises(OSError, match="already exists"):+ client.build_environment(source=source, out=python.parent.parent, explicit=True)+ assert python.is_file()def test_refused_or_already_paused_install_does_not_acquire_runtime(client, monkeypatch):@@ -93,8 +102,6 @@ def test_refused_or_already_paused_install_does_not_acquire_runtime(client, monkmonkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")with pytest.raises(InstallError, match="lazy installs are disabled"):client.ensure("node")- with pytest.raises(InstallError, match="lazy installs are disabled"):- client.uv()paused = threading.Event()paused.set()with pytest.raises(DownloadPaused):@@ -171,16 +178,16 @@ def test_lazy_disabled_sync_does_not_bootstrap_tools(client, tmp_path, monkeypat# Exercise runtime acquisition too: the other worker tests supply a ready# interpreter, which hides an explicit tool install before worker refusal.monkeypatch.setattr("pm.runtime.runtime_python", runtime_python)- engine = importlib.import_module("pm.ensure")- original_uv = engine.uv+ from pm import _uv+ original_toolchain = _uv._toolchain- def uv(*args, **kwargs):+ def toolchain(**kwargs):assert kwargs.get("realize") is False, "lazy-disabled sync bootstrapped tools"if tools_present:- return str(tmp_path / "uv"), {"UV_PYTHON": str(isolated_python)}- return original_uv(*args, **kwargs)+ return tmp_path / "uv", isolated_python+ return original_toolchain(**kwargs)- monkeypatch.setattr(engine, "uv", uv)+ monkeypatch.setattr(_uv, "_toolchain", toolchain)monkeypatch.setattr("pm.runtime_stage.stage_runtime",lambda *a, **kw: pytest.fail("lazy-disabled sync prepared PM runtime"))selections = []@@ -334,11 +341,13 @@ def test_installed_tool_needs_no_pm_runtime(client, dl_server, monkeypatch):assert client.ensure("node", base_env={"PATH": "caller"}).env["PATH"].endswith("caller")-def test_uv_probe_needs_no_pm_runtime(client, monkeypatch):+def test_environment_probe_needs_no_pm_runtime(client, monkeypatch, tmp_path):+ from pm import environment_python, python_toolmonkeypatch.setattr("pm.runtime.runtime_python", lambda: pytest.fail("probe bootstrapped PM"))- binary, env = client.uv(realize=False, venv=Path("project-venv"), base_env={"KEPT": "yes"})- assert binary is None- assert env["KEPT"] == "yes" and env["VIRTUAL_ENV"] == "project-venv"+ root = tmp_path / "not-created"+ assert environment_python("test", root=root) is None+ assert python_tool("test", "test", root=root) is None+ assert not root.exists()def test_worker_receipt_is_exact_even_if_latest_is_replaced(client, tmp_path, monkeypatch):@@ -434,8 +443,8 @@ def test_failed_finish_runs_undo_before_propagating_callback_exception(client, tdef test_invalid_arguments_keep_the_engine_exception_type(client):with pytest.raises(ValueError, match="repair restores"):client.sync_venv([], repair=True)- with pytest.raises(ValueError, match="unknown uv executable"):- client.uv("not-uv")+ with pytest.raises(ValueError, match="environment name"):+ client.ensure_environment("../escape", ["example==1"], explicit=True)with pytest.raises(KeyError):client.ensure("no-such-package", explicit=True)@@ -446,6 +455,51 @@ def test_worker_death_reports_transport_failure(client, monkeypatch, isolated_pyclient.ensure("node", explicit=True)+def test_worker_side_environment_reuses_and_keeps_selection_on_failed_tool(client, tmp_path, monkeypatch, isolated_python):+ import zipfile+ from pm import environment_python, python_tool+ from tests.pm.test_environment_build import _wheel++ uv = shutil.which("uv")+ assert uv+ worker = Path(client.__file__).with_name("worker.py")+ script = (+ "import runpy, sys; "+ f"sys.path.insert(0, {str(worker.parent.parent)!r}); "+ "import pm._uv; "+ f"pm._uv._toolchain = lambda **kwargs: (__import__('pathlib').Path({uv!r}), "+ f"__import__('pathlib').Path({sys.executable!r})); "+ f"runpy.run_path({str(worker)!r}, run_name='__main__')"+ )+ monkeypatch.setattr(client, "runtime_command", lambda path, **kwargs: [str(isolated_python), "-I", "-B", "-c", script])+ wheel = _wheel(tmp_path, "side_dep")+ with zipfile.ZipFile(wheel, "a") as archive:+ archive.writestr("side_dep/cli.py", "def main():\n print('real side dependency')\n")+ archive.writestr("side_dep-1.0.dist-info/entry_points.txt", "[console_scripts]\nside-proof = side_dep.cli:main\n")+ requirements = [f"side-dep @ {wheel.as_uri()}"]+ root = tmp_path / "side environment"+ assert environment_python("proof", root=root) is None+ executable = client.ensure_python_tool("proof", requirements, "side-proof", root=root, explicit=True)+ assert python_tool("proof", "side-proof", root=root) == executable+ result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "real side dependency"+ selected = environment_python("proof", root=root)+ selection = (root / "active.json").read_bytes()+ generations = set(root.glob("gen-*"))+ assert client.ensure_environment("proof", requirements, root=root) == selected+ assert set(root.glob("gen-*")) == generations+ with pytest.raises(InstallError, match="do not provide"):+ client.ensure_python_tool("proof", requirements, "missing-command", root=root, explicit=True)+ assert (root / "active.json").read_bytes() == selection+ assert set(root.glob("gen-*")) == generations+ assert python_tool("proof", "side-proof", root=root) == executable+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1")+ with pytest.raises(InstallError, match="lazy installs are disabled"):+ client.ensure_environment("proof", ["absent-dependency==0"], root=root)+ assert (root / "active.json").read_bytes() == selection++def test_unknown_worker_operation_is_not_dispatched(client):with pytest.raises((KeyError, RuntimeError), match="activate"):client._request("activate", {})