Skip to content

The agent that grows with you

Merge origin/main into ethie/pm-clean

ethernetbb86a74b67e5
diff --cc apps/desktop/scripts/build-command-screenshot-monitor.mjs
index e14d44022f1,3af2b017e53..e584556717e
--- a/apps/desktop/scripts/build-command-screenshot-monitor.mjs
+++ b/apps/desktop/scripts/build-command-screenshot-monitor.mjs
@@@ -8,28 -9,25 +9,26 @@@ import { macosSysroot, xcrunClangArgv
const script = fileURLToPath(import.meta.url)
const root = resolve(dirname(script), '..')
- // `platform` is injectable so tests can exercise both branches without
- // redefining process.platform.
+ // `platform` and `sysroot` are injectable so tests can exercise the branches
+ // without redefining process.platform or shelling out to xcode-select.
export function buildCommandScreenshotMonitor({
- distDir = resolve(root, 'dist'),
+ source = resolve(root, '../..'),
+ distDir = resolve(source, 'apps/desktop/dist'),
platform = process.platform,
+ sysroot,
} = {}) {
if (platform !== 'darwin') return null
const output = resolve(distDir, 'native/command-screenshot-monitor')
const staging = `${output}.${process.pid}.tmp`
mkdirSync(dirname(output), { recursive: true })
+ const sdk = sysroot === undefined ? macosSysroot() : sysroot
try {
- // Pin the SDK explicitly: a bare `xcrun clang` inherits the host default
- // SDK, which may be newer than the active linker (unknown-arch .tbd stubs
- // at link time, #113708). `--sdk macosx` names the same default SDK while
- // forcing the driver and linker to agree on it.
execFileSync('xcrun', [
- '--sdk', 'macosx',
- 'clang', '-arch', 'arm64', '-arch', 'x86_64', '-mmacosx-version-min=11.0',
+ ...xcrunClangArgv(sdk),
+ '-arch', 'arm64', '-arch', 'x86_64', '-mmacosx-version-min=11.0',
'-fobjc-arc', '-fblocks', '-O2', '-Wall', '-Wextra',
'-framework', 'Cocoa', '-framework', 'CoreGraphics',
- resolve(root, 'electron/native/command-screenshot-monitor.m'), '-o', staging,
+ resolve(source, 'apps/desktop/electron/native/command-screenshot-monitor.m'), '-o', staging,
], { stdio: 'inherit', timeout: 120_000 })
chmodSync(staging, 0o755)
renameSync(staging, output)
diff --cc apps/desktop/scripts/build-hud-modifier-monitor.mjs
index a11a09a52c2,ee0d22e37ce..2b5eff582eb
--- a/apps/desktop/scripts/build-hud-modifier-monitor.mjs
+++ b/apps/desktop/scripts/build-hud-modifier-monitor.mjs
@@@ -1,9 -1,10 +1,10 @@@
#!/usr/bin/env node
// Host-built helper. Windows uses its in-box .NET Framework compiler; no SDK download.
import { execFileSync } from 'node:child_process'
-import { chmodSync, existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'
+import { chmodSync, existsSync, mkdirSync, renameSync, rmdirSync, rmSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+ import { macosSysroot, xcrunClangArgv } from './macos-sysroot.mjs'
const script = fileURLToPath(import.meta.url)
const root = resolve(dirname(script), '..')
@@@ -22,10 -23,10 +23,11 @@@ export function hudModifierBinaryRelati
}
export function buildHudModifierMonitor({
- distDir = resolve(root, 'dist'),
+ source = resolve(root, '../..'),
+ distDir = resolve(source, 'apps/desktop/dist'),
platform = process.platform,
- arch = process.arch
+ arch = process.arch,
+ sysroot
} = {}) {
// Cross-packaging must not ship a host binary under the target's name. The
// capability stays unavailable unless that target was built on its own host.
diff --cc hermes_bootstrap.py
index 5d86a17b9be,73107c34012..d57a9f4c7ba
--- a/hermes_bootstrap.py
+++ b/hermes_bootstrap.py
@@@ -317,91 -444,10 +427,92 @@@ def export_scratch_tmp_env() -> None
pass # a missing/unwritable home just leaves the system temp dir in place
-# Apply on import — entry points only need ``import hermes_bootstrap`` first.
+# Apply on import — entry points just need ``import hermes_bootstrap``
+# (or ``from hermes_bootstrap import apply_windows_utf8_bootstrap``) at
+# the very top of their module, before importing anything else. The
+# import side effect does the right thing.
apply_windows_utf8_bootstrap()
suppress_platform_ver_console()
+ install_never_free_environ()
-activate_durable_lazy_target()
+
+# Every entry point imports this module before its dependency graph.
+from pathlib import Path
+
+_root = Path(__file__).resolve().parent
+try:
+ os.getcwd()
+except FileNotFoundError:
+ # Reaped workspaces leave children in a deleted cwd. PM resolves relative
+ # import paths before the CLI's guards, so recover before any PM work.
+ os.chdir(_root)
+
+
+def _legacy_post_swap_invocation(argv: list[str]) -> tuple[Path, list[str]] | None:
+ """Recognize the exact fresh-checkout command emitted by shipped updaters."""
+ if not argv or argv[0] != "update":
+ return None
+ try:
+ marker = argv.index("--post-swap", 1)
+ except ValueError:
+ return None
+ if marker + 2 != len(argv):
+ return None
+ return Path(argv[marker + 1]), argv[1:marker]
+
+
+# Everything below imports Hermes packages, so the root goes on sys.path first. A venv
+# editable-installed from a pre-PM tree maps only the top-level packages it knew then:
+# without this, ``pm`` is unimportable and the launch silently skips PM adoption.
+harden_import_path(str(_root))
+
+_legacy_post_swap = _legacy_post_swap_invocation(sys.argv[1:])
+if _legacy_post_swap is not None:
+ # This continuation exists precisely because the replacement tree may not
+ # run under the old release's dependency graph. Take it over before PM
+ # activation, launch preparation, or argparse imports any of that graph.
+ from hermes_cli.update_handoff import _continue_legacy_post_swap
+
+ _handoff_path, _argv_tail = _legacy_post_swap
+ raise SystemExit(_continue_legacy_post_swap(_handoff_path, argv_tail=_argv_tail))
+
+
+from pm.environments import activate_dependencies
+from hermes_cli._early_recovery import recover_if_needed
+
+from hermes_cli._parser import command_argv
+
+# Repair needs only stdlib. Do not activate the damaged tree to reach it.
+_pm_repair = command_argv(sys.argv[1:])[:2] == ["pm", "repair"]
+if not _pm_repair:
+ from hermes_cli.venv_sync import prepare_launch, relaunch_command
+
+ try:
+ _launch_python = prepare_launch(_root, sys.argv[1:])
+ if _launch_python is not None:
+ _main_spec = getattr(sys.modules.get("__main__"), "__spec__", None)
+ _command = relaunch_command(
+ _launch_python, _root, sys.argv, sys.orig_argv,
+ getattr(_main_spec, "name", None),
+ )
+ if os.name == "nt":
+ import subprocess
+
+ raise SystemExit(subprocess.call(_command))
+ os.execv(str(_launch_python), _command)
+ except Exception as exc:
+ # Degrade, never brick the CLI: the previous dependency generation is still selected
+ # (a failed sync commits nothing), so an offline or half-finished update leaves a
+ # usable Hermes plus a warning. Activation below is the real gate — a tree whose
+ # dependencies cannot load still exits with the repair remedy.
+ print(f"hermes: source-update completion failed: {exc}; "
+ "running with the previous dependencies — run `hermes update` to finish it",
+ file=sys.stderr)
+ recover_if_needed(_root)
+ try:
+ activate_dependencies(_root)
+ except (RuntimeError, OSError) as exc:
+ if command_argv(sys.argv[1:])[:1] != ["pm"]:
+ print(f"hermes: {exc}; run `hermes pm repair`", file=sys.stderr)
+ raise SystemExit(1) from None
install_happy_eyeballs_socket_connect()
export_scratch_tmp_env()
diff --cc tests/test_hermes_bootstrap.py
index f846f284480,00ea711c536..1018184560e
--- a/tests/test_hermes_bootstrap.py
+++ b/tests/test_hermes_bootstrap.py
@@@ -179,135 -179,106 +179,155 @@@ class TestStdioReconfigureErrorHandling
-class TestEntryPointsImportBootstrap:
- """Every Hermes entry point must import hermes_bootstrap as its
- first non-docstring import. We check this by scanning source files
- rather than invoking the entry points (which would require a full
- agent context)."""
-
- # Entry points that invoke Hermes as a process. Each one must
- # import hermes_bootstrap before doing any file I/O or stdout writes.
- ENTRY_POINTS = [
- "hermes_cli/main.py", # hermes CLI (console_script)
- "run_agent.py", # hermes-agent (console_script)
- "acp_adapter/entry.py", # hermes-acp (console_script)
- "gateway/run.py", # gateway
- "batch_runner.py", # batch mode
- "cli.py", # legacy direct-launch CLI
- ]
-
- def test_library_imports_of_dual_use_entry_modules_stay_side_effect_free(self, tmp_path):
- # The codex hermes-tools MCP server and the compute host are ``python -m`` entry points
- # that agent/gateway code and tests also import; there the bootstrap exported TMPDIR and
- # HERMES_SCRATCH_DIR into every importer (gateway.relay's read-only routing included).
- code = textwrap.dedent("""
- import json, os, sys
- before = dict(os.environ)
- import agent.auxiliary_client, gateway.relay, tui_gateway.compute_host # noqa: F401
- changed = sorted(k for k in before.keys() | os.environ.keys() if before.get(k) != os.environ.get(k))
- print(json.dumps({"bootstrapped": "hermes_bootstrap" in sys.modules, "changed": changed}))
- """)
- repo = Path(__file__).resolve().parents[1]
- env = {k: os.environ[k] for k in ("PATH", "SYSTEMROOT", "WINDIR") if k in os.environ}
- env.update({"HOME": str(tmp_path), "USERPROFILE": str(tmp_path), "PYTHONPATH": str(repo),
- "HERMES_HOME": str(tmp_path / "home"), "PYTHONDONTWRITEBYTECODE": "1"})
- child = subprocess.run([sys.executable, "-c", code], cwd=str(tmp_path), env=env,
- capture_output=True, text=True, timeout=120)
- assert child.returncode == 0, child.stderr
- assert child.stdout.splitlines()[-1] == '{"bootstrapped": false, "changed": []}'
-
- @pytest.mark.parametrize("path", ENTRY_POINTS)
- def test_entry_point_imports_bootstrap(self, path):
- """The file must contain 'import hermes_bootstrap' and that
- line must appear before the first 'import' of anything else.
-
- We're lenient about the docstring (can be arbitrarily long) and
- about comment lines — just need to verify the first import
- statement is the bootstrap.
-
- Also lenient about a try/except wrapper around the import: entry
- points may guard the import against ``ModuleNotFoundError`` so a
- half-finished ``hermes update`` (git-reset landed new code but
- ``uv pip install -e .`` didn't finish re-registering
- ``hermes_bootstrap`` as a top-level module) leaves hermes
- recoverable instead of crashing on every invocation. When the
- first top-level node is such a guarded-import block, we peek
- inside it to verify bootstrap is the imported module.
- """
- # Resolve relative to the hermes-agent repo root. Tests live
- # at tests/test_hermes_bootstrap.py, so go up one dir.
- import pathlib
- here = pathlib.Path(__file__).resolve()
- repo_root = here.parent.parent # tests/ -> repo root
- full_path = repo_root / path
- assert full_path.exists(), f"entry point missing: {full_path}"
-
- source = full_path.read_text(encoding="utf-8")
-
- # Find the first non-comment, non-blank line that starts with
- # 'import ' or 'from ', or a Try block whose body is the import.
- import ast
- tree = ast.parse(source)
-
- first_import_node = None
- for node in ast.iter_child_nodes(tree):
- if isinstance(node, (ast.Import, ast.ImportFrom)):
- first_import_node = node
- break
- # Accept a guarded-import Try block where the body is a lone
- # Import node — this is the recovery-friendly form that lets
- # hermes start even when hermes_bootstrap hasn't been
- # re-registered in the venv yet.
- if isinstance(node, ast.Try) and len(node.body) == 1 and isinstance(
- node.body[0], (ast.Import, ast.ImportFrom)
- ):
- first_import_node = node.body[0]
- break
-
- assert first_import_node is not None, (
- f"{path}: no top-level imports found at all"
- )
-
- if isinstance(first_import_node, ast.Import):
- first_import_name = first_import_node.names[0].name
- else: # ImportFrom
- first_import_name = first_import_node.module or ""
-
- assert first_import_name == "hermes_bootstrap", (
- f"{path}: first top-level import is {first_import_name!r}, "
- f"but it must be 'hermes_bootstrap' so UTF-8 stdio is "
- f"configured before anything else initializes. Move the "
- f"'import hermes_bootstrap' line to be the first import."
- )
+ "hermes_cli/main.py", "run_agent.py", "acp_adapter/entry.py",
+ "gateway/run.py", "batch_runner.py", "cli.py",
+])
+def test_entrypoint_executes_bootstrap_before_application_imports(tmp_path, path):
+ import subprocess
+ from pathlib import Path
+
+ root = Path(__file__).resolve().parents[1]
+ entry = tmp_path / "startup.py"
+ entry.write_bytes((root / path).read_bytes())
+ # Stop at the first application import, after executing the REAL bootstrap.
+ # pm repair is the supported stdlib-only startup, so no update/service runs.
+ program = r"""
+import builtins, os, runpy, sys
+root, entry = sys.argv[1:]
+sys.path.insert(0, root)
+sys.argv = [entry, 'pm', 'repair']
+real_import = builtins.__import__
+class Boundary(BaseException): pass
+seen = []
+def guarded(name, globals=None, locals=None, fromlist=(), level=0):
+ if globals and globals.get('__file__') == entry:
+ if name == '__future__':
+ return real_import(name, globals, locals, fromlist, level)
+ if not seen:
+ assert name == 'hermes_bootstrap', name
+ module = real_import(name, globals, locals, fromlist, level)
+ assert module._pm_repair is True
+ assert module._bootstrap_applied is (sys.platform == 'win32')
+ seen.append(name)
+ return module
+ raise Boundary()
+ return real_import(name, globals, locals, fromlist, level)
+builtins.__import__ = guarded
+try:
+ runpy.run_path(entry, run_name='__main__')
+except Boundary:
+ assert seen == ['hermes_bootstrap']
+ print('bootstrap-before-app')
+else:
+ raise AssertionError('entrypoint never reached the application import boundary')
+"""
+ result = subprocess.run([sys.executable, "-I", "-S", "-c", program, str(root), str(entry)],
+ cwd=tmp_path, env={**os.environ, "HERMES_HOME": str(tmp_path / "home")},
+ capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "bootstrap-before-app"
+
++def test_library_imports_of_dual_use_entry_modules_stay_side_effect_free(tmp_path):
++ # The codex hermes-tools MCP server and the compute host are ``python -m`` entry points
++ # that agent/gateway code and tests also import; there the bootstrap exported TMPDIR and
++ # HERMES_SCRATCH_DIR into every importer (gateway.relay's read-only routing included).
++ code = textwrap.dedent("""
++ import json, os, sys
++ before = dict(os.environ)
++ import agent.auxiliary_client, gateway.relay, tui_gateway.compute_host # noqa: F401
++ changed = sorted(k for k in before.keys() | os.environ.keys() if before.get(k) != os.environ.get(k))
++ print(json.dumps({"bootstrapped": "hermes_bootstrap" in sys.modules, "changed": changed}))
++ """)
++ repo = Path(__file__).resolve().parents[1]
++ env = {k: os.environ[k] for k in ("PATH", "SYSTEMROOT", "WINDIR") if k in os.environ}
++ env.update({"HOME": str(tmp_path), "USERPROFILE": str(tmp_path), "PYTHONPATH": str(repo),
++ "HERMES_HOME": str(tmp_path / "home"), "PYTHONDONTWRITEBYTECODE": "1"})
++ child = subprocess.run([sys.executable, "-c", code], cwd=str(tmp_path), env=env,
++ capture_output=True, text=True, timeout=120)
++ assert child.returncode == 0, child.stderr
++ assert child.stdout.splitlines()[-1] == '{"bootstrapped": false, "changed": []}'
++
+
+def test_pre_pm_editable_venv_reaches_pm_through_the_bootstrap(tmp_path):
+ """A venv editable-installed from a pre-PM tree must still start the PM-era tree.
+
+ setuptools' flat-layout editable finder maps only the top-level names it saw at
+ install time (no ``pm``) and never puts the checkout on ``sys.path``. The console
+ script imports ``hermes_cli`` first, then ``hermes_cli.main`` imports the bootstrap;
+ both must load, and the bootstrap must reach ``pm``, or PM adoption never runs.
+ """
+ root = Path(__file__).resolve().parents[1]
+ program = r"""
+import importlib.util, os, sys
+from importlib.abc import MetaPathFinder
+root = sys.argv[1]
+class PrePMEditableFinder(MetaPathFinder):
+ def find_spec(self, name, path=None, target=None):
+ if name == 'hermes_cli':
+ pkg = os.path.join(root, 'hermes_cli')
+ return importlib.util.spec_from_file_location(
+ name, os.path.join(pkg, '__init__.py'), submodule_search_locations=[pkg])
+ if name == 'hermes_bootstrap':
+ return importlib.util.spec_from_file_location(name, os.path.join(root, 'hermes_bootstrap.py'))
+ return None
+sys.meta_path.append(PrePMEditableFinder())
+sys.argv = ['hermes', 'pm', 'repair']
+import hermes_cli
+import hermes_bootstrap
+assert hermes_bootstrap._pm_repair is True
+print('reached-pm')
+"""
+ result = subprocess.run([sys.executable, "-I", "-S", "-c", program, str(root)],
+ cwd=tmp_path, env={**os.environ, "HERMES_HOME": str(tmp_path / "home")},
+ capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "reached-pm"
+
+
+ "hermes_cli/main.py", "run_agent.py", "acp_adapter/entry.py",
+ "gateway/run.py", "batch_runner.py", "cli.py",
+])
[email protected]("bootstrap,expected", [
+ (None, "proceeded"),
+ ("import hermes_missing_dependency_probe\n", "raised hermes_missing_dependency_probe"),
+])
+def test_entrypoint_tolerates_only_an_absent_bootstrap(tmp_path, path, bootstrap, expected):
+ """The entry-point guard covers a bootstrap a partial update left unregistered.
+
+ A bootstrap that exists but cannot import its own dependencies must surface:
+ swallowing that skipped PM activation silently and the tree ran on stale deps.
+ """
+ root = Path(__file__).resolve().parents[1]
+ entry = tmp_path / "startup.py"
+ entry.write_bytes((root / path).read_bytes())
+ fake_root = tmp_path / "root"
+ fake_root.mkdir()
+ if bootstrap is not None:
+ (fake_root / "hermes_bootstrap.py").write_text(bootstrap)
+ program = r"""
+import builtins, runpy, sys
+fake_root, entry = sys.argv[1:]
+sys.path.insert(0, fake_root)
+real_import = builtins.__import__
+class Boundary(BaseException): pass
+def guarded(name, globals=None, locals=None, fromlist=(), level=0):
+ if globals and globals.get('__file__') == entry and name not in ('__future__', 'hermes_bootstrap'):
+ raise Boundary()
+ return real_import(name, globals, locals, fromlist, level)
+builtins.__import__ = guarded
+try:
+ runpy.run_path(entry, run_name='__main__')
+except Boundary:
+ print('proceeded')
+except ModuleNotFoundError as exc:
+ print('raised', exc.name)
+"""
+ result = subprocess.run([sys.executable, "-I", "-S", "-c", program, str(fake_root), str(entry)],
+ cwd=tmp_path, capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == expected
class TestHardenImportPath: