terminal_tool_config.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """Terminal backend configuration: scope-aware TERMINAL_* reads, env-var parsing,
  2. container-cwd sanity checks, plugin-backend classification, and the ``_quiet``
  3. best-effort block shared by the terminal_tool_* modules.
  4. Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,
  5. so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.
  6. """
  7. import logging
  8. import json
  9. import os
  10. import posixpath
  11. import re
  12. from contextlib import contextmanager
  13. from typing import Any, overload
  14. # Log-record parity with the origin module.
  15. logger = logging.getLogger("tools.terminal_tool")
  16. @contextmanager
  17. def _quiet(label: str, *args, exc=Exception, level: int = logging.DEBUG):
  18. """Best-effort block: swallow *exc*, log *label* (``%``-formatted with *args*)
  19. at *level* with the traceback. For janitor/advisory work that must never
  20. take the terminal tool down."""
  21. try:
  22. yield
  23. except exc:
  24. logger.log(level, label, *args, exc_info=True)
  25. def _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"):
  26. """Parse an env var with *converter*, raising a clear ValueError on bad
  27. values (e.g. TERMINAL_TIMEOUT=5m) instead of an opaque crash. TERMINAL_*
  28. names are read scope-aware via :func:`_tenv`."""
  29. raw = _tenv(name, default) if name.startswith("TERMINAL_") else os.getenv(name, default)
  30. try:
  31. return converter(raw)
  32. except (ValueError, json.JSONDecodeError):
  33. raise ValueError(
  34. f"Invalid value for {name}: {raw!r} (expected {type_label}). "
  35. f"Check ~/.hermes/.env or environment variables."
  36. )
  37. # (current home, Hermes root) -> profile name; only homes that exist are stored (see home_profile_name).
  38. _HOME_PROFILE_NAMES: dict[tuple[str, str], str] = {}
  39. def home_profile_name() -> str:
  40. """Profile name of the current Hermes home (the process home, or a routed turn's bound home);
  41. ``"default"`` when it cannot be resolved. One lookup for every reader that must agree: the
  42. persistent-Docker container key, the container's profile label, the name the TUI stamps on its
  43. sessions (``get_active_profile_name``, so ``custom`` for a home inside the root that is not a
  44. ``profiles/<name>`` home), and the file panel's sandbox names.
  45. Memoized per (home, root) path pair: the lookup resolves three paths and runs on every
  46. container-key resolution, several times per tool call."""
  47. try:
  48. from hermes_cli.profiles import get_active_profile_name
  49. from hermes_constants import get_default_hermes_root, get_hermes_home
  50. home = get_hermes_home()
  51. key = (str(home), str(get_default_hermes_root()))
  52. if (cached := _HOME_PROFILE_NAMES.get(key)) is not None:
  53. return cached
  54. name = get_active_profile_name() or "default"
  55. if home.exists(): # a home created later may resolve differently
  56. _HOME_PROFILE_NAMES[key] = name
  57. return name
  58. except (ImportError, OSError, RuntimeError, ValueError): # an unresolvable home keeps the shared default key
  59. return "default"
  60. def profile_container_key(profile: str) -> str:
  61. """Persistent-Docker container key of a profile: the default profile stays literally ``"default"``."""
  62. return "default" if profile == "default" else f"profile:{profile}"
  63. def _safe_getcwd() -> str:
  64. """``os.getcwd()`` tolerant of a deleted cwd (FileNotFoundError) or a macOS
  65. TCC-protected one without Full Disk Access (PermissionError); falls back
  66. to TERMINAL_CWD, then the home directory."""
  67. try:
  68. return os.getcwd()
  69. except (FileNotFoundError, PermissionError):
  70. return _tenv("TERMINAL_CWD") or os.path.expanduser("~")
  71. # Host-cwd shapes that cannot exist inside a container sandbox: POSIX user dirs and ANY Windows
  72. # drive path (``D:\\...``, ``e:/...``) as they leak toward a Linux ``-w`` flag.
  73. _HOST_CWD_PREFIXES = ("/Users/", "/home/")
  74. _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
  75. def _is_host_cwd(path: str) -> bool:
  76. return path.startswith(_HOST_CWD_PREFIXES) or bool(_WINDOWS_DRIVE_RE.match(path))
  77. def _is_windows_drive_path(path: str) -> bool:
  78. """True for any ``D:\\...`` / ``e:/...`` path. Not a username check."""
  79. return bool(path) and bool(_WINDOWS_DRIVE_RE.match(path))
  80. def _host_path_key(path: str) -> str:
  81. """Compare host paths without caring about slash style or drive-letter case.
  82. A trailing slash is not significant, except we never collapse a drive root
  83. (``C:/``) into a bare ``C:`` that would prefix-match every path on that drive.
  84. """
  85. text = (path or "").replace("\\", "/")
  86. if len(text) >= 2 and text[1] == ":":
  87. text = text[0].lower() + text[1:]
  88. if len(text) > 3:
  89. text = text.rstrip("/")
  90. return text
  91. def translate_mounted_host_path(path: str, host_root: str, container_root: str) -> str | None:
  92. """Map *path* onto *container_root* when it is *host_root* or a child of it.
  93. Returns None when *path* is not under that host directory. Slash style and
  94. drive-letter case do not matter; a sibling directory (``proj`` vs ``proj-other``)
  95. is not a child.
  96. """
  97. if not isinstance(path, str) or not isinstance(host_root, str) or not isinstance(container_root, str):
  98. return None
  99. if not path or not host_root or not container_root:
  100. return None
  101. key = _host_path_key(path)
  102. root = _host_path_key(host_root)
  103. if not key or not root:
  104. return None
  105. mount = container_root.rstrip("/") or "/"
  106. if key == root:
  107. return mount
  108. prefix = root if root.endswith("/") else root + "/"
  109. if not key.startswith(prefix):
  110. return None
  111. return f"{mount}/{key[len(prefix):]}"
  112. def cwd_follows_host_mount(cwd: str, mount: str) -> bool:
  113. """True when *cwd* was the host workspace (or the assumed ``/workspace`` view of it).
  114. An explicit in-container path other than that assumption is left alone.
  115. """
  116. if not mount or not cwd or cwd == mount:
  117. return False
  118. if _is_unusable_container_cwd(cwd):
  119. return True
  120. return cwd == "/workspace" and mount != "/workspace"
  121. _CONTAINER_BACKENDS = frozenset({"docker", "modal", "daytona", "vercel_sandbox"})
  122. _BUILTIN_BACKENDS = _CONTAINER_BACKENDS | {"local", "ssh", "managed_modal"}
  123. def _plugin_registry_lookup(env_type: str, fn_name: str, default, *args):
  124. """Call ``agent.terminal_env_registry.<fn_name>(env_type, *args)`` for a
  125. plugin backend. Fail-soft: *default* for built-in/empty backends, when the
  126. registry is unavailable, or when the provider raises — a misbehaving plugin
  127. must never take the terminal tool down."""
  128. if not env_type or env_type in _BUILTIN_BACKENDS:
  129. return default
  130. try:
  131. import agent.terminal_env_registry as reg
  132. return getattr(reg, fn_name)(env_type, *args)
  133. except Exception:
  134. return default
  135. def _plugin_env_flag(env_type: str, attr: str, default=False):
  136. """Classification flag of a plugin-registered backend (fail-soft, see above)."""
  137. return _plugin_registry_lookup(env_type, "provider_flag", default, attr, default)
  138. def _is_container_backend(env_type: str) -> bool:
  139. """True for built-in container backends and plugins declaring ``is_container``."""
  140. return env_type in _CONTAINER_BACKENDS or _plugin_env_flag(env_type, "is_container")
  141. def _get_plugin_env_provider(env_type: str):
  142. """Return the registered plugin provider for *env_type*, or None."""
  143. return _plugin_registry_lookup(env_type, "get_provider", None)
  144. def plugin_sandbox_home(env: Any) -> str | None:
  145. """The home a plugin environment started in (``_build_plugin_env`` stamps it per environment, so two
  146. sandboxes of one backend never share it), or None."""
  147. home = getattr(env, "_hermes_sandbox_home", None)
  148. return home if isinstance(home, str) and posixpath.isabs(home) and home != "/" else None
  149. def _in_sandbox_home(cwd: Any, env: Any) -> bool:
  150. """True for *cwd* at or under *env*'s sandbox home: a ``cd`` inside that sandbox, not a host workspace,
  151. even when it looks like one (``/home/...``)."""
  152. home = plugin_sandbox_home(env)
  153. if not home or not isinstance(cwd, str) or not posixpath.isabs(cwd):
  154. return False
  155. home, cwd = posixpath.normpath(home), posixpath.normpath(cwd)
  156. return cwd == home or cwd.startswith(home + "/")
  157. @overload
  158. def coerce_ssh_remote_cwd(cwd: str, env_type: str | None) -> str: ...
  159. @overload
  160. def coerce_ssh_remote_cwd(cwd: None, env_type: str | None) -> None: ...
  161. def coerce_ssh_remote_cwd(cwd: str | None, env_type: str | None) -> str | None:
  162. """Cwd to send to an SSH backend.
  163. ``~``-prefixed paths stay literal so the remote shell expands them to the
  164. SSH user's home. The Hermes process's subprocess home (``/opt/data/home``
  165. in the official Docker image) is a directory on the machine running
  166. Hermes: it and anything under it are rewritten onto the remote ``~``, since
  167. ``cd`` into the host path exits 126 on the target. A subprocess home that is
  168. the OS user's real home is left alone: a remote path may legitimately match
  169. it. Other backends are unchanged.
  170. """
  171. if not isinstance(cwd, str) or (env_type or "").strip().lower() != "ssh":
  172. return cwd
  173. text = cwd.strip()
  174. if not text or text.startswith("~"):
  175. return text or "~"
  176. from hermes_constants import get_real_home, get_subprocess_home
  177. home = get_subprocess_home()
  178. if not home or not posixpath.isabs(text) or posixpath.normpath(home) == posixpath.normpath(get_real_home()):
  179. return text
  180. rel = posixpath.relpath(posixpath.normpath(text), posixpath.normpath(home))
  181. if rel == ".":
  182. return "~"
  183. return text if rel == ".." or rel.startswith("../") else f"~/{rel}"
  184. def _is_mounted_host_cwd(cwd: str, mounted_host: str | None) -> bool:
  185. """True when *cwd* is the host directory mounted at ``/workspace``.
  186. Checked before the ``/Users`` / ``/home`` / drive-letter heuristic: a WSL
  187. checkout under ``/mnt/...`` or an absolute path under ``/srv/...`` is
  188. ``os.path.isabs`` and would otherwise look like a valid container workdir.
  189. """
  190. if not cwd or not isinstance(mounted_host, str) or not mounted_host:
  191. return False
  192. try:
  193. left = os.path.normpath(os.path.abspath(os.path.expanduser(cwd)))
  194. right = os.path.normpath(os.path.abspath(os.path.expanduser(mounted_host)))
  195. except (OSError, ValueError):
  196. return False
  197. return left == right
  198. def _is_unusable_container_cwd(cwd: str, *, mounted_host: str | None = None) -> bool:
  199. """True if *cwd* is a host or relative path that can't be a container
  200. workdir: ``docker run -w`` needs an absolute in-sandbox path, otherwise the
  201. container fails to start (exit 125). Windows drive paths aren't ``isabs``
  202. on POSIX, so they're caught by the prefix check.
  203. The directory mounted at ``/workspace`` is unusable inside the container
  204. even when it matches none of those prefixes. That equality check runs
  205. first so ``/mnt/...`` and ``/srv/...`` are not wrapped as ``cd`` targets.
  206. """
  207. if not cwd:
  208. return False
  209. if _is_mounted_host_cwd(cwd, mounted_host):
  210. return True
  211. return _is_host_cwd(cwd) or not os.path.isabs(cwd)
  212. def _tenv(name: str, default: str = "") -> str:
  213. """Scope-aware read of a ``TERMINAL_*`` variable. Every terminal setting
  214. must go through this: under gateway multiplexing the active profile's
  215. config arrives via a per-turn scope, and a raw ``os.getenv`` would read
  216. whatever a previous turn pinned into the process env (cross-profile leak)."""
  217. from tools.terminal_scope import terminal_env
  218. return terminal_env(name, default)
  219. def _tenv_bool(name: str, default: str) -> bool:
  220. """Scope-aware boolean ``TERMINAL_*`` read: true/1/yes (case-insensitive)."""
  221. return _tenv(name, default).lower() in {"true", "1", "yes"}