setup_terminal.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. """Terminal-backend setup wizard (local/docker/modal/daytona/vercel/ssh/plugin).
  2. setup.py names are resolved through the module object so test patches on ``hermes_cli.setup.<name>``
  3. take effect; setup.py re-exports the public entry points."""
  4. import json
  5. import logging
  6. import os
  7. from pathlib import Path
  8. from tools import tool_backend_helpers
  9. from tools.environments.docker import docker_runtime_name, find_docker
  10. from hermes_cli import nous_subscription
  11. logger = logging.getLogger("hermes_cli.setup")
  12. from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as _SANDBOX_IMAGE, DEFAULT_VERCEL_IMAGE
  13. _RUN_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace")
  14. def _prompt_vercel_sandbox_settings(config: dict):
  15. """Prompt for Vercel Sandbox settings without exposing unsupported disk sizing."""
  16. terminal = config.setdefault("terminal", {})
  17. _setup._info(None, "Vercel Sandbox settings:", " Filesystem persistence uses Vercel snapshots.",
  18. " Snapshots restore files only; live processes do not continue after sandbox recreation.")
  19. current_image = terminal.get("vercel_image") or DEFAULT_VERCEL_IMAGE
  20. image = _setup.prompt(" Image (Vercel managed image or VCR repository[:tag])", current_image).strip() or current_image
  21. terminal["vercel_image"] = image
  22. _setup.save_env_value("TERMINAL_VERCEL_IMAGE", image)
  23. if terminal.get("vercel_runtime"):
  24. # Vercel deprecated runtimes; a pinned one still wins over the image until the user clears it.
  25. _setup.print_warning(f"terminal.vercel_runtime={terminal['vercel_runtime']!r} is deprecated by Vercel and "
  26. "overrides the image; unset it to use the image above.")
  27. persist_label = "yes" if terminal.get("container_persistent", True) else "no"
  28. persist = _setup.prompt(" Persist filesystem with snapshots? (yes/no)", persist_label).lower()
  29. terminal["container_persistent"] = persist in {"yes", "true", "y", "1"}
  30. # (key, prompt label, default, parser) — unparseable input leaves the value untouched.
  31. for key, label, default, parse in (
  32. ("container_cpu", " CPU cores", 1, float),
  33. ("container_memory", " Memory in MB (5120 = 5GB)", 5120, int)):
  34. try:
  35. terminal[key] = parse(_setup.prompt(label, str(terminal.get(key, default))))
  36. except ValueError:
  37. pass
  38. if terminal.get("container_disk", 51200) not in {0, 51200}:
  39. _setup.print_warning(
  40. "Vercel Sandbox does not support custom disk sizing; resetting container_disk to 51200.")
  41. terminal["container_disk"] = 51200
  42. _setup._info(None, "Vercel authentication:", " Use a long-lived Vercel access token plus project/team IDs.")
  43. linked = _read_nearest_vercel_project()
  44. if linked:
  45. _setup.print_info(" Found defaults in nearest .vercel/project.json.")
  46. _setup.remove_env_value("VERCEL_OIDC_TOKEN")
  47. # (label, env var, linked-project fallback key, secret) — prompted in order, saved when non-empty.
  48. for label, env_var, linked_key, secret in (
  49. (" Vercel access token", "VERCEL_TOKEN", None, True),
  50. (" Vercel project ID", "VERCEL_PROJECT_ID", "projectId", False),
  51. (" Vercel team ID", "VERCEL_TEAM_ID", "orgId", False)):
  52. default = _setup.get_env_value(env_var) or (linked.get(linked_key, "") if linked_key else "")
  53. value = _setup.prompt(label, default, password=secret)
  54. if value:
  55. _setup.save_env_value(env_var, value)
  56. def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:
  57. """Read project/team defaults from the nearest Vercel link file."""
  58. current = (start or Path.cwd()).resolve()
  59. if current.is_file():
  60. current = current.parent
  61. for directory in (current, *current.parents):
  62. project_file = directory / ".vercel" / "project.json"
  63. if not project_file.exists():
  64. continue
  65. try:
  66. data = json.loads(project_file.read_text(encoding="utf-8-sig"))
  67. except (OSError, json.JSONDecodeError):
  68. return {}
  69. if not isinstance(data, dict):
  70. return {}
  71. return {key: data[key] for key in ("projectId", "orgId")
  72. if isinstance(data.get(key), str) and data[key].strip()}
  73. return {}
  74. def _prompt_secret_env(label: str, env_var: str, *, confirm_msg: str = "") -> None:
  75. """Prompt for a secret and persist it to .env when non-empty."""
  76. value = _setup.prompt(label, password=True)
  77. if value:
  78. _setup.save_env_value(env_var, value)
  79. if confirm_msg:
  80. _setup.print_success(confirm_msg)
  81. def _existing_secret_keeps(env_var: str, label: str, question: str) -> bool:
  82. """True when ``env_var`` is already set and the user declines to update it."""
  83. if not _setup.get_env_value(env_var):
  84. return False
  85. _setup.print_info(f" {label}: already configured")
  86. return not _setup.prompt_yes_no(question, False)
  87. def _ensure_sdk(extra: str) -> None:
  88. """Enable a declared SDK extra without mutating the running interpreter."""
  89. import pm
  90. try:
  91. __import__(extra)
  92. except ImportError:
  93. _setup.print_info(f"Installing {extra} SDK...")
  94. try:
  95. pm.sync_venv([extra], explicit=True)
  96. except (pm.InstallError, OSError, ValueError) as exc:
  97. _setup.print_warning(f"Install failed: {exc}")
  98. _setup.print_info("Retry with: hermes setup terminal")
  99. else:
  100. _setup.print_success(f"{extra} SDK installed. Restart Hermes to use it.")
  101. def _report_binary(found: str | None, missing: str, install_hint: str, found_prefix: str = "Found: ") -> None:
  102. if found:
  103. _setup.print_info(f"{found_prefix}{found}")
  104. else:
  105. _setup.print_warning(missing)
  106. _setup.print_info(install_hint)
  107. def _setup_backend_local(config: dict) -> None:
  108. _setup.print_success("Terminal backend: Local")
  109. _setup.print_info("Commands run directly on this machine.")
  110. # Gateway cwd defaults to home; sudo stays off. Both configurable via `hermes setup terminal`.
  111. config["terminal"].setdefault("cwd", str(Path.home()))
  112. def _setup_backend_docker(config: dict) -> None:
  113. _setup.print_success("Terminal backend: Docker / Podman")
  114. docker_exe = find_docker()
  115. _report_binary(docker_exe, "Docker or Podman not found in PATH!",
  116. "Install Docker: https://docs.docker.com/get-docker/ "
  117. "or Podman: https://podman.io/docs/installation",
  118. f"{docker_runtime_name(docker_exe)} found: " if docker_exe else "")
  119. # Image and resource limits use defaults; tune via `hermes setup terminal`.
  120. config["terminal"].setdefault("docker_image", _SANDBOX_IMAGE)
  121. _setup._info(None, "Docker sandboxes can be protected with the egress credential firewall.",
  122. "It routes sandbox traffic through iron-proxy so containers receive "
  123. "proxy tokens instead of real API keys.",
  124. " Docker only for now; Modal, SSH, Daytona and plugin backends are not wired yet.")
  125. if _setup.prompt_yes_no(" Enable egress firewall for Docker sandboxes?", False):
  126. proxy_cfg = config.setdefault("proxy", {})
  127. proxy_cfg["enabled"] = True
  128. proxy_cfg.setdefault("enforce_on_docker", True)
  129. _setup.print_success("Egress firewall enabled in config")
  130. _setup.print_info(
  131. "Run `hermes egress setup` then `hermes egress start` to mint tokens and launch the proxy.")
  132. else:
  133. _setup.print_info("Skipping egress firewall. You can enable it later with `hermes egress setup`.")
  134. def _setup_backend_modal(config: dict) -> None:
  135. _setup.print_success("Terminal backend: Modal")
  136. _setup.print_info("Serverless cloud sandboxes. Each session gets its own container.")
  137. from tools.managed_tool_gateway import is_managed_tool_gateway_ready
  138. from tools.tool_backend_helpers import normalize_modal_mode
  139. managed_modal_available = bool(
  140. tool_backend_helpers.managed_nous_tools_enabled()
  141. and nous_subscription.get_nous_subscription_features(config).nous_auth_present
  142. and is_managed_tool_gateway_ready("modal"))
  143. modal_mode = normalize_modal_mode(_setup.cfg_get(config, "terminal", "modal_mode"))
  144. use_managed_modal = False
  145. if managed_modal_available:
  146. # Default to the configured mode; when unset, to "direct" only if Modal creds exist.
  147. default_idx = {"managed": 0, "direct": 1}.get(modal_mode, 1 if _setup.get_env_value("MODAL_TOKEN_ID") else 0)
  148. use_managed_modal = _setup.prompt_choice(
  149. "Select how Modal execution should be billed:",
  150. ["Use my Nous subscription", "Use my own Modal account"], default_idx) == 0
  151. if use_managed_modal:
  152. config["terminal"]["modal_mode"] = "managed"
  153. _setup.print_info("Modal execution will use the managed Nous gateway and bill to your subscription.")
  154. if _setup.get_env_value("MODAL_TOKEN_ID") or _setup.get_env_value("MODAL_TOKEN_SECRET"):
  155. _setup.print_info(
  156. "Direct Modal credentials are still configured, but this backend is pinned to managed mode.")
  157. return
  158. config["terminal"]["modal_mode"] = "direct"
  159. _setup.print_info("Requires a Modal account: https://modal.com")
  160. _ensure_sdk("modal")
  161. _setup._info(None, "Modal authentication:", " Get your token at: https://modal.com/settings")
  162. if _existing_secret_keeps("MODAL_TOKEN_ID", "Modal token", " Update Modal credentials?"):
  163. return
  164. _prompt_secret_env(" Modal Token ID", "MODAL_TOKEN_ID")
  165. _prompt_secret_env(" Modal Token Secret", "MODAL_TOKEN_SECRET")
  166. def _setup_backend_daytona(config: dict) -> None:
  167. _setup.print_success("Terminal backend: Daytona")
  168. _setup._info("Persistent cloud development environments.",
  169. "Each session gets a dedicated sandbox with filesystem persistence.",
  170. "Sign up at: https://daytona.io")
  171. _ensure_sdk("daytona")
  172. print()
  173. had_key = bool(_setup.get_env_value("DAYTONA_API_KEY"))
  174. if not _existing_secret_keeps("DAYTONA_API_KEY", "Daytona API key", " Update API key?"):
  175. _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY",
  176. confirm_msg=" Updated" if had_key else " Configured")
  177. config["terminal"].setdefault("daytona_image", _SANDBOX_IMAGE)
  178. def _setup_backend_vercel(config: dict) -> None:
  179. _setup.print_success("Terminal backend: Vercel Sandbox")
  180. _setup._info("Cloud microVM sandboxes with snapshot-backed filesystem persistence.",
  181. "Requires the optional Vercel SDK (installed through Hermes PM).")
  182. _ensure_sdk("vercel")
  183. _prompt_vercel_sandbox_settings(config)
  184. def _setup_backend_ssh(config: dict) -> None:
  185. _setup.print_success("Terminal backend: SSH")
  186. _setup.print_info("Run commands on a remote machine via SSH.")
  187. # (label, env var, fallback default when .env is empty); the port is only saved when not 22.
  188. fields = (
  189. (" SSH host (hostname or IP)", "TERMINAL_SSH_HOST", ""),
  190. (" SSH user", "TERMINAL_SSH_USER", os.getenv("USER", "")),
  191. (" SSH port", "TERMINAL_SSH_PORT", "22"),
  192. (" SSH private key path", "TERMINAL_SSH_KEY", str(Path.home() / ".ssh" / "id_rsa")))
  193. values = []
  194. for label, env_var, default in fields:
  195. value = _setup.prompt(label, _setup.get_env_value(env_var) or default)
  196. values.append(value)
  197. if value and (env_var != "TERMINAL_SSH_PORT" or value != "22"):
  198. _setup.save_env_value(env_var, value)
  199. elif env_var == "TERMINAL_SSH_PORT" and value == "22":
  200. # Answering the default must undo a previously saved non-default port:
  201. # skipping the save alone would leave the stale value in .env.
  202. _setup.remove_env_value(env_var)
  203. host, user, port, ssh_key = values
  204. if host and _setup.prompt_yes_no(" Test SSH connection?", True):
  205. _setup.print_info(" Testing connection...")
  206. import subprocess
  207. ssh_cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", *(["-i", ssh_key] if ssh_key else []),
  208. *(["-p", port] if port and port != "22" else []), f"{user}@{host}" if user else host, "echo ok"]
  209. result = subprocess.run(ssh_cmd, timeout=10, **_RUN_KW, check=False)
  210. if result.returncode == 0:
  211. _setup.print_success(" SSH connection successful!")
  212. else:
  213. _setup.print_warning(f" SSH connection failed: {result.stderr.strip()}")
  214. _setup.print_info(" Check your SSH key and host settings.")
  215. def _setup_backend_plugin(config: dict, backend: str) -> None:
  216. try:
  217. from agent.terminal_env_registry import get_provider
  218. provider = get_provider(backend)
  219. _setup.print_success(f"Terminal backend: {provider.display_name}")
  220. for line in provider.setup_instructions():
  221. _setup.print_info(line)
  222. provider.post_setup()
  223. except Exception as exc:
  224. _setup.print_warning(f"Backend plugin setup hook failed: {exc}")
  225. _BUILTIN_TERMINAL_BACKENDS = [
  226. ("local", "Local - run directly on this machine (default)"),
  227. ("docker", "Docker/Podman - isolated container with configurable resources"),
  228. ("modal", "Modal - serverless cloud sandbox"), ("ssh", "SSH - run on a remote machine"),
  229. ("daytona", "Daytona - persistent cloud development environment"),
  230. ("vercel_sandbox", "Vercel Sandbox - cloud microVM with snapshot filesystem persistence")]
  231. _TERMINAL_BACKEND_SETUP = {
  232. "local": _setup_backend_local, "docker": _setup_backend_docker, "modal": _setup_backend_modal,
  233. "daytona": _setup_backend_daytona, "vercel_sandbox": _setup_backend_vercel, "ssh": _setup_backend_ssh}
  234. # Backend -> env var mirrored from config after setup (config.yaml is the source of truth, but
  235. # terminal_tool reads these from .env).
  236. _BACKEND_ENV_MIRROR = {"modal": ("TERMINAL_MODAL_MODE", "modal_mode", "auto"),
  237. "vercel_sandbox": ("TERMINAL_VERCEL_IMAGE", "vercel_image", DEFAULT_VERCEL_IMAGE)}
  238. def setup_terminal_backend(config: dict):
  239. """Configure the terminal execution backend."""
  240. _setup.print_header("Terminal Backend")
  241. _setup._info("Choose where Hermes runs shell commands and code.",
  242. "This affects tool execution, file access, and isolation.",
  243. f" Guide: {_setup._DOCS_BASE}/user-guide/configuration#terminal-backend-configuration", None)
  244. current_backend = _setup.cfg_get(config, "terminal", "backend", default="local")
  245. backends = list(_BUILTIN_TERMINAL_BACKENDS)
  246. # Plugin-registered backends (~/.hermes/plugins/). Fail-soft: a broken plugin must not take
  247. # the wizard down.
  248. plugin_backend_names = []
  249. try:
  250. from hermes_cli.plugins import discover_plugins
  251. discover_plugins() # idempotent — plugin state may not be loaded yet
  252. from agent.terminal_env_registry import list_providers
  253. for provider in list_providers():
  254. pname = provider.name.strip().lower()
  255. backends.append((pname, f"{provider.display_name} - {provider.description}"))
  256. plugin_backend_names.append(pname)
  257. except Exception:
  258. pass
  259. terminal_choices = [label for _, label in backends] + [f"Keep current ({current_backend})"]
  260. terminal_idx = _setup.prompt_choice("Select terminal backend:", terminal_choices, len(backends))
  261. if terminal_idx == len(backends):
  262. _setup.print_info(f"Keeping current backend: {current_backend}")
  263. return
  264. selected_backend = backends[terminal_idx][0] if 0 <= terminal_idx < len(backends) else None
  265. config.setdefault("terminal", {})["backend"] = selected_backend
  266. # Plugin names shadow only the ssh built-in (dispatch order of the original chain).
  267. handler = _TERMINAL_BACKEND_SETUP.get(selected_backend)
  268. if handler is not None and (selected_backend != "ssh" or selected_backend not in plugin_backend_names):
  269. handler(config)
  270. elif selected_backend in plugin_backend_names:
  271. _setup_backend_plugin(config, selected_backend)
  272. _setup.save_env_value("TERMINAL_ENV", selected_backend)
  273. if selected_backend in _BACKEND_ENV_MIRROR:
  274. env_var, key, default = _BACKEND_ENV_MIRROR[selected_backend]
  275. _setup.save_env_value(env_var, config["terminal"].get(key, default))
  276. _setup.save_config(config)
  277. print()
  278. _setup.print_success(f"Terminal backend set to: {selected_backend}")
  279. import hermes_cli.setup as _setup