Skip to content

The agent that grows with you

fix(launchers): a Python repin republishes hermes.exe, not a .cmd

Tekniumbf0203a794a0
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.py
index 51c4143ba14..f39f121049f 100644
--- a/hermes_cli/_launchers.py
+++ b/hermes_cli/_launchers.py
@@ -167,6 +167,39 @@ def _load_script_maker():
return None
+def _store_script_maker(python_exe: Path):
+ """ScriptMaker from the pip that ships with the interpreter being bound.
+
+ A launch activates only the dependency environment, which carries no
+ distlib and drops the store's site-packages, so the update that repins
+ Python could only publish a .cmd and retire hermes.exe -- which Desktop's
+ backend sweep, shortcuts and terminal profiles name. python-build-standalone
+ ships pip (the installer mints the first hermes.exe through it), and its
+ vendored distlib is self-contained. It loads under a private name so the
+ store's pip never answers an ``import pip`` in this process."""
+ package = Path(python_exe).parent / "Lib" / "site-packages" / "pip" / "_vendor" / "distlib"
+ if not (package / "scripts.py").is_file():
+ return None
+ import hashlib
+ import importlib
+ import importlib.util
+
+ # One private package per store copy: a later repin's pip never reuses the first one's.
+ name = f"_hermes_store_distlib_{hashlib.sha256(str(package).encode()).hexdigest()[:12]}"
+ try:
+ if name not in sys.modules:
+ spec = importlib.util.spec_from_file_location(
+ name, package / "__init__.py", submodule_search_locations=[str(package)])
+ if spec is None or spec.loader is None:
+ return None
+ sys.modules[name] = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(sys.modules[name])
+ return importlib.import_module(f"{name}.scripts").ScriptMaker
+ except (ImportError, OSError, SyntaxError, AttributeError): # a torn or foreign pip: mint a .cmd
+ sys.modules.pop(name, None)
+ return None
+
+
def exe_is_venv_bound(exe: Path, venv_dir: Path | None) -> bool:
"""True when an existing launcher exe embeds the venv interpreter —
i.e. it is a copied venv console-script trampoline from the pre-pm
@@ -227,7 +260,7 @@ def mint_launcher(
if not _is_windows():
return _mint_shell_launcher(name, out_dir, python_exe, script)
- script_maker_cls = _load_script_maker()
+ script_maker_cls = _load_script_maker() or _store_script_maker(python_exe)
if script_maker_cls is not None:
class _PathedScriptMaker(script_maker_cls): # type: ignore[misc,valid-type]
def _get_script_text(self, entry):
@@ -572,8 +605,9 @@ def stage_launcher(name: str, repo_root: Path, out_dir: Path) -> Path | None:
def _collect_retired(exe: Path) -> None:
- """Delete aside copies of ``exe`` whose process has since exited."""
- for leftover in exe.parent.glob(f"{exe.name}.*.deleteme"):
+ """Delete aside copies of ``exe`` whose process has since exited: ours
+ (``.<pid>.deleteme``) and distlib's own (``.deleteme``)."""
+ for leftover in exe.parent.glob(f"{exe.name}*.deleteme"):
with suppress(OSError):
leftover.unlink()
diff --git a/tests/hermes_cli/test_source_launcher_publication.py b/tests/hermes_cli/test_source_launcher_publication.py
index 33092e8be56..d62098d2818 100644
--- a/tests/hermes_cli/test_source_launcher_publication.py
+++ b/tests/hermes_cli/test_source_launcher_publication.py
@@ -60,6 +60,12 @@ def fixture_tree(tmp_path, monkeypatch):
return repo, home, interpreter
+def without_distlib(monkeypatch):
+ """No ScriptMaker anywhere: not in this process, not beside the store's Python."""
+ monkeypatch.setattr(_launchers, "_load_script_maker", lambda: None)
+ monkeypatch.setattr(_launchers, "_store_script_maker", lambda _python: None)
+
+
def select_generation(repo, name, value):
selected = install_state_dir(repo) / 'environments' / str(name) / 'venv'
site = site_packages(selected)
@@ -151,7 +157,7 @@ def test_profile_publication_preserves_shared_launcher_default_home(tmp_path, mo
select_generation(repo, "shared", "ready")
out = tmp_path / ".local" / "bin"
if publisher == "cmd":
- monkeypatch.setattr(_launchers, "_load_script_maker", lambda: None)
+ without_distlib(monkeypatch)
launchers = [Path(p) for p in _launchers.ensure_install_launchers(repo, out)]
assert len(launchers) == len(_launchers.ENTRY_POINTS)
if publisher == "cmd":
@@ -368,7 +374,7 @@ def test_running_source_launcher_can_republish_itself(tmp_path, monkeypatch, lau
)
out = repo / ".hermes/bin"
if launcher_form == "cmd":
- monkeypatch.setattr(_launchers, "_load_script_maker", lambda: None)
+ without_distlib(monkeypatch)
launchers = _launchers.ensure_install_launchers(repo, out)
assert len(launchers) == len(_launchers.ENTRY_POINTS)
command = next(Path(p) for p in launchers if Path(p).stem == "hermes")
@@ -383,8 +389,9 @@ def test_running_source_launcher_can_republish_itself(tmp_path, monkeypatch, lau
@pytest.mark.platforms("windows")
[email protected]("running", [False, True], ids=["idle", "running"])
-def test_repin_without_distlib_retires_stale_native_launcher(tmp_path, monkeypatch, running):
[email protected]("running, store_pip", [(False, False), (True, False), (True, True)],
+ ids=["idle", "running", "running-store-pip"])
+def test_repin_without_distlib_retires_stale_native_launcher(tmp_path, monkeypatch, running, store_pip):
repo, home, _interpreter = fixture_tree(tmp_path, monkeypatch)
(repo / "hermes_cli/main.py").write_text(
"import sys\ndef main():\n print('ready', flush=True)\n sys.stdin.read()\n return 0\n",
@@ -395,6 +402,12 @@ def test_repin_without_distlib_retires_stale_native_launcher(tmp_path, monkeypat
new_python = home / "tools" / "repinned" / "python.exe"
new_python.parent.mkdir()
new_python.touch()
+ if store_pip:
+ # python-build-standalone ships pip; the activated update process cannot import it.
+ import distlib
+
+ shutil.copytree(Path(distlib.__file__).parent,
+ new_python.parent / "Lib" / "site-packages" / "pip" / "_vendor" / "distlib")
(home / "tools/facts.json").write_text(
json.dumps({"packages": {"python": {"entry": "repinned"}}}), encoding="utf-8")
real_maker = _launchers._load_script_maker
@@ -416,15 +429,21 @@ def test_repin_without_distlib_retires_stale_native_launcher(tmp_path, monkeypat
except subprocess.TimeoutExpired:
process.kill()
process.communicate()
- assert result == local / "hermes.cmd"
- assert not original.exists() # cmd.exe must not run the old exe first
- assert result is not None and str(new_python) in result.read_text(encoding="utf-8-sig")
+ if store_pip:
+ # Desktop's backend sweep, shortcuts and the install E2E all name hermes.exe.
+ assert result == local / "hermes.exe"
+ assert _launchers._launcher_python(result) == new_python
+ assert not (local / "hermes.cmd").exists()
+ else:
+ assert result == local / "hermes.cmd"
+ assert not original.exists() # cmd.exe must not run the old exe first
+ assert result is not None and str(new_python) in result.read_text(encoding="utf-8-sig")
if process is not None:
assert process.returncode == 0 # the retired launcher finished its own run
# distlib is back for the next publication: the aside copy still goes.
monkeypatch.setattr(_launchers, "_load_script_maker", real_maker)
assert _launchers.stage_launcher("hermes", repo, local) == local / "hermes.exe"
- assert not list(local.glob("hermes.exe.*.deleteme"))
+ assert not list(local.glob("hermes.exe*.deleteme"))
@pytest.mark.platforms("windows")