remote_common.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. """Helpers shared by the non-local terminal backends (docker, ssh, cloud SDKs)."""
  2. from __future__ import annotations
  3. import os
  4. import shlex
  5. import subprocess
  6. from typing import Callable, Iterable
  7. from tools.environments.base_session_env import _SHELL_ENV_NAME_RE
  8. from tools.environments.local_env_policy import _is_hermes_internal_secret, _is_provider_env_blocklisted
  9. def load_hermes_env_vars() -> dict[str, str]:
  10. """``~/.hermes/.env`` values, or ``{}`` — a broken .env must not fail command execution."""
  11. try:
  12. from hermes_cli.config import load_env
  13. return load_env() or {}
  14. except Exception:
  15. return {}
  16. def resolve_passthrough_env(explicit_forward: Iterable[str] = (),
  17. hermes_env_loader: Callable[[], dict[str, str]] = load_hermes_env_vars,
  18. ) -> tuple[dict[str, str], set[str]]:
  19. """Values to forward into a remote shell plus the scoped names that must be unset there.
  20. Implicit passthrough (skill ``required_environment_variables`` + ``terminal.env_passthrough``)
  21. is filtered through the Hermes provider-credential blocklist and the dynamic internal-secret
  22. check; ``explicit_forward`` entries (docker_forward_env) are an operator opt-in that bypasses
  23. both. Each value is the routed profile's secret when multiplex is active; a name the active
  24. scope lacks is returned in the unset set so a shared sandbox cannot leak another profile's
  25. value.
  26. """
  27. passthrough_keys: set[str] = set()
  28. resolve_passthrough_value = None
  29. multiplex_active = False
  30. is_global_env = lambda _name: False
  31. try:
  32. from tools.env_passthrough import get_all_passthrough, resolve_passthrough_value
  33. from agent.secret_scope import _is_global_env as is_global_env, is_multiplex_active
  34. multiplex_active = is_multiplex_active()
  35. passthrough_keys = set(get_all_passthrough())
  36. except Exception:
  37. pass
  38. implicit_forward = {k for k in passthrough_keys if not _is_hermes_internal_secret(k)}
  39. forward_keys = set(explicit_forward) | {
  40. k for k in implicit_forward if not _is_provider_env_blocklisted(k)}
  41. hermes_env = hermes_env_loader() if forward_keys else {}
  42. exec_env: dict[str, str] = {}
  43. unset_names: set[str] = set()
  44. for key in sorted(forward_keys):
  45. value = os.getenv(key) or hermes_env.get(key)
  46. if resolve_passthrough_value is not None:
  47. value = resolve_passthrough_value(key, value)
  48. if value is not None:
  49. exec_env[key] = value
  50. elif multiplex_active and not is_global_env(key) and _SHELL_ENV_NAME_RE.fullmatch(key):
  51. unset_names.add(key)
  52. return exec_env, unset_names
  53. def prepend_unset(cmd_string: str, names: Iterable[str]) -> str:
  54. """Prefix ``cmd_string`` with ``unset`` of the profile-scoped names the remote shell must not see."""
  55. names = sorted(names)
  56. if not names:
  57. return cmd_string
  58. return f"unset {' '.join(shlex.quote(n) for n in names)} 2>/dev/null || true\n{cmd_string}"
  59. def client_env_with(values: dict[str, str]) -> dict[str, str] | None:
  60. """Env for the docker/ssh CLIENT subprocess: forwarded values travel here (owner-readable
  61. /proc/*/environ) while the argv carries names only; ``None`` = inherit when nothing to add."""
  62. return {**os.environ, **values} if values else None
  63. def run_capture(cmd: list[str], *, timeout: float, check: bool = False, env: dict | None = None,
  64. ) -> subprocess.CompletedProcess:
  65. """``subprocess.run`` with the backend-standard capture settings: text mode with utf-8/replace
  66. decoding and stdin closed (DEVNULL) so a CLI that unexpectedly prompts cannot hang the agent."""
  67. return subprocess.run(
  68. cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
  69. timeout=timeout, check=check, stdin=subprocess.DEVNULL, env=env)
  70. def bash_argv(cmd_string: str, login: bool = False) -> list[str]:
  71. """``bash [-l] -c <cmd>`` argv tail used by every spawn-per-call backend."""
  72. return ["bash", "-l", "-c", cmd_string] if login else ["bash", "-c", cmd_string]
  73. def ensure_lazy_dep(extra: str) -> None:
  74. """Lazy-install an optional SDK's pm extra (idempotent). Install failures
  75. surface as ``ImportError``."""
  76. import pm
  77. try:
  78. pm.ensure_import(extra)
  79. except Exception as e:
  80. raise ImportError(str(e))