terminal_env_provider.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """Terminal Environment Provider ABC.
  2. Pluggable-backend interface for terminal execution environments (cloud sandboxes, remote
  3. runners). Providers register via :meth:`PluginContext.register_terminal_environment_provider`;
  4. :func:`tools.terminal_tool_backends._create_environment` consults the registry for any ``TERMINAL_ENV``
  5. / ``terminal.backend`` value that is not a built-in (built-ins stay in ``tools/environments/``;
  6. third-party sandbox vendors do NOT have to live in core). :meth:`create_environment` returns
  7. any ``BaseEnvironment`` duck type (``execute()``, ``cleanup()`` …); the factory stamps
  8. ``_hermes_backend_name`` on the result so file-path resolution can identify plugin backends.
  9. """
  10. from __future__ import annotations
  11. import abc
  12. from typing import Any, Dict, List, Optional, Tuple
  13. from agent.provider_base import ProviderBase
  14. class TerminalEnvironmentProvider(ProviderBase):
  15. """Abstract base class for a pluggable terminal execution backend.
  16. :attr:`name` is the ``terminal.backend`` / ``TERMINAL_ENV`` value (``[a-z0-9_]``); the
  17. registry rejects built-in backend names.
  18. Classification contract — each core policy decision that was historically a frozenset of
  19. built-in names is a declarative attribute so a new backend cannot silently miss one:
  20. * ``is_remote`` — commands run off-host: suppresses host OS/home/cwd hints in the system
  21. prompt, the host Python probe, and remote-aware skill env handling.
  22. * ``is_container`` — own filesystem rooted away from the host: container resource config
  23. passed through, host-looking cwds sanitized, file tools use container path resolution.
  24. * ``skip_container_guards`` — sandbox disposable enough to skip dangerous-command approval
  25. prompts. Defaults to ``is_container``; backends that can mount host paths override to False.
  26. * ``cache_path_base`` — where auto-synced ``~/.hermes/cache`` files land inside the backend
  27. (``"~/.hermes"``, ``"/root/.hermes"``), or ``None`` when host paths remain correct.
  28. * ``strip_env_keys`` — vendor credential env vars, stripped from every subprocess the agent
  29. spawns so a model-authored command can never read them.
  30. * ``session_isolated_when_nonpersistent`` — non-persistent mode gives each session its own
  31. sandbox identity; opt in when a shared name would let two ephemeral runs destroy each other.
  32. * ``default_cwd`` — where commands start when ``terminal.cwd`` is unset or unusable there: an
  33. absolute in-sandbox path, or ``"~"`` for each sandbox's own home. With ``"~"``,
  34. ``create_environment`` receives ``cwd="~"`` (never expanded on the host) and the environment sets
  35. ``self.cwd`` to the absolute home it resolved; commands may also arrive with ``cwd="~"``.
  36. ``None`` keeps the generic ``/root``.
  37. * ``supports_streams`` — environments implement ``exec_prefix(*, user=None, interactive=True)``:
  38. a local argv that runs its remainder (``bash -c <script>``, passed through as separate words)
  39. inside the sandbox with stdin/stdout open, or ``None`` when it cannot right now. Bot Desktop,
  40. ``computer_use`` and the browser then follow the terminal into this backend, as they do for
  41. docker/ssh, instead of refusing.
  42. ``default_cwd`` home resolution and ``exec_prefix`` need the environment object itself, so they
  43. work for in-process plugins only; under ``plugins.isolation: host`` the environment reaches Hermes
  44. as an opaque placeholder and Bot Desktop placement refuses a ``supports_streams`` backend.
  45. """
  46. is_remote: bool = True
  47. is_container: bool = True
  48. session_isolated_when_nonpersistent: bool = False
  49. supports_streams: bool = False
  50. @property
  51. def description(self) -> str:
  52. """One-line description shown in backend pickers."""
  53. return f"Run commands in a {self.display_name} environment."
  54. @property
  55. def skip_container_guards(self) -> bool:
  56. return self.is_container
  57. @property
  58. def cache_path_base(self) -> Optional[str]:
  59. return None
  60. @property
  61. def default_cwd(self) -> Optional[str]:
  62. return None
  63. @property
  64. def strip_env_keys(self) -> frozenset:
  65. return frozenset()
  66. @property
  67. def env_description(self) -> str:
  68. """Prompt-builder fallback for where commands run when the live probe fails (e.g. ``"a Daytona workspace (Linux)"``)."""
  69. return f"a {self.display_name} environment (likely Linux)"
  70. @abc.abstractmethod
  71. def is_available(self) -> bool:
  72. """True when this backend can service commands. Cheap, NO network calls: runs during UI paints."""
  73. def check_requirements(self, config: dict[str, Any]) -> bool:
  74. """Full requirements check with the merged terminal env config; log actionable errors before returning False."""
  75. return self.is_available()
  76. def probe(self) -> tuple[str, str]:
  77. """Dashboard picker health ``(status, detail)``; status ``ready``/``needs_setup``/``unavailable``. Never raise; <~2s."""
  78. return ("ready", "") if self.is_available() else ("needs_setup", f"{self.display_name} is not configured.")
  79. def setup_instructions(self) -> list[str]:
  80. """Lines printed by ``hermes setup`` after selection (the wizard persists ``terminal.backend`` itself)."""
  81. return []
  82. def post_setup(self) -> None:
  83. """Optional interactive hook run by ``hermes setup`` after selection (prompt for tokens, install SDKs)."""
  84. def doctor_checks(self) -> list[tuple[bool, str, str]]:
  85. """``hermes doctor`` rows ``(ok, label, detail)``; default reflects :meth:`is_available`."""
  86. try:
  87. ok = bool(self.is_available())
  88. except Exception:
  89. ok = False
  90. return [(ok, f"{self.display_name} backend", "(configured)" if ok else "(not configured — see setup instructions)")]
  91. @abc.abstractmethod
  92. def create_environment(
  93. self, *, cwd: str, timeout: int, task_id: str = "default", image: Optional[str] = None,
  94. container_config: Optional[dict[str, Any]] = None, **kwargs: Any,
  95. ):
  96. """Create an execution environment (``BaseEnvironment`` duck type). MUST accept ``**kwargs`` and ignore
  97. unknown keys so the factory can evolve without breaking older plugins. ``task_id`` keys reuse/persistence;
  98. ``container_config`` carries ``container_cpu/memory/disk/persistent`` when :attr:`is_container`."""