relaunch.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """Unified self-relaunch for Hermes CLI: preserves inherited flags (--tui, --dev, --profile, --model…)
  2. across process replacement so ``hermes sessions browse`` / post-setup relaunch keep the user's mode."""
  3. import os
  4. import pathlib
  5. import shutil
  6. import sys
  7. from typing import Optional, Sequence
  8. from hermes_cli._parser import (
  9. PRE_ARGPARSE_INHERITED_FLAGS, build_top_level_parser
  10. )
  11. def _build_inherited_flag_table() -> list[tuple[str, bool]]:
  12. """``(option_string, takes_value)`` for every parser Action carrying ``inherit_on_relaunch``
  13. (set by ``_parser._inherited_flag``), plus the pre-argparse flags."""
  14. parser, _subparsers, chat_parser = build_top_level_parser()
  15. table: list[tuple[str, bool]] = []
  16. seen: set[tuple[str, bool]] = set()
  17. for p in (parser, chat_parser):
  18. for action in p._actions:
  19. if not action.option_strings:
  20. continue # positional / no flag form
  21. if not getattr(action, "inherit_on_relaunch", False):
  22. continue
  23. takes_value = action.nargs != 0 # store_true/false set nargs=0
  24. for opt in action.option_strings:
  25. key = (opt, takes_value)
  26. if key not in seen:
  27. seen.add(key)
  28. table.append(key)
  29. table.extend(PRE_ARGPARSE_INHERITED_FLAGS)
  30. return table
  31. _INHERITED_FLAGS_TABLE = _build_inherited_flag_table()
  32. def _extract_inherited_flags(argv: Sequence[str]) -> list[str]:
  33. """Pull out flags that should carry over into a self-relaunched hermes."""
  34. flags: list[str] = []
  35. i = 0
  36. while i < len(argv):
  37. arg = argv[i]
  38. if "=" in arg:
  39. if any(arg.split("=", 1)[0] == flag for flag, _ in _INHERITED_FLAGS_TABLE):
  40. flags.append(arg)
  41. i += 1
  42. continue
  43. for flag, takes_value in _INHERITED_FLAGS_TABLE:
  44. if arg == flag:
  45. flags.append(arg)
  46. if takes_value and i + 1 < len(argv) and not argv[i + 1].startswith("-"):
  47. flags.append(argv[i + 1])
  48. i += 1
  49. break
  50. i += 1
  51. return flags
  52. def resolve_hermes_bin() -> Optional[str]:
  53. """Hermes entry point: ``sys.argv[0]`` if a real executable, else ``which hermes``, else ``None``
  54. (caller falls back to ``python -m hermes_cli.main``).
  55. Python launchers are never returned: on Windows a ``.py`` can't be exec'd directly, and on
  56. POSIX the git installer runs the extensionless source launcher under the managed venv
  57. interpreter while its ``#!/usr/bin/env python3`` shebang would pick the system Python and
  58. lose the venv. Falling through to ``sys.executable -m hermes_cli.main`` keeps the venv.
  59. """
  60. argv0 = sys.argv[0]
  61. _is_windows = sys.platform == "win32"
  62. def _is_python_script(p: str) -> bool:
  63. return p.lower().endswith((".py", ".pyc"))
  64. def _is_unsafe_python_launcher(p: str) -> bool:
  65. if _is_windows:
  66. return _is_python_script(p)
  67. # A console script pinned to the running venv (``#!<venv>/bin/python``) keeps the venv and
  68. # stays exec-able; a shebang that resolves elsewhere (``env python3``) loses it.
  69. from hermes_cli.linux_desktop_entry import _needs_interpreter
  70. return _needs_interpreter(pathlib.Path(p))
  71. # Absolute executable (nix store, venv wrappers, …), then relative-to-CWD, then PATH.
  72. if (
  73. os.path.isabs(argv0) and os.path.isfile(argv0) and os.access(argv0, os.X_OK)
  74. and not _is_unsafe_python_launcher(argv0)
  75. ):
  76. return argv0
  77. if not argv0.startswith("-") and os.path.isfile(argv0):
  78. abs_path = os.path.abspath(argv0)
  79. if os.access(abs_path, os.X_OK) and not _is_unsafe_python_launcher(abs_path):
  80. return abs_path
  81. path_bin = shutil.which("hermes")
  82. if path_bin and not _is_unsafe_python_launcher(path_bin):
  83. return path_bin
  84. return None
  85. def build_relaunch_argv(
  86. extra_args: Sequence[str], *, preserve_inherited: bool = True, original_argv: Optional[Sequence[str]] = None
  87. ) -> list[str]:
  88. """Construct an argv list for replacing the current process with hermes."""
  89. bin_path = resolve_hermes_bin()
  90. argv = [bin_path] if bin_path else [sys.executable, "-m", "hermes_cli.main"]
  91. src = list(original_argv) if original_argv is not None else list(sys.argv[1:])
  92. if preserve_inherited:
  93. argv.extend(_extract_inherited_flags(src))
  94. argv.extend(extra_args)
  95. return argv
  96. def relaunch(
  97. extra_args: Sequence[str], *, preserve_inherited: bool = True, original_argv: Optional[Sequence[str]] = None
  98. ) -> None:
  99. """Replace the current process with a fresh hermes invocation.
  100. POSIX: ``os.execvp`` in place (same PID, no double-fork). Windows has no real exec — its
  101. ``execvp`` emulation only works for a real Win32 executable, so spawn + exit instead.
  102. """
  103. new_argv = build_relaunch_argv(extra_args, preserve_inherited=preserve_inherited, original_argv=original_argv)
  104. if sys.platform == "win32":
  105. import subprocess
  106. try:
  107. result = subprocess.run(new_argv, check=False)
  108. sys.exit(result.returncode)
  109. except KeyboardInterrupt:
  110. sys.exit(130)
  111. except OSError as exc:
  112. # Raw ``[Errno 8] Exec format error`` is cryptic; usual causes are ``hermes`` not on
  113. # PATH yet (install hasn't propagated User PATH into this shell) or a stale shim.
  114. print(
  115. f"\nHermes relaunch failed: {exc}\n"
  116. f"Command: {' '.join(new_argv)}\n"
  117. f"Fix: open a new terminal so PATH picks up, then re-run hermes.",
  118. file=sys.stderr,
  119. )
  120. sys.exit(1)
  121. else:
  122. from hermes_cli.cpu_profile import write_cpu_profile
  123. from hermes_cli.observability.shared_metrics_startup import mark_in_place_relaunch
  124. mark_in_place_relaunch()
  125. write_cpu_profile() # exec skips atexit
  126. os.execvp(new_argv[0], new_argv)