hermes_constants.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. """Shared constants for Hermes Agent.
  2. Import-safe, stdlib-only — importable from anywhere without circular-import risk.
  3. """
  4. import contextlib
  5. import os
  6. import re
  7. import shutil
  8. import stat
  9. import sys
  10. from collections.abc import Callable, Mapping, MutableMapping
  11. from contextvars import ContextVar, Token
  12. from pathlib import Path
  13. _profile_fallback_warned: bool = False
  14. _UNSET = object()
  15. _HERMES_HOME_OVERRIDE: ContextVar[str | object] = ContextVar("_HERMES_HOME_OVERRIDE", default=_UNSET)
  16. # TUI busy-indicator styles (CLI /indicator, TUI gateway config, /help registry).
  17. # Keep in sync with INDICATOR_STYLES / DEFAULT_INDICATOR_STYLE in ui-tui/src/app/interfaces.ts.
  18. INDICATOR_STYLES: tuple[str, ...] = ("ascii", "emoji", "kaomoji", "unicode")
  19. DEFAULT_INDICATOR_STYLE: str = "kaomoji"
  20. # Browser-hosted attachments are staged on the Hermes host and then read back
  21. # as a base64 data URL for the normal remote attachment RPC. Keep the upload
  22. # and read-back boundaries identical so a successful picker/drop can always be
  23. # attached afterward.
  24. WEBAPP_ATTACHMENT_MAX_BYTES: int = 16 * 1024 * 1024
  25. def set_hermes_home_override(path: str | Path | None) -> Token:
  26. """Set a context-local Hermes home override and return its reset token.
  27. Deliberately does not mutate ``os.environ`` (shared by every thread in the process).
  28. """
  29. value: str | object = _UNSET if path is None else str(path)
  30. return _HERMES_HOME_OVERRIDE.set(value)
  31. def reset_hermes_home_override(token: Token) -> None:
  32. """Restore the previous context-local Hermes home override."""
  33. _HERMES_HOME_OVERRIDE.reset(token)
  34. def get_hermes_home_override() -> str | None:
  35. """Return the active context-local Hermes home override, if any."""
  36. override = _HERMES_HOME_OVERRIDE.get()
  37. return str(override) if override is not _UNSET and override else None
  38. def _expand_hermes_home(path: str) -> Path:
  39. """Expand environment and user-home syntax in a Hermes home path."""
  40. return Path(os.path.expanduser(os.path.expandvars(path)))
  41. def _platform_default_hermes_home(environ: Mapping[str, str], user_home: Callable[[], Path]) -> Path:
  42. """The platform default that *environ* names, with the literal data-directory suffix."""
  43. suffix = environ.get("HERMES_DATA_DIR_SUFFIX", "")
  44. if sys.platform == "win32":
  45. local_appdata = environ.get("LOCALAPPDATA", "").strip()
  46. base = Path(local_appdata) if local_appdata else user_home() / "AppData" / "Local"
  47. return base / ("hermes" + suffix)
  48. return user_home() / (".hermes" + suffix)
  49. def _get_platform_default_hermes_home() -> Path:
  50. """Return the platform default with the literal data-directory suffix."""
  51. return _platform_default_hermes_home(os.environ, Path.home)
  52. def _account_home() -> Path:
  53. """The OS account's home from the password database, never ``$HOME``: harnesses and profile isolation
  54. repoint HOME (root under ``sudo`` has uid 0 too, which keeps the #108674 remap). Falls back to the
  55. shared real-home resolver where pwd cannot answer."""
  56. try:
  57. import pwd
  58. return Path(pwd.getpwuid(os.getuid()).pw_dir) # windows-footgun: ok — POSIX-only module inside try/except
  59. except (ImportError, KeyError, OSError, AttributeError):
  60. return Path(get_real_home())
  61. def account_default_hermes_home() -> Path:
  62. """The platform default of the OS ACCOUNT, never of a foreign process ``HOME``.
  63. Host service identities (``systemctl --user`` units, LaunchAgents) belong to the account, and their
  64. definitions are found under the account home. A process started with ``HOME=<scratch>`` used to call
  65. ``<scratch>/.hermes`` native, name the bare ``hermes-gateway`` unit, and stop the account's real
  66. gateway through it. When the process HOME is the account home the two answers are the same home.
  67. """
  68. account = _account_home()
  69. try:
  70. same = Path.home().resolve() == account.resolve()
  71. except (OSError, RuntimeError):
  72. same = False
  73. return _get_platform_default_hermes_home() if same else _platform_default_hermes_home(os.environ, lambda: account)
  74. def _hermes_root_of(native_home: Path, env_path: Path | None) -> Path:
  75. """The root that holds *env_path*: the native home, a custom root, or *env_path* itself."""
  76. if env_path is None:
  77. return native_home
  78. try:
  79. env_path.resolve().relative_to(native_home.resolve()) # under ~/.hermes (normal or profile mode)
  80. except ValueError: # Docker/custom root: <root>/profiles/<name> -> <root>, else HERMES_HOME itself
  81. return env_path.parent.parent if env_path.parent.name == "profiles" else env_path
  82. return native_home
  83. _ENV_REFERENCE = re.compile(r"%([^%]+)%|\$\{([^}]+)\}|\$([A-Za-z0-9_-]+)")
  84. def hermes_root_for_environment(environ: Mapping[str, str]) -> Path | None:
  85. """The Hermes root that a process started with *environ* resolves, or None.
  86. Applies the root rules of ``get_default_hermes_root`` to another process's
  87. environment. ``%NAME%``, ``${NAME}`` and ``$NAME`` references and a leading
  88. ``~`` expand from *environ* alone, never from this process. Returns None
  89. when the answer depends on anything outside *environ*: a relative
  90. HERMES_HOME, an undefined variable, or a missing user profile folder.
  91. """
  92. names = {key.upper(): value for key, value in environ.items()}
  93. profile = names.get("USERPROFILE" if sys.platform == "win32" else "HOME", "").strip()
  94. def user_home() -> Path:
  95. if not profile:
  96. raise LookupError("no user profile folder")
  97. return Path(profile)
  98. raw = names.get("HERMES_HOME", "").strip()
  99. try:
  100. native_home = _platform_default_hermes_home(names, user_home)
  101. if not raw:
  102. return native_home
  103. expanded = _ENV_REFERENCE.sub(lambda match: names[match.group(match.lastindex).upper()], raw)
  104. if expanded == "~" or expanded.startswith(("~/", "~\\")):
  105. expanded = str(user_home()) + expanded[1:]
  106. except LookupError:
  107. return None
  108. env_path = Path(expanded)
  109. return _hermes_root_of(native_home, env_path) if env_path.is_absolute() else None
  110. def sudo_invoker_default_home() -> Path | None:
  111. """The invoking user's native ``~/.hermes`` when this process is root under ``sudo``, else None.
  112. sudo strips HERMES_HOME and sets HOME=/root, so the process's own default is root's; the profile
  113. store and the system service being operated on belong to SUDO_USER.
  114. """
  115. if not hasattr(os, "geteuid") or os.geteuid() != 0:
  116. return None
  117. sudo_user = os.environ.get("SUDO_USER", "").strip()
  118. if not sudo_user or sudo_user == "root":
  119. return None
  120. import pwd
  121. try:
  122. return Path(pwd.getpwnam(sudo_user).pw_dir) / ".hermes"
  123. except KeyError: # SUDO_USER not in passwd (chroot/container)
  124. return None
  125. def _warn_profile_fallback_once() -> None:
  126. """Warn once when HERMES_HOME is unset but a non-default profile is sticky-active (wrong fallback)."""
  127. global _profile_fallback_warned
  128. if _profile_fallback_warned:
  129. return
  130. # Latch on the FIRST check regardless of outcome (one-shot contract). Previously the latch
  131. # was only set on the warning branch, so with no active_profile (or "default") the stat +
  132. # read re-ran on every get_hermes_home() call (#90065).
  133. _profile_fallback_warned = True
  134. try:
  135. fallback_home = _get_platform_default_hermes_home()
  136. active_path = fallback_home / "active_profile"
  137. active = active_path.read_text(encoding="utf-8").strip() if active_path.exists() else ""
  138. except (UnicodeDecodeError, OSError):
  139. active = ""
  140. if active and active != "default":
  141. # Direct stderr, not logging: runs at import time (often before logging is
  142. # configured) and root-logger propagation would double-emit.
  143. msg = (
  144. f"[HERMES_HOME fallback] HERMES_HOME is unset but active "
  145. f"profile is {active!r}. Falling back to {fallback_home}, which "
  146. f"is the DEFAULT profile — not {active!r}. Any data this "
  147. f"process writes will land in the wrong profile. The "
  148. f"subprocess spawner should pass HERMES_HOME explicitly "
  149. f"(see issue #18594)."
  150. )
  151. with contextlib.suppress(Exception):
  152. sys.stderr.write(msg + "\n")
  153. sys.stderr.flush()
  154. def get_hermes_home() -> Path:
  155. """Hermes home: context-local override → ``HERMES_HOME`` env var → platform default."""
  156. override = get_hermes_home_override()
  157. if override:
  158. return _expand_hermes_home(override)
  159. if not os.environ.get("HERMES_HOME", "").strip():
  160. _warn_profile_fallback_once()
  161. return get_process_hermes_home()
  162. # Resolved keys, keyed by the path string that was handed in. Path.resolve()
  163. # is a filesystem call, and this function sits under every ToolRegistry
  164. # lookup through current_scope_key(), so without this the registry pays a
  165. # syscall per lookup. A process only ever sees a handful of home paths, so
  166. # the dict stays tiny. Only paths that really exist are stored, see below.
  167. _HOME_KEY_CACHE: dict[str, str] = {}
  168. def hermes_home_key(path: str | Path | None = None) -> str:
  169. """Stable registry key for a Hermes home/profile dir.
  170. ``strict=False`` so profiles whose directories don't exist yet still get a key.
  171. The resolved value is remembered per input path. A directory that does
  172. not exist yet is resolved without touching the cache, because the answer
  173. can change once it is created (e.g. part of the path turns out to be a symlink).
  174. """
  175. candidate = Path(path) if path is not None else get_hermes_home()
  176. raw = str(candidate)
  177. cached = _HOME_KEY_CACHE.get(raw)
  178. if cached is not None:
  179. return cached
  180. expanded = candidate.expanduser()
  181. try:
  182. resolved = expanded.resolve(strict=True)
  183. except OSError:
  184. # Not on disk yet: lenient resolve, not stored, so the real answer is
  185. # picked up once the directory appears.
  186. return os.path.normcase(str(expanded.resolve(strict=False)))
  187. key = os.path.normcase(str(resolved))
  188. _HOME_KEY_CACHE[raw] = key
  189. return key
  190. def reset_hermes_home_key_cache() -> None:
  191. """Forget every remembered home key (for tests that move a home dir on disk)."""
  192. _HOME_KEY_CACHE.clear()
  193. def get_process_hermes_home() -> Path:
  194. """Hermes home of the running process, ignoring task overrides.
  195. For process-level assets (theme YAML, dashboard plugin manifests) that must stay visible while a
  196. request is scoped to another profile (e.g. embedded ``/chat`` under ``--open-profile``). Follows
  197. ``HERMES_HOME`` live on purpose: routed-profile DECISIONS compare against
  198. :func:`get_routing_process_hermes_home` instead (#119242).
  199. """
  200. val = os.environ.get("HERMES_HOME", "").strip()
  201. return _expand_hermes_home(val) if val else _get_platform_default_hermes_home()
  202. # Host-pinned identity of the profile this process serves as its own (None: follow HERMES_HOME).
  203. _PINNED_PROCESS_HERMES_HOME: str | None = None
  204. def pin_process_hermes_home(path: str | Path | None) -> None:
  205. """Pin the home this process serves as its own profile, for "is this task routed?" decisions.
  206. An embedding host that serves several profiles and mirrors the active turn's profile into
  207. ``os.environ["HERMES_HOME"]`` for legacy readers (Hermes WebUI) otherwise makes every turn's own
  208. profile look like the launch profile: ``agent.secret_scope.serves_routed_profile()`` turns
  209. False and that turn's MCP connections fall back to bare, cross-profile names; the sibling
  210. launch-home checks (``secret_scope._is_process_home``, ``tools.environments.local._is_routed_home``,
  211. ``hermes_cli.env_loader._process_hermes_home``) misjudge the same way. ``None`` clears the pin.
  212. Process-global on purpose: it names the process's own identity, not a per-task value. It is NOT
  213. folded into :func:`get_process_hermes_home`: :func:`get_hermes_home` falls back to that for
  214. tasks carrying no override, and the host's mirror exists precisely so those readers see the
  215. served profile. Hosts that never mutate ``HERMES_HOME`` need not call this (no-op).
  216. """
  217. global _PINNED_PROCESS_HERMES_HOME
  218. _PINNED_PROCESS_HERMES_HOME = None if path is None else str(path)
  219. def process_hermes_home_is_pinned() -> bool:
  220. return _PINNED_PROCESS_HERMES_HOME is not None
  221. def get_routing_process_hermes_home() -> Path:
  222. """Launch home for routed-profile decisions: the pinned home, else :func:`get_process_hermes_home`."""
  223. pinned = _PINNED_PROCESS_HERMES_HOME
  224. return _expand_hermes_home(pinned) if pinned else get_process_hermes_home()
  225. # Hermes-managed runtime downloads at the root of a home (GGUF models, llama.cpp runtimes,
  226. # managed Node): re-downloadable on demand and routinely tens to hundreds of GB. Shared by
  227. # ``hermes backup`` (excludes them) and ``profile create --clone-all`` (skips them from the
  228. # default profile) so the two lists cannot drift apart.
  229. LOCAL_RUNTIME_ROOT_DIRS: frozenset[str] = frozenset({"models", "runtimes", "node"})
  230. # Where connector tool results save the files they return, under each profile's home.
  231. CONNECTOR_DOWNLOADS_SUBDIR = Path("downloads", "connectors")
  232. # get_default_hermes_root() memo keyed on (native home, expanded HERMES_HOME) so it stays
  233. # fresh when a test or plugin mutates either input; saves ~80us/call at 31+ sites.
  234. _default_hermes_root_memo: tuple[str, str, Path] | None = None
  235. def get_default_hermes_root(*, home: str | Path | None = None) -> Path:
  236. """Root of an explicit home, or the process home when none is supplied."""
  237. global _default_hermes_root_memo
  238. # Yaovi: each Bot's runtime home reads the system-layer Hermes root as its profile parent
  239. # (auth.json read-through), mirroring Hermes profile mode without the profiles/ layout.
  240. yaovi_root = os.environ.get("YAOVI_HERMES_ROOT", "").strip() if home is None else ""
  241. if yaovi_root:
  242. return Path(yaovi_root).expanduser()
  243. native_home = _get_platform_default_hermes_home()
  244. env_home = str(home).strip() if home is not None else os.environ.get("HERMES_HOME", "").strip()
  245. env_path = _expand_hermes_home(env_home) if env_home else None
  246. memo_key = (str(native_home), str(env_path) if env_path is not None else "")
  247. memo = _default_hermes_root_memo
  248. if memo is not None and memo[:2] == memo_key:
  249. return memo[2]
  250. result = _hermes_root_of(native_home, env_path)
  251. _default_hermes_root_memo = (*memo_key, result)
  252. return result
  253. # Tombstone lives beside the profile dir (not inside) so a stale mkdir or rmtree cannot erase it.
  254. _DELETED_PROFILES_DIR = ".deleted"
  255. # Files marking a real Hermes home; arbitrary dirs with a ``profiles`` segment lack them.
  256. _HERMES_HOME_MARKERS = ("config.yaml", ".env", "state.db")
  257. def _is_hermes_profiles_root(profiles_dir: Path) -> bool:
  258. """True when *profiles_dir* is provably ``<hermes-home>/profiles``.
  259. Accepts the classic ``~/.hermes`` layout, a root carrying Hermes-home marker files, a
  260. ``profiles/.deleted`` tombstone dir (only ``profile delete`` creates it), or the default root.
  261. """
  262. root = profiles_dir.parent
  263. if root.name == ".hermes":
  264. return True
  265. try:
  266. if (profiles_dir / _DELETED_PROFILES_DIR).is_dir() or any(
  267. (root / marker).exists() for marker in _HERMES_HOME_MARKERS
  268. ):
  269. return True
  270. except OSError:
  271. pass
  272. try:
  273. return root.resolve(strict=False) == get_default_hermes_root().resolve(strict=False)
  274. except OSError:
  275. return False
  276. def named_profile_home(path: str | Path) -> Path | None:
  277. """Return ``<root>/profiles/<name>`` when *path* is that home or under it.
  278. Requires ``<name>`` not to start with ``.`` and the ``profiles`` parent to be a real Hermes home;
  279. a default home whose path merely contains a ``profiles`` segment is not a named profile.
  280. """
  281. current = Path(path)
  282. for candidate in (current, *current.parents):
  283. if (candidate.parent.name == "profiles" and not candidate.name.startswith(".")
  284. and _is_hermes_profiles_root(candidate.parent)):
  285. return candidate
  286. if candidate.name == ".hermes": # default home: a coincidental profiles/ ancestor is not a root
  287. return None
  288. return None
  289. def profile_name_for_home(path: str | Path | None) -> str | None:
  290. """Return the canonical profile id owning *path*, or ``None`` when it is not a profile home.
  291. The default home is the Hermes root itself, so its basename is an installation detail (``.hermes``
  292. on POSIX and commonly ``hermes`` on Windows), not the profile id ``default``.
  293. """
  294. if path is None or not str(path).strip():
  295. return None
  296. current = Path(path).expanduser()
  297. try:
  298. default_root = get_default_hermes_root()
  299. for candidate in (current, current.resolve(strict=False)):
  300. if candidate == default_root or candidate == default_root.resolve(strict=False):
  301. return "default"
  302. named = named_profile_home(candidate)
  303. if named is not None:
  304. return named.name
  305. # A stored profile home is authoritative: its owner already resolved it, so the
  306. # <root>/profiles/<name> shape names the profile even when <root> carries no markers.
  307. if candidate.parent.name == "profiles" and not candidate.name.startswith("."):
  308. return candidate.name
  309. except (OSError, RuntimeError, ValueError):
  310. return None
  311. return None
  312. def profile_tombstone_path(profile_home: Path) -> Path:
  313. return profile_home.parent / _DELETED_PROFILES_DIR / profile_home.name
  314. def named_profile_is_deleted(profile_home: str | Path) -> bool:
  315. return profile_tombstone_path(Path(profile_home)).exists()
  316. # A directory under profiles/ is a profile only when something identifies it as one.
  317. # Runtime side-effects (cron heartbeats, log rotation, caches) create dirs that carry
  318. # none of these; a pre-tombstone ghost shell or a stray infrastructure dir must never be
  319. # listed, served, ticked, or seeded with the default install's credentials.
  320. _PROFILE_IDENTITY_MARKERS = ("config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db")
  321. # Canonical named-profile id grammar; every profile-directory gate imports this one object.
  322. PROFILE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
  323. def named_profile_has_identity(profile_home: str | Path) -> bool:
  324. # A dangling symlinked marker (clone/migration leftover) is still an identity claim:
  325. # ``is_file()`` follows links, so it alone would make such a profile unlistable.
  326. home = Path(profile_home)
  327. return any((home / marker).is_file() or (home / marker).is_symlink() for marker in _PROFILE_IDENTITY_MARKERS)
  328. def named_profile_has_servable_identity(profile_home: str | Path) -> bool:
  329. """Stricter than :func:`named_profile_has_identity`: is this dir a profile a host should change
  330. its own posture for?
  331. An EMPTY ``.env`` is all a crashed ``hermes profile create`` leaves behind, and it is enough for
  332. ``named_profile_has_identity``. Listing such a shell is harmless; counting it as a second tenant
  333. is not — it flips the whole host's credential reads fail-closed at the next boot. Every other
  334. marker, and a non-empty or symlinked ``.env``, still counts.
  335. """
  336. home = Path(profile_home)
  337. for marker in _PROFILE_IDENTITY_MARKERS:
  338. path = home / marker
  339. if path.is_symlink():
  340. return True
  341. try:
  342. if path.is_file() and (marker != ".env" or path.stat().st_size > 0):
  343. return True
  344. except OSError:
  345. continue
  346. return False
  347. def named_profile_is_live(profile_home: str | Path) -> bool:
  348. """A resolvable named profile: an existing dir with identity that has not been deleted.
  349. ``-p``/``--profile`` resolution and ``profile_exists`` share this so a stale ghost shell can
  350. never be started as a backend (whose ``ensure_hermes_home`` would rebuild the full tree)."""
  351. home = Path(profile_home)
  352. return home.is_dir() and named_profile_has_identity(home) and not named_profile_is_deleted(home)
  353. def mark_named_profile_deleted(profile_home: str | Path) -> None:
  354. marker = profile_tombstone_path(Path(profile_home))
  355. marker.parent.mkdir(parents=True, exist_ok=True)
  356. marker.write_text("deleted\n", encoding="utf-8")
  357. def clear_named_profile_deleted(profile_home: str | Path) -> None:
  358. profile_tombstone_path(Path(profile_home)).unlink(missing_ok=True)
  359. def assert_named_profile_home_live(path: str | Path) -> None:
  360. """Refuse missing or tombstoned named profile homes."""
  361. home = named_profile_home(path)
  362. if home is not None and (named_profile_is_deleted(home) or not home.exists()):
  363. raise FileNotFoundError(
  364. f"Named profile home does not exist: {home}. "
  365. "Create the profile explicitly before using it."
  366. )
  367. def mkdir_under_hermes_home(path: str | Path) -> Path:
  368. """Create *path*, but never materialize a deleted/missing named profile."""
  369. target = Path(path)
  370. assert_named_profile_home_live(target)
  371. # Lazy so this module still imports alone; hermes_dir_acl (stdlib only) ships beside it in every
  372. # closure that creates home dirs, and a missing copy fails loudly instead of silently skipping the
  373. # elevated grant (tests/pm/test_bootstrap_import_closure.py).
  374. from hermes_dir_acl import make_user_dir
  375. make_user_dir(target, parents=True, exist_ok=True)
  376. return target
  377. def _packaged_dir(env_var: str, default: Path | None, subdir: str) -> Path:
  378. """Resolve a package-manager-relocatable directory.
  379. Order: *env_var* (Nix wrapper / explicit override) → caller ``default`` (source checkout) →
  380. ``<HERMES_HOME>/<subdir>``.
  381. """
  382. override = os.getenv(env_var, "").strip()
  383. return Path(override) if override else default if default is not None else get_hermes_home() / subdir
  384. def get_optional_skills_dir(default: Path | None = None) -> Path:
  385. """Return the optional-skills directory, honoring package-manager wrappers."""
  386. return _packaged_dir("HERMES_OPTIONAL_SKILLS", default, "optional-skills")
  387. def get_optional_mcps_dir(default: Path | None = None) -> Path:
  388. """Return the optional-mcps directory, honoring package-manager wrappers (``HERMES_OPTIONAL_MCPS``)."""
  389. return _packaged_dir("HERMES_OPTIONAL_MCPS", default, "optional-mcps")
  390. def get_bundled_skills_dir(default: Path | None = None) -> Path:
  391. """Return the bundled skills directory, honoring package-manager wrappers (``HERMES_BUNDLED_SKILLS``)."""
  392. return _packaged_dir("HERMES_BUNDLED_SKILLS", default, "skills")
  393. def get_hermes_dir(new_subpath: str, old_name: str, *, home: Path | None = None) -> Path:
  394. """Resolve a Hermes subdirectory, honouring a populated legacy ``<old_name>/`` (no migration).
  395. An empty legacy dir does NOT count (install scaffolds, manual mkdir) so it cannot shadow the new path.
  396. A bare empty ``<old_name>/`` directory does **not** count as "the legacy install is in use" — install
  397. scaffolds, manual ``mkdir`` work, and cleared-then-abandoned locations all create empty stubs that would
  398. otherwise silently shadow real data populated at ``<new_subpath>/``. See #27602 for the pairing-store
  399. regression where a dormant empty ``pairing/`` orphaned approved-user data in ``platforms/pairing/``.
  400. """
  401. home = home or get_hermes_home()
  402. old_path = home / old_name
  403. return old_path if _legacy_path_has_content(old_path) else home / new_subpath
  404. def iter_hermes_node_dirs(home: Path | None = None) -> list[Path]:
  405. """Historical layout for old-updater diagnostics, never runtime selection."""
  406. node_dir = (home or get_hermes_home()) / "node"
  407. return [node_dir, node_dir / "bin"] if sys.platform == "win32" else [node_dir / "bin", node_dir]
  408. _WINDOWS_NODE_SHIMS = {
  409. "npm": ["npm.cmd", "npm.exe", "npm"], "npx": ["npx.cmd", "npx.exe", "npx"], "node": ["node.exe", "node"],
  410. }
  411. def _candidate_node_command_names(command: str) -> list[str]:
  412. base = Path(command).name
  413. if sys.platform != "win32" or "." in base:
  414. return [base]
  415. # Prefer npm.cmd: PowerShell may block npm.ps1 by policy; CreateProcess cannot launch a bare .ps1.
  416. return _WINDOWS_NODE_SHIMS.get(base.lower(), [f"{base}.cmd", f"{base}.exe", base])
  417. def _run_version_probe(argv: list[str], **kwargs):
  418. """Run a hidden ``--version`` probe; ``None`` when it cannot run."""
  419. import subprocess
  420. try:
  421. from hermes_cli._subprocess_compat import windows_hide_flags
  422. return subprocess.run( # noqa: PLW1510 -- forwarding wrapper: callers pass subprocess kwargs via **kwargs (check may arrive through it); an explicit check=False would raise TypeError
  423. argv, capture_output=True, timeout=10, creationflags=windows_hide_flags(), **kwargs,
  424. )
  425. except (OSError, subprocess.TimeoutExpired, ValueError):
  426. return None
  427. def _version_probe_ok(path: str) -> bool:
  428. """True when ``<path> --version`` exits 0 under the Hermes-managed Node PATH."""
  429. result = _run_version_probe([path, "--version"], env=with_hermes_node_path())
  430. return result is not None and result.returncode == 0
  431. # Install tree root (this file lives at <install_root>/hermes_constants.py). Used by secure_parent_dir() to
  432. # skip chmod on the install dir — chmodding it 0700 breaks hermes-user traversal in Docker (UID 10000). See
  433. # #25821, #93050.
  434. _INSTALL_ROOT = Path(__file__).resolve().parent
  435. def _is_executable_file(path: str) -> bool:
  436. """``exists()`` follows symlinks, so a dangling link never spawns a probe."""
  437. return os.path.exists(path) and os.access(path, os.X_OK)
  438. def node_tool_runnable(path: str | None) -> bool:
  439. """True only when *path* is a Node/npm/npx binary that actually runs (``--version`` probe)."""
  440. if not path:
  441. return False
  442. present = Path(path).is_file() if sys.platform == "win32" else _is_executable_file(path)
  443. return present and _version_probe_ok(path)
  444. def hermes_managed_node_tree_present(home: Path | None = None) -> bool:
  445. """Read-only legacy artifact detection for already-running old updaters."""
  446. names = [n for c in ("node", "npm", "npx") for n in _candidate_node_command_names(c)]
  447. return any((directory / name).is_file() for directory in iter_hermes_node_dirs(home) for name in names)
  448. def find_node_executable(command: str) -> str | None:
  449. """Read PM's selected Node/npm/npx; ``None`` when PM has not installed it.
  450. Never falls back to the user's PATH copy (callers ``pm.ensure`` on ``None``):
  451. mixing toolchains breaks native-addon ABIs and npm caches. Explicit
  452. executable paths remain caller-owned. Discovery never installs, probes,
  453. repairs, or activates the retired ``HERMES_HOME/node`` layout.
  454. """
  455. command = str(command)
  456. if any(sep in command for sep in ("/", "\\")):
  457. if sys.platform == "win32":
  458. return command if Path(command).is_file() else None
  459. return shutil.which(command)
  460. base = command.lower()
  461. for suffix in (".cmd", ".exe", ".ps1"):
  462. base = base.removesuffix(suffix)
  463. package_name = {"node": "node", "npm": "npm", "npx": "npm"}.get(base)
  464. if package_name is not None:
  465. from pm import installed_package
  466. installed = installed_package(package_name)
  467. if installed is None or installed.binary is None:
  468. return None
  469. if base != "npx":
  470. return str(installed.binary)
  471. for name in _candidate_node_command_names("npx"):
  472. candidate = installed.binary.parent / name
  473. if candidate.is_file():
  474. return str(candidate)
  475. return None
  476. if sys.platform != "win32":
  477. return shutil.which(command)
  478. directories = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d]
  479. for name in _candidate_node_command_names(command):
  480. for directory in directories:
  481. candidate = Path(directory) / name
  482. if candidate.is_file():
  483. return str(candidate)
  484. return None
  485. def with_hermes_node_path(env: dict[str, str] | None = None) -> dict[str, str]:
  486. """Compose installed PM npm and its Node dependency without provisioning."""
  487. from pm import env_for
  488. return env_for("npm", base_env=env)
  489. def _legacy_path_has_content(path: Path) -> bool:
  490. """True iff *path* is a non-directory file or a populated directory.
  491. Non-not-found ``OSError`` means "assume occupied" (never orphan legacy data). Symlinks are
  492. judged on their target; a dangling one does NOT count.
  493. """
  494. try:
  495. st = path.lstat()
  496. if stat.S_ISLNK(st.st_mode):
  497. st = path.stat() # judge a symlink on its target; dangling → FileNotFoundError
  498. except FileNotFoundError:
  499. return False
  500. except OSError: # e.g. PermissionError on a parent: assume occupied
  501. return True
  502. if not stat.S_ISDIR(st.st_mode):
  503. return True
  504. try:
  505. next(path.iterdir())
  506. except StopIteration:
  507. return False
  508. except OSError:
  509. pass
  510. return True
  511. def display_hermes_home(home: Path | None = None) -> str:
  512. """User-facing ``~/`` display string for HERMES_HOME (``~/.hermes/profiles/coder``).
  513. ``home`` overrides the lookup for callers that run before the CLI has applied the sticky
  514. ``active_profile`` (``get_hermes_home()`` would emit the wrong-profile fallback warning there).
  515. """
  516. if home is None:
  517. home = get_hermes_home()
  518. try: # as_posix(): str() on Windows yields chimeras like ~/AppData\Local\hermes/skills/
  519. return "~/" + home.relative_to(Path.home()).as_posix()
  520. except ValueError:
  521. return str(home)
  522. def profile_cli_selector() -> str:
  523. """``-p <name> `` (trailing space) pinning copy-pasteable ``hermes ...`` guidance to the
  524. active NAMED profile, else ``""``: a bare ``hermes`` follows the sticky ``active_profile``
  525. file, which can name a different database than the one that failed (#105887). A custom
  526. home outside the profile tree has no selector (only HERMES_HOME names it)."""
  527. name = profile_name_for_home(get_hermes_home())
  528. return f"-p {name} " if name and name != "default" else ""
  529. def secure_parent_dir(path: Path) -> None:
  530. """Chmod ``0o700`` on *path*'s parent, refusing ``/`` and top-level dirs (misresolved HERMES_HOME)."""
  531. parent = path.parent.resolve()
  532. if parent == Path("/") or len(parent.parts) < 3:
  533. return
  534. # Refuse the install tree: chmod 0700 breaks hermes-user traversal in Docker (UID 10000).
  535. # A credential file here means HERMES_HOME misresolved; surface it (caused production lockouts).
  536. # See #25821, #93050.
  537. if parent == _INSTALL_ROOT or _INSTALL_ROOT in parent.parents:
  538. import logging
  539. logging.getLogger(__name__).warning(
  540. "Not restricting permissions on %s: it is inside the "
  541. "hermes-agent install directory (%s). Credential files are "
  542. "normally stored under the hermes home directory instead.", parent, _INSTALL_ROOT,
  543. )
  544. return
  545. with contextlib.suppress(OSError):
  546. os.chmod(parent, 0o700)
  547. def _norm_home_path(path: str | None) -> str:
  548. """Return a comparable absolute path string, or ``""`` for empty input."""
  549. raw = (path or "").strip()
  550. if not raw:
  551. return ""
  552. try:
  553. return os.path.normcase(os.path.abspath(os.path.expanduser(raw)))
  554. except Exception:
  555. return os.path.normcase(raw)
  556. def _profile_home_path(env: dict[str, str] | None = None) -> str | None:
  557. """Return ``{HERMES_HOME}/home`` when the profile-home directory exists."""
  558. hermes_home = get_hermes_home_override() or (env or {}).get("HERMES_HOME") or os.getenv("HERMES_HOME")
  559. if not hermes_home:
  560. return None
  561. profile_home = str(_expand_hermes_home(hermes_home) / "home")
  562. return profile_home if os.path.isdir(profile_home) else None
  563. def _is_profile_home(candidate: str | None, profile_home: str | None) -> bool:
  564. return bool(candidate and profile_home and _norm_home_path(candidate) == _norm_home_path(profile_home))
  565. def _env_get(env: dict[str, str], key: str, default: str = "") -> str:
  566. """Stripped *key* from *env*, falling back to the process environment."""
  567. return str(env.get(key) or os.getenv(key, default)).strip()
  568. def _iter_real_home_candidates(env: dict[str, str] | None = None) -> list[str]:
  569. """Return likely OS-user home candidates in trust order."""
  570. env = env or {}
  571. candidates = [_env_get(env, "HERMES_REAL_HOME"), _env_get(env, "HOME")]
  572. with contextlib.suppress(Exception):
  573. import pwd
  574. candidates.append(pwd.getpwuid(os.getuid()).pw_dir.strip()) # windows-footgun: ok — POSIX-only module inside try/except
  575. candidates.append(_env_get(env, "USERPROFILE"))
  576. drive, path = _env_get(env, "HOMEDRIVE"), _env_get(env, "HOMEPATH")
  577. if drive and path:
  578. candidates.append(f"{drive}{path}" if path.startswith(("\\", "/")) else os.path.join(drive, path))
  579. expanded = os.path.expanduser("~")
  580. if expanded != "~":
  581. candidates.append(expanded)
  582. return [c for c in candidates if c]
  583. def get_real_home(env: dict[str, str] | None = None) -> str:
  584. """The OS user's real home, avoiding the Hermes profile HOME.
  585. ``HOME`` belongs to the OS account and external CLIs keeping credentials under ``~``; a parent
  586. already running with ``HOME={HERMES_HOME}/home`` is repaired back when possible.
  587. """
  588. profile_home = _profile_home_path(env)
  589. seen: set[str] = set()
  590. for candidate in _iter_real_home_candidates(env):
  591. key = _norm_home_path(candidate)
  592. if not key or key in seen:
  593. continue
  594. seen.add(key)
  595. if not _is_profile_home(candidate, profile_home):
  596. return candidate
  597. import tempfile
  598. try:
  599. return tempfile.gettempdir()
  600. except (RuntimeError, OSError):
  601. # no HOME/USERPROFILE at all (env-less child on Windows): tempfile cannot expand ``~``
  602. return "/tmp" # no-tmp: ok — last-resort fallback for an env with no home; not a write target we choose
  603. _HOME_MODE_ALIASES = {"isolated": "profile", "profile_home": "profile", "profile-home": "profile",
  604. "host": "real", "user": "real", "real_home": "real", "real-home": "real"}
  605. def get_subprocess_home(env: dict[str, str] | None = None) -> str | None:
  606. """Subprocess ``HOME`` override, or ``None``.
  607. ``auto``: hosts keep real HOME (repairing a profile-home parent), containers use
  608. ``{HERMES_HOME}/home``; ``real``: always real HOME; ``profile``: always the profile home.
  609. """
  610. env = env or {}
  611. profile_home = _profile_home_path(env)
  612. mode = _env_get(env, "TERMINAL_HOME_MODE", "auto").lower() or "auto"
  613. mode = _HOME_MODE_ALIASES.get(mode, mode)
  614. if mode == "profile":
  615. return profile_home
  616. real_home = get_real_home(env)
  617. current_home = _env_get(env, "HOME")
  618. repaired = real_home if _norm_home_path(real_home) != _norm_home_path(current_home) else None
  619. if mode == "real":
  620. return repaired
  621. if profile_home and is_container():
  622. return profile_home
  623. if not current_home or _is_profile_home(current_home, profile_home):
  624. return repaired
  625. return None
  626. def apply_subprocess_home_env(env: MutableMapping[str, str]) -> None:
  627. """Apply Hermes' subprocess HOME contract to *env* in-place: ``HOME``/``HERMES_REAL_HOME``
  628. per the home mode, and the temp vars re-pointed at ``env["HERMES_HOME"]``'s scratch dir."""
  629. real_home = get_real_home(env)
  630. if real_home:
  631. env["HERMES_REAL_HOME"] = real_home
  632. home = get_subprocess_home(env)
  633. if home:
  634. env["HOME"] = home
  635. apply_scratch_tmp_env(env)
  636. # --- Scratch dir: Hermes' own temp space, never the system /tmp ---
  637. # System temp is tmpfs on most Linux distros and containers, so browser profiles, PTY probes,
  638. # download spools and every ``tempfile.mkdtemp()`` a Hermes-launched script performs eat RAM
  639. # and vanish on reboot. ``HERMES_HOME/cache/scratch`` is real storage with an IDLE retention:
  640. # an entry lives while anything inside it is still being written and goes 24h after the last
  641. # write anywhere in its subtree. A fixed age was wrong both ways — a directory's own mtime only
  642. # moves when a direct child is added or removed, so a lane writing deep inside a tree looked
  643. # untouched and lost its worktree at the deadline, while finished trees (a 7 GB clone with its
  644. # own venv per campaign lane) sat for three days and filled the disk.
  645. SCRATCH_TMP_ENV_VARS = ("TMPDIR", "TMP", "TEMP")
  646. SCRATCH_DIR_MARKER_ENV = "HERMES_SCRATCH_DIR"
  647. SCRATCH_MAX_IDLE_HOURS = 24
  648. _SCRATCH_PRUNE_STAMP = ".last_prune"
  649. _SCRATCH_PRUNE_INTERVAL_SECONDS = 3600
  650. _scratch_pruned_once = False
  651. # AF_UNIX socket paths cap at 104 bytes (macOS) / 108 (Linux). Chrome appends
  652. # ``com.google.Chrome.XXXXXX/SingletonSocket`` (~45) and the code kernel
  653. # ``hermes_rpc_<32 hex>.sock`` (~49) to the temp root, so a root longer than this budget
  654. # makes the bind fail (Chrome: "Socket path too long" at startup).
  655. SOCKET_TMPDIR_MAX_LEN = 50
  656. def socket_safe_tmpdir() -> str:
  657. """Temp root short enough for AF_UNIX sockets. The scratch dir usually fits; macOS
  658. ``TMPDIR`` never does and a deep profile home may not, so those fall back to the OS
  659. default root for sockets only (everything else stays in the scratch dir)."""
  660. import tempfile
  661. if sys.platform == "darwin":
  662. return "/tmp" # no-tmp: ok — AF_UNIX 104-byte socket path limit on darwin
  663. candidate = tempfile.gettempdir()
  664. if len(candidate) <= SOCKET_TMPDIR_MAX_LEN or not os.path.isdir("/tmp"): # no-tmp: ok — probe, not a write target
  665. return candidate
  666. return "/tmp" # no-tmp: ok — AF_UNIX 108-byte socket path limit on Linux
  667. # ---- Managed mode (NixOS declarative config) ----
  668. # Canonical home of "is this install package-manager managed": ``hermes_cli.config`` re-exports
  669. # these, and :func:`apply_secure_dir_policy` below reads them. Lives here because constants
  670. # must stay import-safe from the CLI.
  671. _MANAGED_TRUE_VALUES = ("true", "1", "yes")
  672. # Only the NixOS module ever wrote a bare "true" or an empty marker.
  673. _LEGACY_MANAGED_SYSTEM = "nixos"
  674. # Homebrew is no longer a supported distribution: these markers fall through to git/unknown
  675. # detection instead of blocking config writes.
  676. _IGNORED_MANAGED_VALUES = frozenset({"brew", "homebrew"})
  677. # Explicit opt-out (``HERMES_MANAGED=false``): without this a bool-shaped value became a package
  678. # manager literally named "false" and is_managed() blocked `hermes update` (#12864).
  679. _MANAGED_FALSE_VALUES = frozenset({"false", "0", "no", "off"})
  680. def get_managed_system(home: str | Path | None = None) -> str | None:
  681. """Return the package manager owning this install, if any.
  682. Signals: HERMES_MANAGED env var (systemd service) or a ``.managed`` marker file in
  683. HERMES_HOME (NixOS activation script — interactive shells don't see the service env).
  684. An unreadable or empty marker still counts as managed (the legacy NixOS shape).
  685. ``home`` names the home whose marker file is read, for callers that already resolved it
  686. (:func:`get_scratch_dir` at boot, before ``--profile`` re-homes the process).
  687. Defaults to the effective home."""
  688. marker = os.getenv("HERMES_MANAGED", "").strip().lower() or None
  689. managed_marker = (Path(home) if home is not None else get_hermes_home()) / ".managed"
  690. if marker is None and managed_marker.exists():
  691. try:
  692. marker = managed_marker.read_text(encoding="utf-8", errors="replace").strip().lower()
  693. except OSError:
  694. marker = ""
  695. if marker is None or marker in _IGNORED_MANAGED_VALUES or marker in _MANAGED_FALSE_VALUES:
  696. return None
  697. if marker == "" or marker in _MANAGED_TRUE_VALUES:
  698. return _LEGACY_MANAGED_SYSTEM
  699. return marker
  700. def _container_or_chmod_skipped() -> bool:
  701. """Container/chmod-skip detection: the ``HERMES_CONTAINER``/``HERMES_SKIP_CHMOD`` operator
  702. overrides on top of the canonical :func:`_detect_container` signals (same breadth as
  703. :func:`is_container` — Docker/Podman/LXC/Kubernetes, cgroup and root-mountinfo). The cached
  704. :func:`is_container` itself is deliberately avoided: it ignores these env overrides and is
  705. computed only once per process, so tests could not flip it. Volume-mounted config is not
  706. forced to owner-only in containers: gateway and dashboard may run as different UIDs, or
  707. the mount itself needs broader permissions."""
  708. if os.environ.get("HERMES_CONTAINER") or os.environ.get("HERMES_SKIP_CHMOD"):
  709. return True
  710. return _detect_container()
  711. def _resolve_hermes_uid_gid() -> tuple[int | None, int | None]:
  712. """Read HERMES_UID / HERMES_GID (set by Docker deployments); (None, None) if unset/invalid/Windows.
  713. The entrypoint chowns HERMES_HOME once, but subdirs created at runtime (``profiles/<name>/``)
  714. need the same chown or they land root:root and block later uid-mapped workers.
  715. Docker containers running Hermes commonly set these to map the in-container user to a host user so
  716. volume-mounted state files end up with the right ownership. See #34107.
  717. """
  718. if sys.platform == "win32":
  719. return None, None
  720. def _env_int(name: str) -> int | None:
  721. try:
  722. return int(os.environ.get(name, "").strip() or None)
  723. except (TypeError, ValueError):
  724. return None
  725. return _env_int("HERMES_UID"), _env_int("HERMES_GID")
  726. def _chown_to_hermes_uid(path) -> None:
  727. """Chown ``path`` to ``HERMES_UID:HERMES_GID`` when set; EPERM/ENOENT are non-fatal (the
  728. entrypoint's startup chown -R fixes ownership on the next restart).
  729. Used by :func:`apply_secure_dir_policy` to keep ownership consistent across all directories
  730. created by ``ensure_hermes_home`` on Docker deployments. See #34107.
  731. """
  732. uid, gid = _resolve_hermes_uid_gid()
  733. if uid is None and gid is None:
  734. return
  735. try:
  736. os.chown(path, uid if uid is not None else -1, gid if gid is not None else -1)
  737. except (OSError, AttributeError, NotImplementedError):
  738. pass
  739. def apply_secure_dir_policy(path, *, home: str | Path | None = None) -> None:
  740. """Apply the canonical Hermes home-directory permission policy to *path*.
  741. Owner-only ``0700`` by default, but the operator's explicit and managed sharing choices
  742. win (#117347): managed installs are left exactly as the package manager / activation
  743. script set them (#77579); in a container only an explicit ``HERMES_HOME_MODE`` is applied
  744. (a bind-mounted data dir is often shared with sibling containers, #10757); elsewhere
  745. ``HERMES_HOME_MODE`` (e.g. ``0701``, ``2770``) is passed to the host's ``chmod``. Special
  746. bits may be cleared by the host filesystem (macOS commonly clears setgid on directories
  747. whose group the caller does not belong to). ``HERMES_UID`` / ``HERMES_GID`` ownership is
  748. applied when those env vars are set (#34107).
  749. ``home`` (keyword-only: both arguments are path-likes) names the home whose managed-mode
  750. marker is read, for callers that already resolved it; without it the effective home is
  751. consulted.
  752. Import-safe twin of ``hermes_cli.config._secure_dir`` (which delegates here), so callers
  753. outside the CLI package — like :func:`get_scratch_dir` — share one policy implementation.
  754. """
  755. if get_managed_system(home) is not None:
  756. return
  757. explicit_mode = os.environ.get("HERMES_HOME_MODE", "").strip()
  758. if _container_or_chmod_skipped() and not explicit_mode:
  759. _chown_to_hermes_uid(path)
  760. return
  761. try:
  762. mode = int(explicit_mode or "700", 8)
  763. except ValueError:
  764. mode = 0o700
  765. try:
  766. os.chmod(path, mode)
  767. except (OSError, NotImplementedError):
  768. pass
  769. _chown_to_hermes_uid(path)
  770. def get_scratch_dir(home: str | Path | None = None, *, prune: bool = True) -> Path:
  771. """``<home>/cache/scratch`` (created, owner-only); *home* defaults to the active Hermes home.
  772. Every Hermes process and child gets ``TMPDIR``/``TMP``/``TEMP`` pointed here at boot (see
  773. :func:`export_scratch_tmp_env`), so ``tempfile`` defaults land here without call sites
  774. knowing. Entries idle for ``SCRATCH_MAX_IDLE_HOURS`` are pruned at most once per process
  775. and once per hour across processes (stamp file), so a fan-out of children stays cheap.
  776. The pass itself runs in a detached child process (``hermes_constants_scratch_detach``): the
  777. directory is created and permissioned before this returns, no caller (the boot hook
  778. included) waits on the idle scan or the ``rmtree`` of a multi-GB entry, and the pass still
  779. finishes when the caller is a ``hermes`` command that exits a moment later.
  780. Permissions follow :func:`apply_secure_dir_policy`, so an explicit ``HERMES_HOME_MODE`` or
  781. a managed/shared home is honored instead of a blanket ``0700`` (#117347).
  782. """
  783. base = Path(home) if home is not None else get_hermes_home()
  784. scratch = base / "cache" / "scratch"
  785. try:
  786. scratch.mkdir(parents=True, exist_ok=True)
  787. if sys.platform != "win32":
  788. # The caller's home decides the policy: re-reading the effective home here would
  789. # warn about a profile the CLI has not switched to yet (boot scratch setup).
  790. apply_secure_dir_policy(scratch, home=base)
  791. except OSError:
  792. pass
  793. if prune:
  794. _prune_scratch_dir_once(scratch)
  795. return scratch
  796. def prune_scratch_dir(scratch: Path | None = None, max_idle_hours: float = SCRATCH_MAX_IDLE_HOURS) -> int:
  797. """Delete top-level scratch entries with no write anywhere in their subtree for
  798. *max_idle_hours*, reaping processes and git worktree registrations rooted in them
  799. first (``hermes_constants_scratch``); return the count removed. Each removal, each
  800. kill and each entry rescued mid-prune is recorded in ``<home>/logs/scratch-prune.log``
  801. (*scratch* is ``<home>/cache/scratch``)."""
  802. from hermes_constants_scratch import prune_idle_entries
  803. root = scratch if scratch is not None else get_scratch_dir(prune=False)
  804. log_file = root.parent.parent / "logs" / "scratch-prune.log"
  805. return prune_idle_entries(root, max_idle_hours, frozenset({_SCRATCH_PRUNE_STAMP}), log_file)
  806. def _prune_scratch_dir_once(scratch: Path) -> None:
  807. global _scratch_pruned_once
  808. if _scratch_pruned_once:
  809. return
  810. _scratch_pruned_once = True
  811. import time
  812. stamp = scratch / _SCRATCH_PRUNE_STAMP
  813. try:
  814. if time.time() - stamp.stat().st_mtime < _SCRATCH_PRUNE_INTERVAL_SECONDS:
  815. return
  816. except OSError:
  817. pass
  818. with contextlib.suppress(Exception):
  819. stamp.touch()
  820. from hermes_constants_scratch_detach import spawn_prune
  821. spawn_prune(scratch)
  822. def scratch_dir_usage_bytes(scratch: Path | None = None) -> int:
  823. """Total bytes under the scratch dir (for ``hermes doctor``); 0 when unreadable."""
  824. root = scratch if scratch is not None else get_scratch_dir(prune=False)
  825. total = 0
  826. for dirpath, _dirnames, filenames in os.walk(root, onerror=lambda _e: None):
  827. for name in filenames:
  828. with contextlib.suppress(OSError):
  829. total += os.lstat(os.path.join(dirpath, name)).st_size
  830. return total
  831. def apply_scratch_tmp_env(env: MutableMapping[str, str]) -> bool:
  832. """Point ``TMPDIR``/``TMP``/``TEMP`` in *env* at the scratch dir of ``env["HERMES_HOME"]``.
  833. A temp var the user (or the OS: macOS ``/var/folders``, Windows ``%TEMP%``) set is
  834. respected and nothing changes. A value Hermes itself exported earlier — recognisable
  835. because it equals ``HERMES_SCRATCH_DIR`` — is re-derived, so a child running under another
  836. profile's home gets that home's scratch dir rather than its parent's. Returns True when
  837. the vars were (re)written.
  838. """
  839. ours = env.get(SCRATCH_DIR_MARKER_ENV, "")
  840. for key in SCRATCH_TMP_ENV_VARS:
  841. value = env.get(key, "").strip()
  842. if value and value != ours:
  843. return False
  844. home = env.get("HERMES_HOME", "").strip()
  845. try:
  846. scratch = str(get_scratch_dir(_expand_hermes_home(home) if home else get_process_hermes_home()))
  847. except (RuntimeError, OSError):
  848. # No HERMES_HOME and no resolvable user home (a child env built from nothing on
  849. # Windows): there is no scratch dir to point at; the child keeps the OS default.
  850. return False
  851. for key in SCRATCH_TMP_ENV_VARS:
  852. env[key] = scratch
  853. env[SCRATCH_DIR_MARKER_ENV] = scratch
  854. return True
  855. def export_scratch_tmp_env() -> bool:
  856. """Boot hook: apply :func:`apply_scratch_tmp_env` to this process and reset ``tempfile``'s
  857. cached default so ``tempfile.gettempdir()`` follows. Call again after anything that
  858. re-homes the process (``--profile`` resolution); a user-set temp var is never overridden."""
  859. changed = apply_scratch_tmp_env(os.environ)
  860. if changed:
  861. import tempfile
  862. tempfile.tempdir = None
  863. return changed
  864. VALID_REASONING_EFFORTS = ("minimal", "low", "medium", "high", "xhigh", "max", "ultra")
  865. def parse_reasoning_effort(effort) -> dict | None:
  866. """Parse a reasoning effort level into a config dict.
  867. ``None`` for empty/unrecognized input (caller uses the default); ``{"enabled": False}`` for
  868. "none"/"false"/"disabled"/YAML False — ``reasoning_effort: false`` must mean disabled.
  869. The dict form ``{"enabled": true, "effort": "<level>"}`` passes ``effort`` through verbatim so
  870. providers with bespoke thinking tiers (``fast``/``thinking`` relays) can be asked for their real
  871. level; bare strings stay strict so a typo like ``hgih`` never reaches the wire. The wire layer
  872. already tolerates unknown names (``agent.reasoning_effort.clamp_effort``).
  873. """
  874. if effort is None or effort is True:
  875. return None
  876. if isinstance(effort, dict):
  877. if effort.get("enabled", True) is False:
  878. return {"enabled": False}
  879. # ``or ""``: a falsy effort (0/False) is "no level", never the string "0" on the wire.
  880. level = str(effort.get("effort") or "").strip()
  881. return {"enabled": True, "effort": level} if level else None
  882. effort = str(effort).strip().lower() # False -> "false" -> disabled; "" matches neither set
  883. if effort in {"none", "false", "disabled"}:
  884. return {"enabled": False}
  885. if effort in VALID_REASONING_EFFORTS:
  886. return {"enabled": True, "effort": effort}
  887. return None
  888. def _canonical_model_variants(model: str) -> list[str]:
  889. """Spelling variants for tolerant override matching, exact first, deduped in order.
  890. Dot/dash recovery runs on EACH base form so ``x-4.5``, ``x-4-5`` and ``x.4.5`` share one variant set.
  891. """
  892. _dash_to_dot = lambda s: re.sub(r'(\d)-(\d)', r'\1.\2', s)
  893. _dot_to_dash = lambda s: re.sub(r'(\d)\.(\d)', r'\1-\2', s)
  894. seen: set[str] = set()
  895. variants: list[str] = []
  896. def _add(*values):
  897. for v in values:
  898. if v and v not in seen:
  899. seen.add(v)
  900. variants.append(v)
  901. def _add_with_derivatives(s):
  902. dashed, dotted = s.replace('.', '-'), s.replace('-', '.')
  903. _add(s, dashed, dotted, _dash_to_dot(s), _dot_to_dash(s), _dash_to_dot(dashed), _dot_to_dash(dotted))
  904. _add_with_derivatives(model)
  905. parts = model.split('/')
  906. if len(parts) >= 2: # bare model (strip provider/aggregator prefix)
  907. _add_with_derivatives(parts[-1])
  908. if len(parts) >= 3: # strip aggregator only: "openrouter/anthropic/x" → "anthropic/x"
  909. _add_with_derivatives('/'.join(parts[1:]))
  910. known_providers = (
  911. 'anthropic', 'openai', 'google', 'openrouter', 'groq', 'mistral',
  912. 'xai', 'cohere', 'perplexity', 'together', 'fireworks', 'deepseek',
  913. )
  914. for v in [v for v in variants if '/' not in v]:
  915. _add(*(f"{provider}/{v}" for provider in known_providers))
  916. known_aggregators = ('openrouter', 'opencode', 'fireworks', 'groq', 'together')
  917. for v in [v for v in variants if v.count('/') == 1]:
  918. _add(*(f"{agg}/{v}" for agg in known_aggregators))
  919. return variants
  920. def resolve_per_model_reasoning_effort(model: str, overrides: dict | None) -> dict | None:
  921. """Per-model reasoning_effort override with spelling tolerance; first non-None parse wins.
  922. Order: exact → dots↔dashes → provider stripped → aggregator stripped → known prefixes added →
  923. reverse lookup of prefixed keys whose stripped forms match (custom provider slugs are not
  924. enumerable, so a key like ``ollama-local/qwen3.6:27b`` must still match the bare
  925. ``qwen3.6:27b`` model string a fallback swap feeds after stripping the prefix).
  926. """
  927. if not overrides or not isinstance(overrides, dict) or not model:
  928. return None
  929. variants = _canonical_model_variants(model)
  930. for variant in variants:
  931. if variant in overrides:
  932. result = parse_reasoning_effort(overrides[variant])
  933. if result is not None:
  934. return result
  935. # Reverse lookup: the key may carry a custom-provider prefix the model string lost
  936. # (fallback entries and custom-provider resolution feed the bare slug, while the
  937. # documented key spelling keeps the ``provider/model`` form). Direct and variant
  938. # matches above still win, so provider-qualified keys stay most specific.
  939. variant_set = set(variants)
  940. for key, raw in overrides.items():
  941. if not isinstance(key, str) or "/" not in key:
  942. continue
  943. parts = key.split("/")
  944. key_forms = _canonical_model_variants(parts[-1])
  945. if len(parts) >= 3:
  946. key_forms += _canonical_model_variants("/".join(parts[1:]))
  947. if any(form in variant_set for form in key_forms):
  948. result = parse_reasoning_effort(raw)
  949. if result is not None:
  950. return result
  951. return None
  952. def resolve_per_model_provider_routing(model: str, models: dict | None) -> dict:
  953. """``provider_routing.models.<id>`` entry for *model*, spelling-tolerant like
  954. ``reasoning_overrides``; ``{}`` when none matches. Only the keys a user sets per model
  955. are returned so unset ones fall through to the flat ``provider_routing`` values."""
  956. if not model or not isinstance(models, dict):
  957. return {}
  958. for variant in _canonical_model_variants(model):
  959. entry = models.get(variant)
  960. if isinstance(entry, dict):
  961. return entry
  962. return {}
  963. def resolve_reasoning_config(cfg: dict | None, model: str = "") -> dict | None:
  964. """Effective reasoning config for *model*: per-model override, then global ``agent.reasoning_effort``.
  965. Single chokepoint for every surface (CLI, gateway, TUI, cron, ``/model``, fallback activation).
  966. """
  967. cfg = cfg if isinstance(cfg, dict) else {}
  968. agent_cfg = cfg.get("agent") if isinstance(cfg.get("agent"), dict) else {}
  969. if not model:
  970. model_cfg = cfg.get("model")
  971. if isinstance(model_cfg, dict):
  972. model_cfg = model_cfg.get("default") or model_cfg.get("model") or ""
  973. model = model_cfg.strip() if isinstance(model_cfg, str) else ""
  974. per_model = resolve_per_model_reasoning_effort(model, agent_cfg.get("reasoning_overrides") or {})
  975. if per_model is not None:
  976. return per_model
  977. # Keep the raw value: ``or ""`` would turn a YAML False into "" and silently re-enable thinking.
  978. effort = agent_cfg.get("reasoning_effort", "")
  979. result = parse_reasoning_effort(effort)
  980. if effort and str(effort).strip() and result is None:
  981. import logging
  982. logging.getLogger(__name__).warning("Unknown reasoning_effort '%s', using default (medium)", effort)
  983. return result
  984. def is_termux() -> bool:
  985. """Delegate Termux detection without making the bootstrap constants module depend on the full package."""
  986. from hermes_platform.host.runtime import is_termux as detect
  987. return detect()
  988. def is_wsl() -> bool:
  989. """Delegate WSL detection without making the bootstrap constants module depend on the full package."""
  990. from hermes_platform.host.runtime import is_wsl as detect
  991. return detect()
  992. def is_container() -> bool:
  993. """Delegate container detection without making the bootstrap constants module depend on the full package."""
  994. from hermes_platform.host.runtime import is_container as detect
  995. return detect()
  996. def _detect_container() -> bool:
  997. """Keep the historical test seam while delegating canonical detection."""
  998. from hermes_platform.host.runtime import _detect_container as detect
  999. return detect()
  1000. def windows_path_to_wsl(path: str) -> str | None:
  1001. """Convert a Windows drive path (``C:\\...``) to its ``/mnt/<drive>/...`` form."""
  1002. match = re.match(r"^([A-Za-z]):[\\/](.*)$", str(path or "").strip())
  1003. return f"/mnt/{match.group(1).lower()}/{match.group(2).replace(chr(92), '/')}" if match else None
  1004. def wsl_unc_path_to_posix(path: str) -> str | None:
  1005. """Convert a ``\\\\wsl.localhost\\<distro>\\...`` (or legacy ``\\\\wsl$``) UNC path to POSIX."""
  1006. normalized = str(path or "").strip().replace("/", "\\")
  1007. match = re.match(r"^\\\\wsl(?:\.localhost|\$)\\[^\\]+\\(.*)$", normalized, re.IGNORECASE)
  1008. return "/" + match.group(1).replace("\\", "/") if match else None
  1009. def translate_cwd_for_wsl_backend(cwd: str) -> str:
  1010. """Map a Windows-host cwd (drive path or ``\\\\wsl.localhost\\`` UNC) to POSIX when Hermes runs in WSL.
  1011. No-op off WSL and for paths already POSIX.
  1012. """
  1013. if not is_wsl():
  1014. return cwd
  1015. for translator in (wsl_unc_path_to_posix, windows_path_to_wsl):
  1016. translated = translator(cwd)
  1017. if translated is not None:
  1018. return translated
  1019. return cwd
  1020. def get_config_path() -> Path:
  1021. """Return the path to ``config.yaml`` under HERMES_HOME."""
  1022. return get_hermes_home() / "config.yaml"
  1023. def get_skills_dir() -> Path:
  1024. """Return the path to the skills directory under HERMES_HOME."""
  1025. return get_hermes_home() / "skills"
  1026. def get_env_path() -> Path:
  1027. """Return the path to the ``.env`` file under HERMES_HOME."""
  1028. return get_hermes_home() / ".env"
  1029. def apply_ipv4_preference(force: bool = False) -> None:
  1030. """Monkey-patch ``socket.getaddrinfo`` to prefer IPv4 when *force* is True.
  1031. Broken-IPv6 hosts hang on AAAA for the full TCP timeout; ``AF_UNSPEC`` resolves as ``AF_INET``,
  1032. falling back to full resolution when no A record exists (pure-IPv6 hosts still work).
  1033. """
  1034. if not force:
  1035. return
  1036. import socket
  1037. if getattr(socket.getaddrinfo, "_hermes_ipv4_patched", False):
  1038. return
  1039. _original_getaddrinfo = socket.getaddrinfo
  1040. def _ipv4_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  1041. if family == 0: # AF_UNSPEC — caller didn't request a specific family
  1042. try:
  1043. return _original_getaddrinfo(host, port, socket.AF_INET, type, proto, flags)
  1044. except socket.gaierror: # no A record — pure-IPv6 host
  1045. return _original_getaddrinfo(host, port, family, type, proto, flags)
  1046. return _original_getaddrinfo(host, port, family, type, proto, flags)
  1047. _ipv4_getaddrinfo._hermes_ipv4_patched = True # type: ignore[attr-defined]
  1048. socket.getaddrinfo = _ipv4_getaddrinfo # type: ignore[assignment]
  1049. PARTIAL_STREAM_STUB_ID = "partial-stream-stub"
  1050. FINISH_REASON_LENGTH = "length"
  1051. OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
  1052. OPENROUTER_MODELS_URL = f"{OPENROUTER_BASE_URL}/models"
  1053. # OpenRouter request-time routing variants (docs: guides/routing/model-variants).
  1054. # These suffixes are per-request routing modifiers valid on ANY model id —
  1055. # ":nitro" sorts the endpoint pool by throughput and admits priority-tier
  1056. # endpoints, ":floor" sorts by price and admits flex-tier endpoints, ":exacto"
  1057. # applies quality-first provider sorting, ":online" attaches the web plugin.
  1058. # They are never separate catalog entries: /models lists only the base id, so
  1059. # every catalog lookup must key on the BASE while the suffixed id stays on the
  1060. # wire.
  1061. # NOT in this set: ":free", ":batch", ":thinking", ":extended" — those ARE
  1062. # distinct catalog SKUs with their own /models entries (and their own context
  1063. # windows), so stripping them would resolve the wrong window.
  1064. OPENROUTER_VARIANT_SUFFIXES: frozenset[str] = frozenset(
  1065. {"nitro", "floor", "exacto", "online"}
  1066. )
  1067. def openrouter_variant_base(model_id: str) -> str | None:
  1068. """Return the base model id when ``model_id`` carries a recognized
  1069. OpenRouter routing-variant suffix (e.g. ``x-ai/grok-4:nitro`` →
  1070. ``x-ai/grok-4``), else ``None``.
  1071. Lives here rather than in ``hermes_cli.models`` so the metadata layer
  1072. (``agent.model_metadata``) can share one definition without importing the
  1073. CLI — this module is dependency-free by contract.
  1074. >>> openrouter_variant_base("x-ai/grok-4:nitro")
  1075. 'x-ai/grok-4'
  1076. >>> openrouter_variant_base("x-ai/grok-4:free") is None
  1077. True
  1078. >>> openrouter_variant_base("x-ai/grok-4") is None
  1079. True
  1080. """
  1081. base, sep, suffix = (model_id or "").rpartition(":")
  1082. if not sep or not base:
  1083. return None
  1084. if suffix.lower() in OPENROUTER_VARIANT_SUFFIXES:
  1085. return base
  1086. return None
  1087. AI_GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh/v1"
  1088. def venv_bin_dir(venv_dir, *, windows: bool | None = None) -> Path:
  1089. """Frozen updater surface: pre-PM updaters import this name; pm.environments owns it."""
  1090. from pm.environments import venv_bin_dir as resolve
  1091. return resolve(venv_dir, windows=windows)
  1092. def project_venv_dir(project_root) -> Path | None:
  1093. """The project's ``venv`` or ``.venv`` dir when one exists (``uv venv`` defaults to ``.venv``);
  1094. for an install whose interpreter lives outside the checkout, the running interpreter's venv.
  1095. ``uv venv`` defaults to ``.venv`` while our installers create ``venv``, so both layouts are in the wild.
  1096. Call sites that only knew about ``venv`` silently no-oped on a ``.venv`` install — that is how the
  1097. Windows shim-lock preflight skipped itself entirely (#79542). ``venv`` wins when both exist, matching
  1098. what the installers write.
  1099. Installers that keep the interpreter out of the checkout (``$HERMES_HOME/venvs/<name>``, the layout the
  1100. shipped Windows launchers assume) have neither, and the ``project_venv_dir(root) or root / "venv"``
  1101. idiom those call sites share then handed ``uv`` a ``VIRTUAL_ENV`` that does not exist: that one invented
  1102. path skipped the import probe, reclassified every ``hermes tools`` dependency as missing and failed the
  1103. reinstall with interpreter errors (#116148). The interpreter running this module is the only truthful
  1104. answer to "which venv is live", so fall back to it — but only for the checkout it was loaded from. A
  1105. foreign root (test temp dir, another clone) still resolves to ``None``: handing it someone else's venv
  1106. would point the callers' writes at the wrong environment.
  1107. """
  1108. root = Path(project_root)
  1109. in_tree = next((root / n for n in ("venv", ".venv") if (root / n).is_dir()), None)
  1110. if in_tree is not None:
  1111. return in_tree
  1112. # Out-of-tree install: the path is real by construction (never invented), and non-venv installs
  1113. # keep today's ``None`` so the ``or root / "venv"`` fallback cannot install into a base interpreter.
  1114. running = Path(sys.prefix)
  1115. if (Path(__file__).resolve().parent == root.resolve()
  1116. and sys.prefix != sys.base_prefix
  1117. and venv_python_path(running).is_file()
  1118. and _venv_installs_checkout(running, root)):
  1119. return running
  1120. return None
  1121. def _venv_installs_checkout(venv: Path, root: Path) -> bool:
  1122. """Is *venv*'s own ``hermes-agent`` installed from *root*?
  1123. Where this module was loaded from does not answer that: ``PYTHONPATH=<checkout>
  1124. <other install>/bin/python`` runs one checkout's code on another install's interpreter,
  1125. and adopting that venv made a dev checkout's update rewrite the Desktop install's venv
  1126. into an editable install of the dev tree. Every install of a checkout into a venv
  1127. (installers, ``uv sync``) records the source tree in ``direct_url.json``.
  1128. """
  1129. import json
  1130. from importlib.metadata import distributions
  1131. from urllib.parse import urlparse
  1132. from urllib.request import url2pathname
  1133. from pm.environments import site_packages
  1134. for dist in distributions(name="hermes-agent", path=[str(site_packages(venv))]):
  1135. try:
  1136. raw = dist.read_text("direct_url.json") # windows-footgun: ok — importlib.metadata API, reads utf-8, no encoding=
  1137. url = json.loads(raw or "{}").get("url", "")
  1138. except ValueError:
  1139. continue
  1140. if url.startswith("file:") and Path(url2pathname(urlparse(url).path)).resolve() == root.resolve():
  1141. return True
  1142. return False
  1143. def venv_python_path(venv_dir, *, windows: bool | None = None) -> Path:
  1144. """Frozen updater surface: pre-PM updaters import this name; pm.environments owns it."""
  1145. from pm.environments import venv_python
  1146. return venv_python(venv_dir, windows=windows)
  1147. # First-party roots: an ImportError naming one means our own tree is inconsistent. The
  1148. # update post-probe shares this set so the guard that BLOCKS and the hint that EXPLAINS agree.
  1149. FIRST_PARTY_MODULE_ROOTS = frozenset({
  1150. "agent", "acp_adapter", "cli", "cron", "gateway", "model_tools", "plugins",
  1151. "providers", "tools", "toolsets", "run_agent", "tui_gateway", "utils",
  1152. })
  1153. def is_first_party_module(name: str | None) -> bool:
  1154. """True when *name* ships with Hermes (exact first segment; ``startswith`` would claim ``agentops``)."""
  1155. root = str(name).split(".")[0] if name else ""
  1156. return bool(root) and (root in FIRST_PARTY_MODULE_ROOTS or root.startswith("hermes_"))
  1157. def partial_update_hint(exc: BaseException) -> list[str]:
  1158. """Recovery guidance lines when *exc* looks like a half-updated tree, else ``[]``."""
  1159. # A missing third-party dep (bad venv, missing extra) is a different problem.
  1160. if (not isinstance(exc, ImportError) or isinstance(exc, ModuleNotFoundError)
  1161. or not is_first_party_module(getattr(exc, "name", None))):
  1162. return []
  1163. return [
  1164. "",
  1165. "This looks like a partially-updated install: one module was refreshed "
  1166. "and a related one was not.",
  1167. "Re-run the update to bring the whole tree to the same version:",
  1168. " hermes update",
  1169. "If that also fails, reinstall: https://hermes-agent.nousresearch.com",
  1170. ]
  1171. def emit_partial_update_hint(exc: BaseException, *, file=None) -> bool:
  1172. """Print recovery guidance for a half-updated tree."""
  1173. lines = partial_update_hint(exc)
  1174. if not lines:
  1175. return False
  1176. for line in (f"Error: {exc}", *lines):
  1177. print(line, file=sys.stderr if file is None else file)
  1178. return True
  1179. def normalize_scope(scope: str | Path | None) -> str | None:
  1180. """Normalize a WRITE-side registry scope key, preserving ``None``.
  1181. Two different contracts live on the same registries — do not unify them:
  1182. * **Write / slot paths** (``register_*``, ``snapshot_registration``,
  1183. ``restore_registration``, tool-registry slot lookup): ``None`` means
  1184. the process-global layer and must stay ``None``. Use this function.
  1185. * **Read paths** (``list_providers``, ``get_provider``): ``None`` means
  1186. "the active home's scope" and must go through :func:`hermes_home_key`
  1187. (falsy input resolves to the active default home). Using this
  1188. function there hides every scoped registration — the exact bug
  1189. fixed after e66a627aa5.
  1190. Both normalize non-None values identically (resolved absolute path,
  1191. normcase on Windows) so writes and reads agree on the key.
  1192. """
  1193. return hermes_home_key(scope) if scope is not None else None