web_host_terminal.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Host-terminal policy and process setup for the browser-hosted Desktop UI."""
  2. from __future__ import annotations
  3. import os
  4. from collections.abc import Mapping
  5. from pathlib import Path
  6. from typing import Optional
  7. META_PREFIX = "\0HERMES_TERMINAL_META:"
  8. def request_allowed() -> bool:
  9. """Allow host shells only for Webapp on loopback or behind authentication."""
  10. from hermes_cli.web_server import app
  11. from hermes_cli.web_server_chat import _LOOPBACK_HOSTS
  12. from hermes_cli.web_server_surface import policy
  13. if not policy(app.state).host_terminal:
  14. return False
  15. if getattr(app.state, "auth_required", False):
  16. return True
  17. return (getattr(app.state, "bound_host", "") or "").strip().lower() in _LOOPBACK_HOSTS
  18. def shell_command(candidate: str) -> Optional[str]:
  19. """Return an executable shell path for ``candidate``, or None.
  20. A relative path is refused: the PTY chdirs into the workspace before exec,
  21. so it would name a different file than the one checked here.
  22. """
  23. from hermes_platform.resolver import locate_command
  24. raw = (candidate or "").strip()
  25. found = locate_command(raw).command if raw else ()
  26. return found[0] if found else None
  27. def shell_spec() -> tuple[list[str], str]:
  28. """Resolve the interactive-shell ladder the native Desktop uses (electron/terminal-ipc.ts).
  29. POSIX honours ``$SHELL``, then /bin/zsh, /bin/bash, /bin/sh. Windows ignores ``$SHELL``
  30. (usually a stray MSYS/Git path) and takes PowerShell 7, Windows PowerShell, ``COMSPEC``,
  31. then cmd.exe. Electron's ``HERMES_DESKTOP_SHELL`` override is not read here: settings do
  32. not ride on ``HERMES_*`` environment variables.
  33. """
  34. if os.name == "nt":
  35. system_root = os.environ.get("SystemRoot") or os.environ.get("windir") or r"C:\Windows"
  36. windows_powershell = Path(system_root) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
  37. ladder = ("pwsh.exe", "pwsh", str(windows_powershell), "powershell.exe", os.environ.get("COMSPEC", ""))
  38. fallback = "cmd.exe"
  39. else:
  40. ladder = (os.environ.get("SHELL", ""), "/bin/zsh", "/bin/bash", "/bin/sh")
  41. fallback = "/bin/sh"
  42. command = next(filter(None, map(shell_command, ladder)), fallback)
  43. name = Path(command).name.lower()
  44. if name.startswith(("pwsh", "powershell")):
  45. args = ["-NoLogo"]
  46. elif name.startswith("cmd"):
  47. args = []
  48. elif "zsh" in name or "bash" in name:
  49. args = ["-il"]
  50. else:
  51. args = ["-i"]
  52. return [command, *args], name
  53. def safe_cwd(requested: Optional[str]) -> str:
  54. fallback = Path.home()
  55. try:
  56. candidate = Path((requested or "").strip() or fallback).expanduser().resolve()
  57. if candidate.is_dir():
  58. return str(candidate)
  59. if candidate.is_file():
  60. return str(candidate.parent)
  61. except (OSError, RuntimeError, ValueError):
  62. pass
  63. return str(fallback)
  64. def terminal_lc_ctype(env: Mapping[str, str], platform: str) -> Optional[str]:
  65. """Return the LC_CTYPE a host shell's ``env`` needs added, or None to leave it alone.
  66. macOS accepts the bare charset name ``UTF-8`` as a locale; glibc rejects it,
  67. and LC_CTYPE outranks LANG, so forcing it on Linux breaks even a valid LANG.
  68. There a set LANG is left in charge (copying it would pin a value a login rc
  69. may still change) and only a missing one falls back to glibc's C.UTF-8.
  70. Windows shells take their code page from the console, not LC_CTYPE. Desktop's
  71. terminalLcCtype (electron/terminal-ipc.ts) shares the darwin and C.UTF-8 choices
  72. but copies LANG into LC_CTYPE and does not defer to LC_ALL.
  73. """
  74. if env.get("LC_ALL") or env.get("LC_CTYPE") or platform == "win32":
  75. return None
  76. if platform == "darwin":
  77. return "UTF-8"
  78. return None if env.get("LANG") else "C.UTF-8"
  79. def resolve_argv(
  80. *, home: Path, requested_cwd: Optional[str] = None,
  81. ) -> tuple[list[str], str, dict[str, str], str]:
  82. """Return argv/cwd/env/name for Webapp's authenticated host terminal in ``home``."""
  83. from gateway.run import _profile_runtime_scope
  84. from hermes_cli import __version__
  85. from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP
  86. from hermes_constants import (
  87. get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override,
  88. )
  89. from hermes_platform.host.facts import os_family
  90. from tools.environments.local import build_subprocess_env, served_profile_child_env
  91. from tools.terminal_scope import enforce_no_refusal, get_terminal_scope
  92. from tui_gateway.launch_profile_policy import (
  93. activate_multi_profile_hosting, launch_profile_runtime_scope,
  94. )
  95. if home.resolve() != get_process_hermes_home().resolve():
  96. activate_multi_profile_hosting()
  97. scope = _profile_runtime_scope(home)
  98. else:
  99. scope = launch_profile_runtime_scope(home)
  100. # The startup eager-multiplex guard applies even before a secondary's first
  101. # request. Home alone cannot authorize passthrough reads; both shell paths
  102. # need the same complete scope, including the frozen launch environment.
  103. override_token = set_hermes_home_override(str(home))
  104. try:
  105. with scope:
  106. enforce_no_refusal()
  107. base_env = served_profile_child_env(target_home=home)
  108. for env_var in TERMINAL_CONFIG_ENV_MAP.values():
  109. base_env.pop(env_var, None)
  110. terminal_scope = get_terminal_scope()
  111. assert terminal_scope is not None # both runtime scopes bind the complete policy
  112. base_env.update(terminal_scope)
  113. env = build_subprocess_env(base=base_env, scrub_secrets=True)
  114. finally:
  115. reset_hermes_home_override(override_token)
  116. for key in list(env):
  117. if key == "npm_config_prefix" or key.startswith(("npm_config_", "npm_package_")):
  118. env.pop(key, None)
  119. for key in ("NO_COLOR", "FORCE_COLOR", "COLORFGBG"):
  120. env.pop(key, None)
  121. env["COLORTERM"] = "truecolor"
  122. env["TERM"] = "xterm-256color"
  123. env["TERM_PROGRAM"] = "Hermes"
  124. env["TERM_PROGRAM_VERSION"] = __version__
  125. env["HERMES_DESKTOP_TERMINAL"] = "1"
  126. if lc_ctype := terminal_lc_ctype(env, os_family()):
  127. env["LC_CTYPE"] = lc_ctype
  128. argv, shell_name = shell_spec()
  129. return argv, safe_cwd(requested_cwd), env, shell_name
  130. def query_dimension(raw: Optional[str], default: int, maximum: int) -> int:
  131. try:
  132. value = int(raw or default)
  133. except (TypeError, ValueError, OverflowError):
  134. return default
  135. return max(2, min(maximum, value))