The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(installer): require Hermes-managed Python on Windows
fangliquanflq60c7c0c667a0
diff --git a/scripts/install.ps1 b/scripts/install.ps1index 8ac4df07902..28f6fa162fa 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -1164,37 +1164,85 @@ function Resolve-UvCmd {throw "uv is not installed. Run install.ps1 -Stage uv first."}+function Initialize-ManagedPythonEnvironment {+ # Python used by Hermes belongs to the checkout, never to another+ # application or a user-level uv configuration. Keep this aligned with+ # hermes_cli.managed_uv.managed_python_env(), which owns the update path.+ foreach ($name in @(+ "CONDA_DEFAULT_ENV", "CONDA_PREFIX", "UV_PROJECT_ENVIRONMENT",+ "UV_NO_MANAGED_PYTHON", "UV_PYTHON", "UV_PYTHON_DOWNLOADS",+ "UV_SYSTEM_PYTHON", "VIRTUAL_ENV", "PYTHONHOME", "PYTHONPATH"+ )) {+ Remove-Item -Path "Env:$name" -ErrorAction SilentlyContinue+ }++ $managedRoot = Join-Path $InstallDir ".hermes-runtime\python"+ New-Item -ItemType Directory -Force -Path $managedRoot | Out-Null+ $env:UV_MANAGED_PYTHON = "1"+ $env:UV_NO_CONFIG = "1"+ $env:UV_PYTHON_INSTALL_BIN = "0"+ $env:UV_PYTHON_INSTALL_DIR = $managedRoot+ $env:UV_PYTHON_INSTALL_REGISTRY = "0"+ return [System.IO.Path]::GetFullPath($managedRoot)+}+function Resolve-AvailablePythonVersion {- # Return the first Python minor version uv can actually find, preferring the- # requested $PythonVersion and then $PythonFallbackVersions. Returns $null- # when none are available.+ # Return the absolute path of the first Hermes-managed interpreter uv can+ # find, preferring the requested version and then fallback minors. System+ # and application-owned interpreters are deliberately ineligible.#- # This is the cross-process-safe counterpart to Test-Python's in-memory- # ``$script:PythonVersion = $fallbackVer`` mutation. Under Hermes-Setup.exe- # each ``-Stage NAME`` runs in a *fresh* powershell.exe, so the fallback the- # ``python`` stage settled on (e.g. 3.12 when 3.11 is absent) does NOT- # survive into the ``venv`` stage's process -- there $PythonVersion is back- # at its "3.11" default. Consumers re-resolve here instead of trusting that- # default, which is exactly the propagation gap behind issue #50769.+ # Under Hermes-Setup.exe each stage runs in a fresh powershell.exe. The+ # venv stage therefore re-resolves both version and provenance rather than+ # relying on state selected by the earlier Python stage (#50769).+ [string]$managedRoot = Initialize-ManagedPythonEnvironment+ $managedPrefix = $managedRoot.TrimEnd('\') + '\'$candidates = @($PythonVersion) + $PythonFallbackVersions$seen = @{}foreach ($ver in $candidates) {if (-not $ver -or $seen.ContainsKey($ver)) { continue }$seen[$ver] = $true+ $process = $nulltry {- $found = & $UvCmd python find $ver 2>$null- if ($found) { return $ver }- } catch { }+ # PowerShell 5.1 can lose a nested native command's stdout when+ # this installer itself is redirected by the desktop bootstrapper.+ # Capture uv directly through ProcessStartInfo instead of relying+ # on the native-command pipeline for the interpreter path.+ $process = New-Object System.Diagnostics.Process+ $startInfo = New-Object System.Diagnostics.ProcessStartInfo+ $startInfo.FileName = $UvCmd+ $startInfo.Arguments = "python find $ver --managed-python --no-config"+ $startInfo.UseShellExecute = $false+ $startInfo.CreateNoWindow = $true+ $startInfo.RedirectStandardOutput = $true+ $startInfo.RedirectStandardError = $true+ $process.StartInfo = $startInfo+ if (-not $process.Start()) { continue }+ $stdout = $process.StandardOutput.ReadToEnd()+ $process.StandardError.ReadToEnd() | Out-Null+ $process.WaitForExit()+ if ($process.ExitCode -ne 0) { continue }+ [string]$foundPath = ($stdout.Trim() -split "`r?`n") | Select-Object -Last 1+ if ($foundPath) {+ $absolute = [System.IO.Path]::GetFullPath($foundPath)+ if ($absolute.StartsWith($managedPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {+ return $absolute+ }+ }+ } catch {+ } finally {+ if ($process) { $process.Dispose() }+ }}return $null}function Test-Python {+ Initialize-ManagedPythonEnvironment | Out-NullWrite-Info "Checking Python $PythonVersion..."-- # Let uv find or install Python++ # Only a checkout-private uv-managed interpreter satisfies this stage.try {- $pythonPath = & $UvCmd python find $PythonVersion 2>$null+ $pythonPath = Resolve-AvailablePythonVersionif ($pythonPath) {$ver = & $pythonPath --version 2>$nullWrite-Success "Python found: $ver"@@ -1219,13 +1267,13 @@ function Test-Python {# semantics or stderr noise. This fix was previously landed as# commit ec1714e71 and then lost in a release squash; reapplied here.$ErrorActionPreference = "Continue"- $uvOutput = & $UvCmd python install $PythonVersion 2>&1+ $uvOutput = & $UvCmd python install $PythonVersion --no-bin --no-registry --no-config 2>&1$uvExitCode = $LASTEXITCODE$ErrorActionPreference = $prevEAP# Check if Python is now available (more reliable than exit code# since uv may return non-zero due to "already installed" etc.)- $pythonPath = & $UvCmd python find $PythonVersion 2>$null+ $pythonPath = Resolve-AvailablePythonVersionif ($pythonPath) {$ver = & $pythonPath --version 2>$nullWrite-Success "Python installed: $ver"@@ -1243,60 +1291,30 @@ function Test-Python {Write-Warn "uv python install error: $_"}- # Fallback: check if ANY Python 3.10+ is already available on the system- Write-Info "Trying to find any existing Python 3.10+..."+ # Preserve the established minor-version fallback contract, but provision+ # every fallback into the same private store instead of borrowing a system+ # interpreter. This path is reached only when the preferred install failed.foreach ($fallbackVer in $PythonFallbackVersions) {try {- $pythonPath = & $UvCmd python find $fallbackVer 2>$null+ Write-Info "Trying managed Python fallback $fallbackVer..."+ $previousFallbackEAP = $ErrorActionPreference+ $ErrorActionPreference = "Continue"+ & $UvCmd python install $fallbackVer --no-bin --no-registry --no-config 2>&1 | Out-Null+ $ErrorActionPreference = $previousFallbackEAP+ $pythonPath = Resolve-AvailablePythonVersionif ($pythonPath) {- $ver = & $pythonPath --version 2>$null- Write-Success "Found fallback: $ver"$script:PythonVersion = $fallbackVer+ $ver = & $pythonPath --version 2>$null+ Write-Success "Python fallback installed: $ver"return $true}- } catch { }- }-- # Fallback: try system python -- but skip the Microsoft Store stub.- # On Windows, %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe is a 0-byte- # reparse-point stub that prints "Python was not found; run without- # arguments to install from the Microsoft Store..." to stdout and exits- # non-zero. Get-Command finds it; invoking it produces a confusing error- # that the user sees as our installer crashing.- $pythonCmd = Get-Command python -ErrorAction SilentlyContinue- if ($pythonCmd) {- $isStoreStub = $false- try {- $pythonSource = $pythonCmd.Source- if ($pythonSource -and $pythonSource -like "*\WindowsApps\*") {- $isStoreStub = $true- } else {- # Even outside WindowsApps, a 0-byte file is the stub- $item = Get-Item $pythonSource -ErrorAction SilentlyContinue- if ($item -and $item.Length -eq 0) { $isStoreStub = $true }- }- } catch { }-- if (-not $isStoreStub) {- try {- $prevEAP2 = $ErrorActionPreference- $ErrorActionPreference = "Continue"- $sysVer = & python --version 2>&1- $ErrorActionPreference = $prevEAP2- if ($sysVer -match "Python 3\.(1[0-9]|[1-9][0-9])") {- Write-Success "Using system Python: $sysVer"- return $true- }- } catch {- if ($prevEAP2) { $ErrorActionPreference = $prevEAP2 }- }+ } catch {+ if ($previousFallbackEAP) { $ErrorActionPreference = $previousFallbackEAP }}}Write-Err "Failed to install Python $PythonVersion"- Write-Info "Install Python 3.11 manually, then re-run this script:"- Write-Info " https://www.python.org/downloads/"- Write-Info " Or: winget install Python.Python.3.11"+ Write-Info "Check network access to uv's managed Python downloads, then retry."return $false}@@ -2534,10 +2552,9 @@ function Install-Venv {# fresh process -- $PythonVersion is back at its "3.11" default. Trusting it# here made `uv venv venv --python 3.11` fail with exit 2 on machines without# 3.11 even though the `python` stage reported success (issue #50769).- $resolved = Resolve-AvailablePythonVersion- if ($resolved -and $resolved -ne $PythonVersion) {- Write-Info "Python $PythonVersion not available; using detected Python $resolved"- $script:PythonVersion = $resolved+ $resolvedPython = Resolve-AvailablePythonVersion+ if (-not $resolvedPython) {+ throw "Hermes-managed Python is unavailable. Run install.ps1 -Stage python first."}Write-Info "Creating virtual environment with Python $PythonVersion..."@@ -2659,16 +2676,36 @@ function Install-Venv {}}- # uv creates the venv and pins the Python version in one step. uv emits- # normal progress such as "Using CPython ..." on stderr; under Windows- # PowerShell 5.1 with EAP=Stop that stderr is a NativeCommandError unless- # we temporarily relax EAP and trust $LASTEXITCODE for real failures.- Invoke-NativeWithRelaxedErrorAction { & $UvCmd venv venv --python $PythonVersion }- # Relaxing EAP above means a *genuine* uv-venv failure (exit != 0) no longer- # aborts on its own. Capture $LASTEXITCODE immediately and fail fast, so the- # `venv` stage can't falsely report success (and Invoke-Stage can't emit- # ok=true) when the venv was never created.- $venvExitCode = $LASTEXITCODE+ # Pass the already-validated private interpreter path and prohibit uv from+ # resolving or downloading a different Python during venv creation. Use+ # ProcessStartInfo because the desktop bootstrapper redirects this script;+ # Windows PowerShell 5.1 can otherwise lose nested native output/exit state.+ $venvProcess = New-Object System.Diagnostics.Process+ try {+ $venvStartInfo = New-Object System.Diagnostics.ProcessStartInfo+ $venvStartInfo.FileName = $UvCmd+ $venvStartInfo.Arguments = "venv venv --python `"$resolvedPython`" --managed-python --no-python-downloads --no-config"+ $venvStartInfo.WorkingDirectory = $InstallDir+ $venvStartInfo.UseShellExecute = $false+ $venvStartInfo.CreateNoWindow = $true+ $venvStartInfo.RedirectStandardOutput = $true+ $venvStartInfo.RedirectStandardError = $true+ $venvProcess.StartInfo = $venvStartInfo+ if (-not $venvProcess.Start()) {+ throw "Failed to start uv while creating the virtual environment"+ }+ $venvStdoutTask = $venvProcess.StandardOutput.ReadToEndAsync()+ $venvStderrTask = $venvProcess.StandardError.ReadToEndAsync()+ $venvProcess.WaitForExit()+ $venvStdout = $venvStdoutTask.Result+ $venvStderr = $venvStderrTask.Result+ $venvExitCode = $venvProcess.ExitCode+ if ($venvStdout) { Write-Host $venvStdout.TrimEnd() }+ if ($venvStderr) { Write-Host $venvStderr.TrimEnd() }+ } finally {+ $venvProcess.Dispose()+ }+ # Fail fast so the stage cannot report ok=true when uv failed.if ($venvExitCode -ne 0) {throw "Failed to create virtual environment (uv venv exited with $venvExitCode)"}diff --git a/tests/install_ps1_fake_uv.py b/tests/install_ps1_fake_uv.pynew file mode 100644index 00000000000..10df5ba345e--- /dev/null+++ b/tests/install_ps1_fake_uv.py@@ -0,0 +1,75 @@+"""Fake uv executable used by behavioral Windows installer tests."""++from __future__ import annotations++from pathlib import Path+import subprocess+++_FAKE_UV = r'''+using System;+using System.IO;+using System.Linq;++public static class FakeUv {+ public static int Main(string[] args) {+ File.AppendAllText(Environment.GetEnvironmentVariable("FAKE_UV_LOG"),+ string.Join(" ", args) + Environment.NewLine);++ if (args.Length >= 2 && args[0] == "python" && args[1] == "find") {+ bool managed = args.Contains("--managed-python");+ Console.WriteLine(Environment.GetEnvironmentVariable(+ managed ? "FAKE_MANAGED_PYTHON" : "FAKE_THIRD_PARTY_PYTHON"));+ return 0;+ }+ if (args.Length >= 2 && args[0] == "python" && args[1] == "install") {+ return 0;+ }+ if (args.Length >= 2 && args[0] == "venv" && args[1] == "venv") {+ string managedPython = Environment.GetEnvironmentVariable("FAKE_MANAGED_PYTHON");+ int pythonAt = Array.IndexOf(args, "--python");+ bool correctPython = pythonAt >= 0 && pythonAt + 1 < args.Length+ && string.Equals(args[pythonAt + 1], managedPython,+ StringComparison.OrdinalIgnoreCase);+ if (!correctPython || !args.Contains("--managed-python")+ || !args.Contains("--no-python-downloads")) {+ return 42;+ }+ string scripts = Path.Combine(Environment.CurrentDirectory, "venv", "Scripts");+ Directory.CreateDirectory(scripts);+ File.WriteAllText(Path.Combine(scripts, "python.exe"), "fake");+ return 0;+ }+ return 2;+ }+}+'''+++def compile_fake_uv(powershell: str, output: Path) -> None:+ source = output.with_suffix(".cs")+ source.write_text(_FAKE_UV, encoding="utf-8")+ compile_script = output.with_name("compile-fake-uv.ps1")+ compile_script.write_text(+ "param([string]$Source, [string]$Output)\n"+ "Add-Type -Path $Source -OutputAssembly $Output "+ "-OutputType ConsoleApplication\n",+ encoding="utf-8",+ )+ subprocess.run(+ [+ powershell,+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(compile_script),+ "-Source",+ str(source),+ "-Output",+ str(output),+ ],+ check=True,+ capture_output=True,+ text=True,+ )diff --git a/tests/test_install_ps1_managed_python_provenance.py b/tests/test_install_ps1_managed_python_provenance.pynew file mode 100644index 00000000000..e0ed994b33d--- /dev/null+++ b/tests/test_install_ps1_managed_python_provenance.py@@ -0,0 +1,94 @@+"""Behavioral regression for Hermes-managed Python provenance on Windows."""++from __future__ import annotations++import json+from pathlib import Path+import shutil+import subprocess++import pytest++from tests.install_ps1_fake_uv import compile_fake_uv+++pytestmark = pytest.mark.windows_only++_INSTALL_PS1 = Path(__file__).resolve().parents[1] / "scripts" / "install.ps1"+++def test_venv_stage_rejects_third_party_python_and_uses_managed_path(+ tmp_path: Path,+) -> None:+ powershell = shutil.which("powershell")+ if not powershell:+ pytest.skip("Windows PowerShell is required")++ hermes_home = tmp_path / "hermes-home"+ install_dir = tmp_path / "install"+ managed_root = install_dir / ".hermes-runtime" / "python"+ managed_python = managed_root / "cpython-3.11" / "python.exe"+ third_party = tmp_path / "KiCad" / "bin" / "python.exe"+ log = tmp_path / "uv.log"+ uv = hermes_home / "bin" / "uv.exe"+ uv.parent.mkdir(parents=True)+ install_dir.mkdir()+ managed_python.parent.mkdir(parents=True)+ managed_python.write_text("fake", encoding="ascii")+ third_party.parent.mkdir(parents=True)+ third_party.write_text("fake", encoding="ascii")+ compile_fake_uv(powershell, uv)++ env = {+ **dict(__import__("os").environ),+ "FAKE_UV_LOG": str(log),+ "FAKE_MANAGED_PYTHON": str(managed_python),+ "FAKE_THIRD_PARTY_PYTHON": str(third_party),+ "UV_PYTHON": str(third_party),+ "UV_NO_MANAGED_PYTHON": "1",+ "UV_SYSTEM_PYTHON": "1",+ }+ stdout_path = tmp_path / "installer.stdout"+ stderr_path = tmp_path / "installer.stderr"+ with stdout_path.open("w", encoding="utf-8") as stdout, stderr_path.open(+ "w", encoding="utf-8"+ ) as stderr:+ run = subprocess.run(+ [+ powershell,+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(_INSTALL_PS1),+ "-Stage",+ "venv",+ "-HermesHome",+ str(hermes_home),+ "-InstallDir",+ str(install_dir),+ ],+ cwd=tmp_path,+ env=env,+ stdout=stdout,+ stderr=stderr,+ text=True,+ check=False,+ )++ installer_stdout = stdout_path.read_text(encoding="utf-8")+ installer_stderr = stderr_path.read_text(encoding="utf-8")+ frames = [+ json.loads(line) for line in installer_stdout.splitlines() if line.startswith("{")+ ]+ assert run.returncode == 0, installer_stdout + installer_stderr+ assert frames[-1]["ok"] is True+ commands = log.read_text(encoding="utf-8").splitlines()+ assert any(+ command.startswith("python find 3.11") and "--managed-python" in command+ for command in commands+ )+ venv_command = next(command for command in commands if command.startswith("venv venv"))+ assert f"--python {managed_python}" in venv_command+ assert "--managed-python" in venv_command+ assert "--no-python-downloads" in venv_commanddiff --git a/tests/test_install_ps1_native_stderr_eap.py b/tests/test_install_ps1_native_stderr_eap.pyindex de99bf22900..b0c44faf222 100644--- a/tests/test_install_ps1_native_stderr_eap.py+++ b/tests/test_install_ps1_native_stderr_eap.py@@ -47,35 +47,23 @@ def test_repository_stage_relieves_eap_for_ssh_and_https_git_clone() -> None:)-def test_uv_venv_and_dependency_installs_relax_eap() -> None:+def test_dependency_installs_relax_eap() -> None:text = _install_ps1()- _assert_relaxed_call(text, r"& \$UvCmd venv venv --python \$PythonVersion")_assert_relaxed_call(text, r"& \$UvCmd sync --extra all --locked")_assert_relaxed_call(text, r"& \$UvCmd pip install -e \$tier\.Spec")-def test_uv_venv_failure_is_not_swallowed_after_eap_relax() -> None:- """Relaxing EAP must not let a genuine `uv venv` failure pass as success.-- Once EAP is relaxed, a real non-zero `uv venv` exit no longer aborts on its- own, so install.ps1 must capture $LASTEXITCODE right after the call and fail- fast — otherwise the `venv` stage falsely reports success (Invoke-Stage emits- ok=true) when no venv was created. Regression guard for the gap caught while- reviewing #48372 (the explicit check originally proposed in #48463).- """+def test_uv_venv_failure_is_not_swallowed() -> None:+ """The redirected uv process exit code must gate venv-stage success."""text = _install_ps1()- # The uv-venv invocation, then an exit-code capture, then a throw — all- # within a small window after the relaxed call.guard = re.search(- r"& \$UvCmd venv venv --python \$PythonVersion[\s\S]{0,400}?"- r"\$LASTEXITCODE[\s\S]{0,200}?"+ r"\$venvExitCode\s*=\s*\$venvProcess\.ExitCode[\s\S]{0,400}?"r"-ne 0[\s\S]{0,200}?throw",text,)assert guard is not None, (- "install.ps1 must capture uv venv's exit code and throw on failure after "- "relaxing ErrorActionPreference, so a genuine venv-creation failure isn't "- "reported as a successful stage"+ "install.ps1 must capture the redirected uv venv process exit code and "+ "throw so a genuine creation failure is not reported as success")diff --git a/tests/test_install_ps1_venv_process_tree.py b/tests/test_install_ps1_venv_process_tree.pyindex b51a9ccd4ab..23e817e2816 100644--- a/tests/test_install_ps1_venv_process_tree.py+++ b/tests/test_install_ps1_venv_process_tree.py@@ -17,6 +17,8 @@ from pathlib import Pathimport psutilimport pytest+from tests.install_ps1_fake_uv import compile_fake_uv+REPO_ROOT = Path(__file__).resolve().parent.parentINSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"@@ -86,7 +88,7 @@ def test_venv_sweep_stops_managed_runtime_children_but_not_unrelated_processes(hermes_home = tmp_path / "hermes-home"install_dir = hermes_home / "hermes-agent"venv_scripts = install_dir / "venv" / "Scripts"- runtime_dir = hermes_home / ".hermes-runtime" / "python" / "generation-test"+ runtime_dir = install_dir / ".hermes-runtime" / "python" / "generation-test"unrelated_dir = tmp_path / "unrelated"fake_bin = tmp_path / "fake-bin"for directory in (venv_scripts, runtime_dir, unrelated_dir, fake_bin):@@ -119,18 +121,17 @@ def test_venv_sweep_stops_managed_runtime_children_but_not_unrelated_processes("if not errorlevel 1 exit /b 0\n"'"%SystemRoot%\\System32\\taskkill.exe" %*\n',)- _write_cmd(- fake_bin / "uv.cmd",- "@echo off\n"- 'if /I "%~1 %~2"=="python find" (\n'- " echo C:\\Windows\\System32\\cmd.exe\n"- " exit /b 0\n"- ")\n"- 'if /I "%~1"=="venv" (\n'- ' if not exist "%CD%\\venv\\Scripts" mkdir "%CD%\\venv\\Scripts"\n'- " exit /b 0\n"- ")\n"- "exit /b 1\n",+ uv = hermes_home / "bin" / "uv.exe"+ uv.parent.mkdir(parents=True)+ compile_fake_uv(POWERSHELL, uv)+ wrapper = tmp_path / "run-venv-stage.ps1"+ wrapper.write_text(+ f"function global:schtasks {{ & '{fake_bin / 'schtasks.cmd'}' @args }}\n"+ f"function global:taskkill {{ & '{fake_bin / 'taskkill.cmd'}' @args }}\n"+ f"& '{INSTALL_PS1}' -Stage venv -NonInteractive "+ f"-InstallDir '{install_dir}' -HermesHome '{hermes_home}'\n"+ "exit $LASTEXITCODE\n",+ encoding="utf-8",)creation_flags = subprocess.CREATE_NO_WINDOW@@ -151,20 +152,16 @@ def test_venv_sweep_stops_managed_runtime_children_but_not_unrelated_processes(env = os.environ | {"OS": "Windows_NT","PATH": str(fake_bin) + os.pathsep + os.environ["PATH"],+ "FAKE_UV_LOG": str(tmp_path / "uv.log"),+ "FAKE_MANAGED_PYTHON": str(runtime_child_exe),+ "FAKE_THIRD_PARTY_PYTHON": str(unrelated_exe),}result = subprocess.run([POWERSHELL,"-NoProfile","-File",- str(INSTALL_PS1),- "-Stage",- "venv",- "-NonInteractive",- "-InstallDir",- str(install_dir),- "-HermesHome",- str(hermes_home),+ str(wrapper),],cwd=tmp_path,env=env,diff --git a/tests/test_install_ps1_venv_recreate_safety.py b/tests/test_install_ps1_venv_recreate_safety.pyindex f205be0bd54..0ff9bf66cdc 100644--- a/tests/test_install_ps1_venv_recreate_safety.py+++ b/tests/test_install_ps1_venv_recreate_safety.py@@ -46,7 +46,7 @@ def test_manual_recovery_hints_do_not_delete_live_venv() -> None:def test_previous_venv_survives_until_replacement_is_ready() -> None:body = _install_venv_body()- create = body.index("& $UvCmd venv venv")+ create = body.index("$venvProcess.Start()")stale_cleanup = body.index('Get-ChildItem -Directory -Filter "venv.stale.*"')assert create < stale_cleanup, ("stale backups must not be cleaned before uv can succeed or rollback"