_startup_fast.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """Pre-import startup fast paths — THE canonical lightweight helpers.
  2. This module is imported by ``hermes_cli/main.py`` BEFORE its heavy import
  3. wall (config, argparse tree, logging, providers). Everything here must stay
  4. **stdlib-only and cheap** (os/sys file probes; no yaml, no hermes_cli.config,
  5. no argparse). A guard test (``test_startup_fast_import_weight``) subprocess-
  6. imports this module and fails if any heavy module sneaks into sys.modules.
  7. Why this module exists (the bug class it kills): version-printing kept being
  8. reimplemented as ``*_fast()`` copies at the top of main.py, each duplicating
  9. canonical logic — project-root resolution, container detection, profile
  10. detection. The copies drifted: eb4040242 changed the canonical output and
  11. referenced ``PROJECT_ROOT`` inside the fast function, which doesn't exist
  12. yet on the fast path → the fast path NameError'd on --version and nobody
  13. noticed. One implementation, imported by both the fast path and the module
  14. constants, makes that drift structurally impossible; the parity guard test
  15. would have caught eb4040242 the day it landed.
  16. ``hermes_cli/config.py``'s ``get_container_exec_info()`` reads the same
  17. ``.container-mode`` file; keep the file-format assumptions here and there in
  18. sync (this module deliberately only PROBES existence/typos cheaply and errs
  19. toward the slow path, which then does the authoritative parse).
  20. """
  21. from __future__ import annotations
  22. import os
  23. import sys
  24. __all__ = [
  25. "active_profile_may_override_home",
  26. "container_mode_may_be_active",
  27. "ensure_project_root_on_path",
  28. "is_container_startup_environment",
  29. "is_desktop_ssh_backend_argv",
  30. "is_global_fast_version_argv",
  31. "normalize_hermes_home_env",
  32. "print_fast_version_info",
  33. "project_root_str",
  34. "read_install_method",
  35. "read_openai_version",
  36. "try_fast_version",
  37. ]
  38. def _read_text(path: str) -> str | None:
  39. """Read a small text file, or None when it is missing/unreadable."""
  40. try:
  41. with open(path, encoding="utf-8-sig") as handle:
  42. return handle.read()
  43. except (OSError, UnicodeDecodeError):
  44. return None
  45. def project_root_str() -> str:
  46. """Repo root as a str — the single source for main.py's PROJECT_ROOT."""
  47. return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir))
  48. def normalize_hermes_home_env() -> None:
  49. """Expand ``~``/``$VAR`` in ``HERMES_HOME`` once, at process entry, and write it back.
  50. fish does not expand ``~`` inside ``VAR=~/...`` and every shell passes a quoted value
  51. through verbatim, so a literal tilde reaches the process. ``Path("~/.hermes")`` is
  52. *relative*: the many raw ``os.environ["HERMES_HOME"]`` readers (this fast path, the
  53. active_profile probe, profile re-home, the dotenv loader) would each resolve it against
  54. cwd and scaffold a full home under ``<cwd>/~/.hermes``. One expansion here gives every
  55. reader the same absolute spelling; ``hermes_constants`` expands as well for non-CLI
  56. entry points. A relative value that is not tilde/variable-shaped is left alone.
  57. """
  58. raw = os.environ.get("HERMES_HOME", "")
  59. if not raw.strip():
  60. return
  61. expanded = os.path.expanduser(os.path.expandvars(raw.strip()))
  62. if expanded != raw:
  63. os.environ["HERMES_HOME"] = expanded
  64. def _realpath_or_self(path: str) -> str:
  65. """``os.path.realpath`` that survives a deleted cwd.
  66. A relative ``sys.path`` entry is resolved through ``os.getcwd()``, which raises
  67. ``FileNotFoundError`` once the directory the process started in has been removed
  68. (a cron delivery child spawned from a reaped scratch workspace, #102941); the CLI
  69. then dies before it can parse argv.
  70. """
  71. try:
  72. return os.path.realpath(path)
  73. except OSError:
  74. return path
  75. def ensure_project_root_on_path() -> None:
  76. """Put the project root at sys.path[0], deduping realpath-equivalents."""
  77. project_root = project_root_str()
  78. normalized_root = os.path.normcase(_realpath_or_self(project_root))
  79. sys.path[:] = [entry for entry in sys.path
  80. if not entry or os.path.normcase(_realpath_or_self(entry)) != normalized_root]
  81. sys.path.insert(0, project_root)
  82. def is_global_fast_version_argv(argv: list[str]) -> bool:
  83. return argv in (["--version"], ["-V"])
  84. def is_desktop_ssh_backend_argv(argv: list[str]) -> bool:
  85. """Is ``argv`` the Desktop client's SSH backend spawn (``serve --ssh-session-token-file``)?
  86. That child has a fixed identity: Desktop names the remote profile explicitly (or none for
  87. the root home) and hands its session token through a 0600 FILE, never the
  88. ``HERMES_DASHBOARD_SESSION_TOKEN`` env var the local pool spawn uses. Every reader of
  89. "is this process Desktop's backend" needs both shapes; this is the argv half.
  90. """
  91. return "--ssh-session-token-file" in argv
  92. def is_container_startup_environment() -> bool:
  93. """True when we're already INSIDE a container (fast path is then safe)."""
  94. if os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv"):
  95. return True
  96. cgroup = _read_text("/proc/1/cgroup") or ""
  97. return "docker" in cgroup or "podman" in cgroup or "/lxc/" in cgroup
  98. def active_profile_may_override_home(hermes_root: str) -> bool:
  99. """Cheap probe: does an active non-default profile redirect HERMES_HOME?"""
  100. active = (_read_text(os.path.join(hermes_root, "active_profile")) or "").strip()
  101. return bool(active and active != "default")
  102. def _default_home() -> str:
  103. return os.path.join(os.path.expanduser("~"), ".hermes")
  104. def _resolved_home() -> str:
  105. return os.environ.get("HERMES_HOME", "").strip() or _default_home()
  106. def container_mode_may_be_active() -> bool:
  107. """Conservative probe for NixOS container-mode routing.
  108. False positives are fine (the slow path does the authoritative check). False negatives are NOT —
  109. they'd print the host's version instead of the container's — so any profile ambiguity means "may
  110. be active".
  111. """
  112. if os.environ.get("HERMES_DEV") == "1" or is_container_startup_environment():
  113. return False
  114. hermes_home = os.environ.get("HERMES_HOME", "").strip()
  115. if hermes_home:
  116. if os.path.exists(os.path.join(hermes_home, ".container-mode")):
  117. return True
  118. parent_name = os.path.basename(os.path.dirname(os.path.normpath(hermes_home)))
  119. return parent_name != "profiles" and active_profile_may_override_home(hermes_home)
  120. default_home = _default_home()
  121. return active_profile_may_override_home(default_home) or os.path.exists(
  122. os.path.join(default_home, ".container-mode"))
  123. def read_openai_version() -> str | None:
  124. """Read OpenAI SDK version without importing ``importlib.metadata``."""
  125. for base in sys.path:
  126. version_file = os.path.join(base or os.getcwd(), "openai", "_version.py")
  127. try:
  128. with open(version_file, encoding="utf-8-sig") as handle:
  129. for line in handle:
  130. stripped = line.strip()
  131. if not stripped.startswith("__version__"):
  132. continue
  133. _key, _sep, value = stripped.partition("=")
  134. value = value.split("#", 1)[0].strip().strip("\"'")
  135. return value or None
  136. except OSError:
  137. continue
  138. return None
  139. def read_install_method() -> str | None:
  140. """The installer's ``.install_method`` stamp, if present.
  141. Only the stamp (step 1 of ``config.detect_install_method``'s resolution order) — the
  142. managed/git/pip fallbacks need heavier imports and stay on the slow path.
  143. """
  144. method = _read_text(os.path.join(_resolved_home(), ".install_method"))
  145. return (method or "").strip().lower() or None
  146. def print_fast_version_info(*, check_updates: bool = True) -> None:
  147. """THE canonical ``hermes --version`` output (also used by /version).
  148. Every lazy block degrades gracefully — a broken/heavy import can never take the basic version
  149. output down.
  150. """
  151. # Registry-owned banner label (includes "· upstream <sha>" for git installs); banner.py keeps
  152. # rich/prompt_toolkit lazy, so this import is light.
  153. try:
  154. from hermes_cli.banner import format_banner_version_label
  155. print(format_banner_version_label())
  156. except Exception:
  157. from hermes_cli import __release_date__
  158. from hermes_cli.version_info import get_version_info
  159. print(f"Hermes Agent v{get_version_info().derived_version} ({__release_date__})")
  160. print(f"Install directory: {project_root_str()}")
  161. # Authoritative resolver first (code-scoped stamp → managed → nix → git → pip; also self-heals
  162. # poisoned shared-home 'docker' stamps); cheap stdlib stamp probe only if it fails.
  163. try:
  164. from pathlib import Path
  165. from hermes_cli.config import detect_install_method
  166. install_method = detect_install_method(Path(project_root_str()))
  167. except Exception:
  168. install_method = read_install_method()
  169. if install_method:
  170. print(f"Install method: {install_method}")
  171. print(f"Python: {sys.version.split()[0]}")
  172. openai_version = read_openai_version()
  173. print(f"OpenAI SDK: {openai_version}" if openai_version else "OpenAI SDK: Not installed")
  174. if not check_updates:
  175. return
  176. # Synchronous update status — bounded by check_for_updates' own subprocess/network timeouts
  177. # and its 6-hour cache; any failure prints nothing.
  178. try:
  179. from hermes_cli.source_check import UPDATE_AVAILABLE_NO_COUNT, check_for_updates
  180. from hermes_cli.config import recommended_update_command
  181. status = check_for_updates(passive=True)
  182. behind = status.get("behind")
  183. if status.get("rollback"):
  184. print(f"Newer than stable release v{status.get('sourceVersion')} — "
  185. f"'{recommended_update_command()}' moves back to it")
  186. elif behind == UPDATE_AVAILABLE_NO_COUNT:
  187. print(f"Update available — run '{recommended_update_command()}'")
  188. elif behind and behind > 0:
  189. commits_word = "commit" if behind == 1 else "commits"
  190. print(f"Update available: {behind} {commits_word} behind — run '{recommended_update_command()}'")
  191. elif behind == 0:
  192. print("Up to date")
  193. except Exception:
  194. pass
  195. def try_fast_version(argv: list[str] | None = None) -> bool:
  196. """Handle ``hermes --version`` before the heavy import wall.
  197. Only ``--version``/``-V`` (the ``version`` subcommand was removed —
  198. ``--version`` now carries the full output incl. update status), and
  199. never when container mode may need to route the command into the
  200. container.
  201. """
  202. if argv is None:
  203. argv = sys.argv[1:]
  204. if not is_global_fast_version_argv(argv):
  205. return False
  206. if container_mode_may_be_active():
  207. return False
  208. print_fast_version_info()
  209. return True