sandbox_image_switch.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Approval gate for the default sandbox image change (nikolaik base → hermes-sandbox:desktop).
  2. A persisted Docker sandbox is state the user built up; a default flip must not replace it under
  3. them. ``DockerEnvironment`` keeps a container whose image differs from an UNPINNED default and
  4. this module is where the user decides: approve (pin the new image; the next terminal use
  5. recreates the container — ``/root`` and ``/workspace`` are host mounts and carry over, system
  6. packages get reinstalled, 3.11 venvs need a rebuild) or keep (pin the image the container runs,
  7. which also ends the notice). Surfaces: the interactive CLI startup offer here, the Screen pane's
  8. switch action (``display.switchSandboxImage``) and the plain ``hermes config set``. Headless
  9. surfaces (gateway, cron) never decide; they keep the sandbox and log.
  10. Modal restores its snapshot and Daytona reuses its labeled sandbox regardless of the configured
  11. image, so existing sandboxes there are untouched without any gate; only fresh ones get the new
  12. image.
  13. """
  14. from __future__ import annotations
  15. import logging
  16. import os
  17. from dataclasses import dataclass, field
  18. from typing import Optional
  19. logger = logging.getLogger(__name__)
  20. @dataclass
  21. class PendingSwitch:
  22. current_image: str # what the persisted container runs
  23. target_image: str # the effective default it would move to
  24. containers: list[str] = field(default_factory=list) # names, for the notice
  25. def pending() -> Optional[PendingSwitch]:
  26. """The switch this profile still has to decide, or None: backend is docker, the image is the
  27. unpinned default, and a container labeled for this profile runs another image. ``docker`` is
  28. consulted (one ``ps``); any failure is "nothing pending"."""
  29. from hermes_cli.config import load_config_readonly
  30. from tools.environments.docker import _container_identity, _docker_query, find_docker
  31. terminal = (load_config_readonly() or {}).get("terminal") or {}
  32. if terminal.get("backend") != "docker":
  33. return None
  34. if _image_pinned(terminal):
  35. return None
  36. target = str(terminal.get("docker_image") or "")
  37. docker = find_docker()
  38. if not docker or not target:
  39. return None
  40. listing = _docker_query(
  41. [docker, "ps", "-a", "--filter", "label=hermes-agent=1",
  42. "--filter", f"label=hermes-profile={_container_identity(str(terminal.get('docker_shared_container_key') or ''))}",
  43. "--format", "{{.Names}}\t{{.Image}}"],
  44. timeout=10, fail="sandbox image switch probe failed: %s", nonzero="docker ps exited %s: %s")
  45. if listing is None:
  46. return None
  47. stale: dict[str, list[str]] = {}
  48. for line in listing.stdout.splitlines():
  49. name, _, image = line.partition("\t")
  50. if image and image != target:
  51. stale.setdefault(image, []).append(name)
  52. if not stale:
  53. return None
  54. current = max(stale, key=lambda img: len(stale[img]))
  55. return PendingSwitch(current_image=current, target_image=target,
  56. containers=sorted(n for names in stale.values() for n in names))
  57. def _image_pinned(terminal_cfg: dict) -> bool:
  58. """Same verdict the runtime uses. The file's own key first; then the bound terminal scope
  59. (a routed profile: recomputed per turn, never the launch profile's ``os.environ``); else the
  60. launch env, where an operator's ``TERMINAL_DOCKER_IMAGE`` differing from the effective value
  61. is their choice."""
  62. from hermes_cli.config import read_raw_config
  63. from tools.terminal_scope import get_terminal_scope
  64. raw = read_raw_config().get("terminal")
  65. if isinstance(raw, dict) and "docker_image" in raw:
  66. return True
  67. scope = get_terminal_scope()
  68. if scope is not None:
  69. return scope.get("TERMINAL_DOCKER_IMAGE_PINNED") == "1"
  70. env_image = os.environ.get("TERMINAL_DOCKER_IMAGE")
  71. return bool(env_image) and env_image != str(terminal_cfg.get("docker_image") or "")
  72. def decide(switch: PendingSwitch, approve: bool) -> str:
  73. """Pin ``terminal.docker_image`` to the target (approve) or the current image (keep) and
  74. re-bridge the live process so a long-running gateway/TUI backend acts on it without a
  75. restart. Returns the image now pinned."""
  76. from hermes_cli.config import apply_terminal_config_to_env, load_config, save_config
  77. image = switch.target_image if approve else switch.current_image
  78. config = load_config()
  79. terminal = config.setdefault("terminal", {})
  80. terminal["docker_image"] = image
  81. save_config(config, preserve_keys={("terminal", "docker_image")})
  82. apply_terminal_config_to_env(env=None, override=True)
  83. if approve:
  84. # The cached environment object still points at the old container; drop it so the next
  85. # terminal call reattaches, sees the pin and recreates. The container itself keeps running
  86. # until then (persistent), nothing is removed here.
  87. from tools.terminal_tool_lifecycle import _evict_environment_for_task
  88. _evict_environment_for_task(None)
  89. return image
  90. def explain_lines(switch: PendingSwitch) -> list[str]:
  91. n = len(switch.containers)
  92. return [
  93. f"Your Docker sandbox ({n} container{'s' if n != 1 else ''}) runs {switch.current_image}.",
  94. f"The default sandbox image is now {switch.target_image}: Python 3.13, Node 26, and a desktop",
  95. "so Bot Screen, computer_use and the browser run inside the sandbox instead of on this machine.",
  96. "Switching recreates the container on the next terminal call. Files in /root and /workspace",
  97. "stay (they live on this machine); packages installed with apt/pip/npm -g inside the container",
  98. "are reinstalled on demand; Python 3.11 virtualenvs need a rebuild.",
  99. ]
  100. def offer_interactive(*, cprint, ask=input) -> Optional[bool]:
  101. """TTY startup offer. Either answer pins an image, so the question is asked once. Returns the
  102. decision, or None when nothing was pending / the user skipped (asked again next start)."""
  103. switch = pending()
  104. if switch is None:
  105. return None
  106. cprint("")
  107. cprint("☤ A new default sandbox image is available.")
  108. for line in explain_lines(switch):
  109. cprint(f" {line}")
  110. try:
  111. answer = ask(" Switch now? [y = switch / n = keep the current image / Enter = ask later]: ").strip().lower()
  112. except (KeyboardInterrupt, EOFError):
  113. print()
  114. return None
  115. if answer in {"y", "yes"}:
  116. decide(switch, approve=True)
  117. cprint(f" ✓ terminal.docker_image = {switch.target_image}; the sandbox is recreated on its next use.")
  118. return True
  119. if answer in {"n", "no"}:
  120. decide(switch, approve=False)
  121. cprint(f" ✓ terminal.docker_image = {switch.current_image}; unset it in config.yaml to be asked again.")
  122. return False
  123. cprint(" Later. `hermes config set terminal.docker_image <image>` decides it any time.")
  124. return None