terminal_scope.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """Per-turn terminal scope: profile-scoped TERMINAL_* policy.
  2. Multiplexed surfaces (gateway, dashboard/TUI, cron) serve several profiles from one process;
  3. mirroring terminal settings into ``os.environ`` let the first profile pin its backend onto
  4. everyone else (sandbox escape). Like ``agent/secret_scope.py``, a ContextVar holds the active
  5. profile's COMPLETE ``TERMINAL_*`` policy; while bound, ``terminal_env`` resolves ONLY from it
  6. (omitted keys -> defined default, never ambient env). If the policy cannot be resolved a
  7. *refusal* scope is installed and terminal execution raises :class:`TerminalPolicyUnavailable`.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import os
  12. from contextlib import contextmanager
  13. from contextvars import ContextVar, Token
  14. from pathlib import Path
  15. from typing import Any, Dict, Iterator, Optional
  16. logger = logging.getLogger(__name__)
  17. # None = no scope bound (process-env behavior); dict = complete policy; Refusal = resolution failed.
  18. _terminal_scope_var: ContextVar = ContextVar("hermes_terminal_scope", default=None)
  19. # Keys whose default lives in terminal_tool.py, not DEFAULT_CONFIG (which wins on overlap);
  20. # without them the projection is not total.
  21. _TOOL_LEVEL_DEFAULTS: dict[str, Any] = {
  22. "cwd": ".", "ssh_host": "", "ssh_user": "", "ssh_port": 22, "ssh_key": "",
  23. "docker_orphan_reaper": True, "docker_persist_across_processes": True,
  24. "sandbox_dir": "", "lifetime_seconds": 300, "docker_shared_container_key": "",
  25. "home_mode": "auto",
  26. }
  27. class TerminalPolicyUnavailable(Exception):
  28. """The routed profile's ``.env``/``config.yaml`` exists but cannot be read/parsed."""
  29. class TerminalPolicyRefusal(dict[str, str]):
  30. """Marker scope (empty dict subclass) installed when policy resolution failed."""
  31. def __init__(self, reason: str) -> None:
  32. super().__init__()
  33. self.reason = reason
  34. def set_terminal_scope(mapping: Optional[dict[str, str]]) -> Token:
  35. """Install *mapping* as the current context's terminal policy."""
  36. return _terminal_scope_var.set(mapping)
  37. def reset_terminal_scope(token: Token) -> None:
  38. _terminal_scope_var.reset(token)
  39. def get_terminal_scope() -> Optional[dict[str, str]]:
  40. """The active scope mapping/refusal, or ``None`` when no scope is bound."""
  41. return _terminal_scope_var.get()
  42. def enforce_no_refusal() -> None:
  43. """Raise when the active scope is a refusal scope (fail closed).
  44. Execution paths (terminal tool, execute_code) call this before spawning anything: under a refusal scope
  45. the profile's terminal policy could not be resolved, and running with the launch process's ambient
  46. policy is exactly the authority leak this module closes (#68559 requires refusal, not fallback).
  47. Non-scoped and policy-scoped contexts pass silently.
  48. """
  49. scope = _terminal_scope_var.get()
  50. if isinstance(scope, TerminalPolicyRefusal):
  51. raise TerminalPolicyUnavailable(
  52. f"terminal policy unavailable for this profile: {scope.reason}")
  53. def terminal_env(name: str, default: str = "") -> str:
  54. """Authoritative read of a ``TERMINAL_*`` variable.
  55. No scope: process env, then *default*. Refusal scope: raise. Policy scope: ONLY the
  56. policy; a missing key yields *default*, never os.environ.
  57. """
  58. scope = _terminal_scope_var.get()
  59. if scope is None:
  60. return os.environ.get(name, default)
  61. enforce_no_refusal()
  62. value = scope.get(name)
  63. return default if value is None else str(value)
  64. def _apply_terminal_mapping(scope: dict[str, str], mapping: dict[str, Any]) -> None:
  65. from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value
  66. for cfg_key, value in mapping.items():
  67. # cwd placeholders are resolved per-surface later; not a policy value.
  68. if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):
  69. continue
  70. env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)
  71. if env_var:
  72. # List/dict config values must be JSON (same contract as
  73. # apply_terminal_config_to_env). str() yields Python repr, which
  74. # json.loads in terminal_tool rejects.
  75. scope[env_var] = _terminal_env_value(value)
  76. def default_terminal_scope() -> dict[str, str]:
  77. """Code-default ``TERMINAL_*`` policy: what a profile-bypassing session freezes instead of
  78. reading ``.env``/``config.yaml``. Total like the profile projection, minus the profile."""
  79. from hermes_cli.config_defaults import DEFAULT_CONFIG
  80. scope: dict[str, str] = {}
  81. _apply_terminal_mapping(scope, {**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})
  82. return scope
  83. def build_profile_terminal_scope(
  84. hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:
  85. """Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.
  86. Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <- *env_overlay*
  87. <- profile ``config.yaml`` ``terminal:`` <- managed-scope ``terminal:``. Total by construction,
  88. so a bound scope never widens back to ambient authority. Raises :class:`TerminalPolicyUnavailable`
  89. if a present file is unreadable, except a ``.env`` that refuses reads while managed scope pins
  90. ``terminal.backend``.
  91. *env_overlay* is a TRUSTED ``TERMINAL_*`` mapping captured from the launch process before
  92. multiplexing began (``tui_gateway/launch_profile_policy.py``): the launch profile's
  93. env-only policy (``TERMINAL_ENV=ssh`` from systemd, ``op run``, a launcher bridge) has no
  94. file to rebuild it from, and reading live ``os.environ`` here is the leak this module
  95. closes. It sits where the process env sits in the standalone bridge — explicit YAML keys
  96. still win (``apply_terminal_config_to_env``).
  97. """
  98. from hermes_cli import managed_scope
  99. from hermes_cli.config import _deep_merge
  100. from hermes_cli.config_backend import config_exists
  101. home = Path(hermes_home)
  102. scope = default_terminal_scope()
  103. default_image = scope.get("TERMINAL_DOCKER_IMAGE")
  104. env_path = home / ".env"
  105. if env_path.exists():
  106. # load_env_file swallows OSError by design (secret scope fails soft); an unreadable
  107. # profile .env must fail closed here, unless managed scope pins the backend: a sandbox
  108. # launcher withholds the .env and pins the backend there, and load_env_file reads it as {}.
  109. try:
  110. env_path.read_bytes()
  111. except Exception as exc:
  112. if not isinstance(exc, PermissionError) or managed_scope.pinned_terminal_backend() is None:
  113. raise TerminalPolicyUnavailable(f"cannot read {env_path}: {exc}") from exc
  114. from agent.secret_scope import load_env_file
  115. profile_env = load_env_file(env_path)
  116. scope.update((k, str(v)) for k, v in profile_env.items() if k.startswith("TERMINAL_"))
  117. # Provenance, not value: an image WRITTEN in the profile's .env is the user's choice even when
  118. # it spells the default (same rule apply_terminal_config_to_env applies to a set env var).
  119. image_pinned = "TERMINAL_DOCKER_IMAGE" in profile_env
  120. else:
  121. image_pinned = False
  122. if env_overlay:
  123. scope.update((k, str(v)) for k, v in env_overlay.items()
  124. if k.startswith("TERMINAL_") and k != "TERMINAL_DOCKER_IMAGE_PINNED")
  125. # The overlay is the LAUNCHER's environment: its pin verdict is about the launcher's profile and
  126. # is never inherited, and the bridge backfills TERMINAL_DOCKER_IMAGE for defaults too, so only a
  127. # value that differs from the default can prove a choice made there.
  128. if env_overlay.get("TERMINAL_DOCKER_IMAGE") not in (None, default_image):
  129. image_pinned = True
  130. # Read config.yaml directly, not via read_raw_config() (which collapses "missing" and
  131. # "unparseable" into {}): present-but-unparseable must fail closed.
  132. config_path = home / "config.yaml"
  133. try:
  134. has_config = config_exists(config_path)
  135. except Exception as exc:
  136. raise TerminalPolicyUnavailable(f"cannot resolve terminal config in {home}: {exc}") from exc
  137. raw_terminal = None
  138. if has_config:
  139. from hermes_cli.config_backend import read_config_doc_readonly
  140. try:
  141. # Signature-cached: a scope is rebuilt per routed turn/poll, the file rarely changes.
  142. raw = read_config_doc_readonly(config_path)
  143. except Exception as exc:
  144. raise TerminalPolicyUnavailable(f"cannot parse {config_path}: {exc}") from exc
  145. raw_terminal = raw.get("terminal") if isinstance(raw, dict) else None
  146. if isinstance(raw_terminal, dict):
  147. _apply_terminal_mapping(scope, raw_terminal)
  148. image_pinned = image_pinned or "docker_image" in raw_terminal
  149. managed_terminal = managed_scope.apply_managed_overlay({}).get("terminal")
  150. if isinstance(managed_terminal, dict):
  151. # Managed scope applies last, merged per key into the profile's mapping as load_config() merges
  152. # them, so a managed docker_env entry keeps the profile's other entries. A null value pins nothing.
  153. _apply_terminal_mapping(
  154. scope, _deep_merge(raw_terminal if isinstance(raw_terminal, dict) else {}, managed_terminal))
  155. image_pinned = image_pinned or managed_terminal.get("docker_image") is not None
  156. scope["TERMINAL_DOCKER_IMAGE_PINNED"] = "1" if image_pinned else "0"
  157. _resolve_scope_cwd_placeholder(scope)
  158. return scope
  159. def _resolve_scope_cwd_placeholder(scope: dict[str, str]) -> None:
  160. """Give a scope with no explicit ``terminal.cwd`` the same resolved ``TERMINAL_CWD`` a standalone
  161. gateway computes at import (``gateway/run.py``: local backend → ``$HOME``; docker with the
  162. workspace mount → the host cwd signal; other backends → unset). Without it a routed turn's
  163. ``resolve_agent_cwd()`` falls back to the multiplexer PROCESS cwd (wherever ``hermes gateway``
  164. was launched), so the system prompt, context-file discovery and the local terminal all run in
  165. a directory the profile's standalone gateway would never have used."""
  166. if scope.get("TERMINAL_CWD"):
  167. return
  168. from gateway.cwd_placeholder import resolve_placeholder_terminal_cwd
  169. resolved = resolve_placeholder_terminal_cwd(
  170. configured_cwd="", terminal_backend=scope.get("TERMINAL_ENV", ""),
  171. messaging_cwd=None,
  172. docker_mount_cwd_to_workspace=scope.get(
  173. "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in {"true", "1", "yes"},
  174. home_fallback=str(Path.home()),
  175. )
  176. if resolved:
  177. scope["TERMINAL_CWD"] = resolved
  178. def prepare_profile_terminal_scope(
  179. hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> dict[str, str]:
  180. """The scope ``install_profile_terminal_scope`` installs: the profile's policy, or the refusal scope
  181. when it cannot be resolved. Never raises. Reads the profile files (the managed-scope overlay under the
  182. current context's home override); the result can be built in a worker and installed on the loop with
  183. ``install_and_reset_profile_terminal_scope(prepared=...)``."""
  184. try:
  185. return build_profile_terminal_scope(hermes_home, env_overlay=env_overlay)
  186. except TerminalPolicyUnavailable as exc:
  187. logger.warning("terminal policy unavailable: %s", exc)
  188. return TerminalPolicyRefusal(str(exc))
  189. def install_profile_terminal_scope(
  190. hermes_home: Any, *, env_overlay: Optional[dict[str, str]] = None) -> Token:
  191. """Build AND install a profile's policy; on failure install the refusal scope. Never raises."""
  192. return set_terminal_scope(prepare_profile_terminal_scope(hermes_home, env_overlay=env_overlay))
  193. @contextmanager
  194. def install_and_reset_profile_terminal_scope(
  195. hermes_home: Any, *, prepared: Optional[dict[str, str]] = None) -> Iterator[None]:
  196. """Install the profile's terminal policy for a bounded turn/fire. Never raises. *prepared* is a
  197. ``prepare_profile_terminal_scope`` result built earlier (off the loop); without it the policy is
  198. built here."""
  199. token = set_terminal_scope(prepared) if prepared is not None else install_profile_terminal_scope(hermes_home)
  200. try:
  201. yield
  202. finally:
  203. reset_terminal_scope(token)