main_tui_launch.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. """TUI (ui-tui) launcher: prepared source builds and argv/env assembly.
  2. Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_ROOT``, ...)
  3. are imported lazily inside the functions that use them (avoids an import cycle).
  4. """
  5. import logging
  6. import contextlib
  7. import json
  8. import os
  9. import shutil
  10. import sqlite3
  11. import subprocess
  12. import sys
  13. from pathlib import Path
  14. from typing import Optional
  15. from agent.i18n import t
  16. # Log-record parity with the origin module.
  17. logger = logging.getLogger("hermes_cli.main")
  18. def _bypass_chat_launch(args) -> bool:
  19. """--safe-mode / --ignore-user-config chat: the gateway owner freezes code defaults and runs
  20. the turn out of process, so the profile's display.interface must not pick a surface and the
  21. client performs no discovery. Explicit --tui forwards the flags in its session.create policy."""
  22. return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False)) \
  23. and not getattr(args, "tui", False)
  24. def _read_tui_active_session_file(path: Optional[str]) -> Optional[str]:
  25. if not path:
  26. return None
  27. try:
  28. data = json.loads(Path(path).read_text(encoding="utf-8-sig"))
  29. return str(data.get("session_id") or "").strip() or None
  30. except Exception:
  31. return None
  32. # A canonical local session is keyed ``local-`` + 64 hex; main's epilogue printed 22-char stored ids.
  33. _SHORT_RESUME_LEN = 22
  34. def _short_resume_id(db, session_id: str) -> str:
  35. """The 22-char prefix of a canonical ``local-…`` id when it names only that session (``--resume``
  36. resolves a unique prefix back); every other id, or an ambiguous prefix, prints whole."""
  37. if not session_id.startswith("local-") or len(session_id) <= _SHORT_RESUME_LEN:
  38. return session_id
  39. short = session_id[:_SHORT_RESUME_LEN]
  40. try:
  41. return short if db.resolve_session_id(short) == session_id else session_id
  42. except sqlite3.Error: # an unreadable store prints the whole id
  43. return session_id
  44. def _branch_lineage(db, session: dict) -> list:
  45. """*session* plus each ``/branch`` ancestor it was cut from. Main's epilogue after ``/branch`` still
  46. named the parent and so reported the conversation's tokens; a canonical branch child is named
  47. itself, and its copied history was billed on the ancestors."""
  48. rows, seen = [session], {session.get("id")}
  49. while True:
  50. try:
  51. config = json.loads(rows[-1].get("model_config") or "{}")
  52. except (TypeError, ValueError):
  53. break
  54. parent_id = config.get("_branched_from") if isinstance(config, dict) else None
  55. parent = db.get_session(parent_id) if parent_id and parent_id not in seen else None
  56. if not parent:
  57. break
  58. seen.add(parent_id)
  59. rows.append(parent)
  60. return rows
  61. def _print_tui_exit_summary(session_id: Optional[str], active_session_file: Optional[str] = None) -> None:
  62. """Print a shell-visible epilogue after TUI exits."""
  63. from hermes_cli.main import _resolve_last_session
  64. target = (
  65. _read_tui_active_session_file(active_session_file) or session_id or _resolve_last_session(source="tui")
  66. )
  67. if not target:
  68. return
  69. db = None
  70. try:
  71. from hermes_state import SessionDB
  72. from hermes_cli.config import get_hermes_home
  73. db = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)
  74. session = db.get_session(target)
  75. if not session:
  76. return
  77. title = db.get_session_title(target)
  78. resume_id = _short_resume_id(db, target)
  79. message_count = int(session.get("message_count") or 0)
  80. if message_count == 0:
  81. return # No real conversation — don't show resume info
  82. tokens = {k: 0 for k in ("input", "output", "cache_read", "cache_write", "reasoning")}
  83. for row in _branch_lineage(db, session):
  84. for k in tokens:
  85. tokens[k] += int(row.get(f"{k}_tokens") or 0)
  86. except Exception:
  87. return
  88. finally:
  89. if db is not None:
  90. db.close()
  91. # Sessions live under the profile's HERMES_HOME — mirror cli_session_mixin::_print_exit_summary.
  92. from hermes_cli.profiles import get_active_profile_name
  93. active_profile = get_active_profile_name()
  94. profile_flag = "" if active_profile in ("default", "custom") else f" -p {active_profile}"
  95. print(f"\n{t('cli.session.exit_resume_hint')}\n hermes --tui --resume {resume_id}{profile_flag}")
  96. if title:
  97. print(f' hermes --tui -c "{title}"{profile_flag}')
  98. print(f"\nSession: {resume_id}")
  99. if title:
  100. print(f"Title: {title}")
  101. print(f"Messages: {message_count}")
  102. print(
  103. "Tokens: "
  104. f"{sum(tokens.values())} (in {tokens['input']}, out {tokens['output']}, "
  105. f"cache {tokens['cache_read'] + tokens['cache_write']}, reasoning {tokens['reasoning']})"
  106. )
  107. def _tui_need_rebuild(root: Path) -> bool:
  108. from hermes_cli.source_build import source_product_current
  109. force = (os.environ.get("HERMES_TUI_FORCE_BUILD") or "").strip().lower()
  110. return force in {"1", "true", "yes", "on"} or not source_product_current(root.parent, "tui", root / "dist")
  111. def _find_bundled_tui(hermes_cli_dir: Path | None = None) -> Path | None:
  112. """Find a pre-built TUI entry.js bundled in the wheel."""
  113. if hermes_cli_dir is None:
  114. hermes_cli_dir = Path(__file__).parent
  115. bundled = hermes_cli_dir / "tui_dist" / "entry.js"
  116. return bundled if bundled.is_file() else None
  117. def _restore_tui_workspace(tui_dir: Path) -> bool:
  118. """Best-effort ``git restore`` of a missing ``ui-tui/`` (Windows AV/NTFS filters can delete
  119. tracked files after ``hermes update``); True when the directory exists afterwards.
  120. On Windows an antivirus / NTFS filter driver can leave tracked ``ui-tui/`` files deleted in the working
  121. tree after ``hermes update`` (HEAD stays intact; the files just vanish — see issue #49145). Those files
  122. are tracked, so ``git restore`` puts them back deterministically. Best-effort: returns False (rather
  123. than raising) when git is unavailable, this isn't a checkout, or the restore leaves the directory still
  124. missing — the caller then prints the manual-recovery message.
  125. """
  126. git = shutil.which("git")
  127. if not git or not (tui_dir.parent / ".git").exists():
  128. return False
  129. try:
  130. subprocess.run(
  131. [git, "restore", "--", tui_dir.name], cwd=str(tui_dir.parent), capture_output=True,
  132. text=True, encoding="utf-8", errors="replace", check=False)
  133. except OSError:
  134. return False
  135. return tui_dir.is_dir()
  136. def _ensure_tui_workspace(tui_dir: Path) -> None:
  137. """Ensure ``ui-tui/`` exists before it is used as a subprocess cwd (else ``NotADirectoryError``
  138. / ``WinError 267`` with no usable message): git-restore first, then abort with recovery steps.
  139. Without this, a missing workspace falls through to ``subprocess.run(..., cwd=<missing ui-tui>)``, which
  140. crashes with ``NotADirectoryError`` (``WinError 267`` on Windows) instead of a usable message (#49145).
  141. We first try to self-heal via ``git restore``; only if that can't recover the directory do we abort with
  142. concrete manual-recovery steps.
  143. """
  144. if tui_dir.is_dir():
  145. return
  146. if _restore_tui_workspace(tui_dir):
  147. if not os.environ.get("HERMES_QUIET"):
  148. print(f"Restored missing TUI workspace: {tui_dir}")
  149. return
  150. print(
  151. "Error: the TUI workspace is missing from this Hermes checkout.\n"
  152. f"Expected directory: {tui_dir}\n"
  153. "This usually means `hermes update` left tracked ui-tui files deleted.\n"
  154. "Recovery:\n"
  155. " 1. From the Hermes checkout, run `git restore -- ui-tui`\n"
  156. " 2. Run `npm install --silent --no-fund --no-audit --progress=false`\n"
  157. " 3. Retry `hermes --tui`\n"
  158. "If the checkout is still inconsistent, run `hermes update --force`.",
  159. file=sys.stderr)
  160. sys.exit(1)
  161. def _tui_node_bin(bin: str) -> str:
  162. """Resolve the TUI runtime through PM; an explicit bundled HERMES_NODE wins."""
  163. if bin == "node":
  164. env_node = os.environ.get("HERMES_NODE")
  165. if env_node and os.path.isfile(env_node) and os.access(env_node, os.X_OK):
  166. return env_node
  167. from pm import ensure
  168. path = shutil.which(bin, path=ensure(bin).env["PATH"])
  169. if not path:
  170. print(
  171. f"Node.js is required for the TUI but `{bin}` was not found. Install it from "
  172. "https://nodejs.org (run `hermes doctor` for the install hint for your OS), then "
  173. "retry `hermes --tui`. To keep working now, run `hermes --cli`."
  174. )
  175. sys.exit(1)
  176. return path
  177. def _make_tui_argv(tui_dir: Path, tui_dev: bool) -> tuple[list[str], Path]:
  178. """TUI: --dev → tsx src; else node dist (HERMES_TUI_DIR prebuilt or esbuild)."""
  179. # Footgun: --dev against a prebuilt bundle that has no source/node_modules.
  180. ext_dir = os.environ.get("HERMES_TUI_DIR")
  181. if tui_dev and ext_dir:
  182. print(
  183. f"Error: --dev is incompatible with HERMES_TUI_DIR={ext_dir}\n"
  184. f"The prebuilt TUI has no source code to hot-reload.\n"
  185. f"Unset HERMES_TUI_DIR (e.g. `unset HERMES_TUI_DIR`) to use --dev from a checkout.",
  186. file=sys.stderr)
  187. sys.exit(1)
  188. # 1. Prebuilt bundle (nix / packaged release / Docker image): just run it.
  189. # Must run BEFORE _ensure_tui_workspace(): a prebuilt install ships
  190. # hermes_cli/tui_dist/entry.js but never ui-tui/ (git checkouts only).
  191. # 1. A prebuilt install (Docker image, Nix build, or prior `npm run build`) ships
  192. # hermes_cli/tui_dist/entry.js but never ships ui-tui/ at all (that directory only exists in a git
  193. # checkout) — so requiring the workspace to exist first made every prebuilt dashboard Chat tab
  194. # connection hard-exit before it ever got a chance to try the bundled entry.js it already has. See
  195. # #56665.
  196. if not tui_dev:
  197. if ext_dir:
  198. p = Path(ext_dir)
  199. if (p / "dist" / "entry.js").is_file():
  200. return [_tui_node_bin("node"), "--expose-gc", str(p / "dist" / "entry.js")], p
  201. bundled = _find_bundled_tui()
  202. if bundled is not None:
  203. return [_tui_node_bin("node"), "--expose-gc", str(bundled)], bundled.parent
  204. # About to npm install/build from source, so the workspace must exist.
  205. if not ext_dir:
  206. _ensure_tui_workspace(tui_dir)
  207. if not tui_dev and not _tui_need_rebuild(tui_dir):
  208. return [_tui_node_bin("node"), "--expose-gc", str(tui_dir / "dist/entry.js")], tui_dir
  209. from hermes_cli.source_build import build_source_tui, prepare_launch_dependencies, source_build_env
  210. project_root = tui_dir.parent
  211. env = source_build_env()
  212. prepare_launch_dependencies(project_root, env=env)
  213. if tui_dev:
  214. # tsx imports @hermes/ink's built exports; the production bundle instead
  215. # compiles its source directly through scripts/build/tui.mjs.
  216. npm = shutil.which("npm", path=env["PATH"])
  217. subprocess.run([npm, "run", "build"], cwd=tui_dir / "packages/hermes-ink", env=env, check=True)
  218. tsx = tui_dir / "node_modules/.bin/tsx"
  219. return ([str(tsx), "src/entry.tsx"] if tsx.exists() else [npm, "start"]), tui_dir
  220. build_source_tui(project_root, env=env)
  221. node = shutil.which("node", path=env["PATH"])
  222. return [node, "--expose-gc", str(tui_dir / "dist/entry.js")], tui_dir
  223. def _split_comma_items(items, *, split_non_str: bool = True) -> list[str]:
  224. """Flatten str / list (comma-separated) input into stripped non-empty parts."""
  225. raw_items = [items] if isinstance(items, str) else items
  226. if not isinstance(raw_items, (list, tuple)):
  227. raw_items = [raw_items]
  228. normalized: list[str] = []
  229. for item in raw_items:
  230. if split_non_str or isinstance(item, str):
  231. normalized.extend(part.strip() for part in str(item).split(","))
  232. else:
  233. normalized.append(str(item).strip())
  234. return [item for item in normalized if item]
  235. def _normalize_tui_toolsets(toolsets: object) -> list[str]:
  236. """Normalize argparse/Fire-style toolset input for the TUI subprocess."""
  237. try:
  238. from hermes_cli.oneshot import _normalize_toolsets
  239. return _normalize_toolsets(toolsets) or []
  240. except (AttributeError, ImportError):
  241. return _split_comma_items(toolsets, split_non_str=False) if toolsets else []
  242. def _read_cgroup_memory_limit() -> Optional[int]:
  243. """Container memory limit in bytes, or None if unconstrained (v2 ``memory.max``, then v1).
  244. V8 is NOT cgroup-aware: a flat 8GB heap grows past a smaller container limit
  245. and the OOM-killer SIGKILLs Node with no breadcrumb (bare ``stdin EOF``).
  246. """
  247. candidates = (
  248. "/sys/fs/cgroup/memory.max", # cgroup v2
  249. "/sys/fs/cgroup/memory/memory.limit_in_bytes", # cgroup v1
  250. )
  251. for path in candidates:
  252. try:
  253. with open(path, "r", encoding="utf-8-sig") as f:
  254. raw = f.read().strip()
  255. except (OSError, ValueError):
  256. continue
  257. if raw == "max":
  258. return None
  259. if not raw:
  260. continue # don't mistake an empty v2 file for "unlimited"
  261. try:
  262. limit = int(raw)
  263. except ValueError:
  264. continue
  265. if limit <= 0:
  266. continue
  267. if limit >= (1 << 50): # >= ~1 PB is the v1 "unlimited" sentinel
  268. return None
  269. return limit
  270. return None
  271. def _resolve_tui_heap_mb(default_mb: int = 8192) -> int:
  272. """V8 ``--max-old-space-size`` (MB) that fits the container: ``default_mb`` when unconstrained,
  273. else 75% of the cgroup limit (headroom for non-heap RSS + the gateway child), floored at
  274. 1536MB when the container is > 2GB (below that V8 GC-thrashes)."""
  275. limit = _read_cgroup_memory_limit()
  276. if not limit:
  277. return default_mb
  278. limit_mb = limit // (1024 * 1024)
  279. sized = int(limit_mb * 0.75)
  280. if sized >= default_mb:
  281. return default_mb
  282. # Below the floor, honor the limit-derived value anyway: a graceful V8 exit
  283. # beats a silent cgroup kill.
  284. return max(1536, sized) if limit_mb > 2048 else sized
  285. def _safe_tui_cwd(env: Optional[dict] = None) -> str:
  286. """Return a stable cwd value for the Node TUI child environment."""
  287. from hermes_cli.main import PROJECT_ROOT
  288. try:
  289. return os.getcwd()
  290. except FileNotFoundError:
  291. candidate = ((env or {}).get("PWD") or os.environ.get("PWD") or "").strip()
  292. if candidate and Path(candidate).is_dir():
  293. return candidate
  294. return str(PROJECT_ROOT)
  295. def _apply_tui_python_env(env: dict) -> None:
  296. """Seed/repair Python-related env vars shared by CLI and dashboard TUI launches."""
  297. from hermes_cli.main import PROJECT_ROOT
  298. src_root = str(env.get("HERMES_PYTHON_SRC_ROOT") or "").strip()
  299. if not src_root or not Path(src_root).is_dir():
  300. env["HERMES_PYTHON_SRC_ROOT"] = str(PROJECT_ROOT)
  301. cwd = str(env.get("HERMES_CWD") or "").strip()
  302. if not cwd or not Path(cwd).is_dir():
  303. env["HERMES_CWD"] = _safe_tui_cwd(env)
  304. python = str(env.get("HERMES_PYTHON") or "").strip()
  305. if os.path.dirname(python):
  306. python_path = Path(python)
  307. if not python_path.is_absolute():
  308. python_path = Path(env["HERMES_CWD"]) / python_path
  309. python_is_executable = python_path.is_file() and os.access(python_path, os.X_OK)
  310. else:
  311. python_is_executable = bool(shutil.which(python, path=env.get("PATH")))
  312. if not python_is_executable:
  313. env["HERMES_PYTHON"] = sys.executable
  314. def _setup_tui_worktree() -> dict:
  315. """Create the ``--worktree`` checkout for a TUI launch (prune + async pack maintenance); exits on failure."""
  316. wt_info = None
  317. try:
  318. from cli import _git_repo_root, _maintain_pack_health, _prune_stale_worktrees, _setup_worktree
  319. repo = _git_repo_root()
  320. if repo:
  321. _prune_stale_worktrees(repo)
  322. # Repack on pack sprawl so `worktree add` never crawls on a
  323. # multi-agent box; on a thread so it can't block launch.
  324. import threading as _threading
  325. _threading.Thread(
  326. target=_maintain_pack_health, args=(repo,), name="pack-maintenance", daemon=True).start()
  327. from hermes_cli.config import get_hermes_home
  328. # The session's frozen cwd keeps this checkout; name the store from creation so a
  329. # launcher killed with its terminal still leaves the tree to its sessions.
  330. wt_info = _setup_worktree(retain_db=get_hermes_home() / "state.db")
  331. except Exception as exc:
  332. print(f"✗ Failed to create TUI worktree: {exc}", file=sys.stderr)
  333. if not wt_info:
  334. sys.exit(1)
  335. return wt_info
  336. def _remove_idle_clean_tui_worktree(wt_info: dict) -> bool:
  337. """Remove the ``--tui -w`` checkout on quit when nothing still needs it (N8) -> True if gone.
  338. Kept when the gateway has queued or started work for a session inside it (quitting only
  339. detaches the viewer), still schedules work for one (an active loop, heartbeat or goal
  340. continuation, or a cron job bound to it), another viewer still holds one, or another process
  341. still works in it; and by ``_cleanup_worktree`` when it is dirty, holds unpushed commits or
  342. something no branch keeps.
  343. """
  344. from hermes_cli.config import get_hermes_home
  345. from hermes_cli.worktree_exit import _still_in_use
  346. from hermes_cli.worktree_ops import _retained_tree_is_live, _tree_still_served
  347. path = wt_info.get("path")
  348. if not path or not Path(path).is_dir():
  349. return False
  350. try:
  351. db_path = str(get_hermes_home() / "state.db")
  352. if _retained_tree_is_live(db_path, path, pending_only=True):
  353. return False
  354. if _still_in_use(path):
  355. return False
  356. # After the grace above: a legacy sidecar stamps its rows ``tui_shutdown`` as it exits.
  357. if _tree_still_served(db_path, path):
  358. return False
  359. from cli import _cleanup_worktree
  360. _cleanup_worktree(wt_info)
  361. except Exception:
  362. logger.debug("TUI worktree cleanup failed; keeping %s", path, exc_info=True)
  363. return False
  364. return not Path(path).exists()
  365. def _require_bypass_model(env: dict, model: Optional[str], resume_session_id: Optional[str]) -> None:
  366. """A --safe-mode / --ignore-user-config session reads no profile default model, so the owner
  367. refuses its session.create without one (bare invalid_params). Say so before the TUI starts,
  368. as classic chat does; a resume reuses the frozen route and needs none."""
  369. from utils import is_truthy_value
  370. bypass = any(is_truthy_value(env.get(name)) for name in ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"))
  371. if bypass and not resume_session_id and not (model or env.get("HERMES_MODEL", "").strip()):
  372. print("Error: --safe-mode / --ignore-user-config (or HERMES_IGNORE_USER_CONFIG=1) read no profile "
  373. "default model: pass --model explicitly.\n"
  374. " Example: hermes --tui --safe-mode --provider openrouter --model anthropic/claude-sonnet-4",
  375. file=sys.stderr)
  376. raise SystemExit(1)
  377. # Launch flags the Ink client cannot carry into session.create yet. Refused (exit 2, as classic
  378. # chat refuses unsupported flags), never dropped: a dropped --api-key/--base-url would silently
  379. # run the session on the profile's own endpoint and credentials.
  380. _TUI_UNFORWARDED = {"api_key": "--api-key", "base_url": "--base-url", "reasoning": "--reasoning"}
  381. def _refuse_unforwarded_tui_flags(args) -> None:
  382. flags = [flag for name, flag in _TUI_UNFORWARDED.items() if getattr(args, name, None)]
  383. if flags:
  384. print(f"Error: Unsupported --tui options: {', '.join(flags)}. No session was started.\n"
  385. f" Use classic chat for this launch: hermes chat --cli {' '.join(flags)} ...\n"
  386. " Or set model.base_url / agent.reasoning_effort in config.yaml (/reasoning in the TUI).",
  387. file=sys.stderr)
  388. raise SystemExit(2)
  389. def _launch_tui(
  390. resume_session_id: Optional[str] = None, tui_dev: bool = False, native_mode: Optional[bool] = None,
  391. model: Optional[str] = None,
  392. provider: Optional[str] = None, toolsets: object = None, skills: object = None,
  393. verbose: Optional[bool] = None, quiet: bool = False, query: Optional[str] = None,
  394. image: Optional[str] = None, worktree: bool = False, checkpoints: bool = False,
  395. pass_session_id: bool = False, max_turns: Optional[int] = None, accept_hooks: bool = False):
  396. """Replace current process with the TUI."""
  397. from hermes_cli.main import PROJECT_ROOT
  398. tui_dir = PROJECT_ROOT / "ui-tui"
  399. import tempfile
  400. # TUI child is a hermes process: propagate the profile-home contract via
  401. # the single factory; keep secrets (the TUI/agent needs provider creds).
  402. from tools.environments.local import build_subprocess_env
  403. env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=True)
  404. _require_bypass_model(env, model, resume_session_id)
  405. # The directory this launch was invoked from is the source of truth. An inherited
  406. # HERMES_CWD (exported by an outer `hermes --tui`, or by the user's own shell) merely
  407. # names *a* real directory, so the is_dir() repair in _apply_tui_python_env keeps it
  408. # and the gateway starts in last session's project. `--worktree` still wins below.
  409. env["HERMES_CWD"] = _safe_tui_cwd(env)
  410. from hermes_cli.shared_session_attach import configure_tui_attachment
  411. try:
  412. configure_tui_attachment(env, resume_session_id)
  413. except (ValueError, RuntimeError) as exc:
  414. print(f"Error: {exc}", file=sys.stderr)
  415. raise SystemExit(1) from None
  416. try:
  417. from hermes_cli.config import apply_terminal_config_to_env
  418. apply_terminal_config_to_env(env=env)
  419. except Exception:
  420. logger.debug("Failed to apply terminal config bridge for TUI launch", exc_info=True)
  421. active_session_fd, active_session_file = tempfile.mkstemp(
  422. prefix="hermes-tui-active-session-", suffix=".json")
  423. os.close(active_session_fd)
  424. env["HERMES_TUI_ACTIVE_SESSION_FILE"] = active_session_file
  425. env.setdefault("NODE_ENV", "development" if tui_dev else "production")
  426. if native_mode is None:
  427. try:
  428. from hermes_cli.config import load_config
  429. from utils import is_truthy_value
  430. display = load_config().get("display", {})
  431. native_mode = is_truthy_value(display.get("tui_native", False)) if isinstance(display, dict) else False
  432. except Exception:
  433. native_mode = False
  434. env["HERMES_TUI_NATIVE"] = "1" if native_mode else "0"
  435. wt_info = None
  436. if worktree:
  437. wt_info = _setup_tui_worktree()
  438. env["HERMES_CWD"] = wt_info["path"]
  439. env["TERMINAL_CWD"] = wt_info["path"]
  440. # A local interactive session starts where the user launched (or in the --worktree), the
  441. # classic CLI's rule; terminal.cwd stays the default for gateway, cron and remote backends.
  442. # HERMES_TUI_CWD is what the TUI sends on session.create, which beats the configured cwd (#84015).
  443. if str(env.get("TERMINAL_ENV") or "local") == "local":
  444. env["TERMINAL_CWD"] = env["HERMES_TUI_CWD"] = env["HERMES_CWD"]
  445. else:
  446. env.pop("HERMES_TUI_CWD", None)
  447. _apply_tui_python_env(env)
  448. # This shell's allowlisted environment, sent as each session's ``client_env`` (LC-8, T3): taken from
  449. # the shell before the launcher's own edits (NODE_OPTIONS heap, TUI pins) so the session gets the
  450. # PATH / venv / HERMES_* values the user exported.
  451. from hermes_cli.gateway_chat import shell_client_env
  452. env["HERMES_TUI_CLIENT_ENV"] = json.dumps(shell_client_env())
  453. skills_value = ""
  454. if skills:
  455. skills_value = (
  456. ",".join(_split_comma_items(skills)) if isinstance(skills, (list, tuple)) else str(skills).strip())
  457. for key, value in (
  458. ("HERMES_MODEL", model), ("HERMES_INFERENCE_MODEL", model),
  459. ("HERMES_TUI_PROVIDER", provider), ("HERMES_INFERENCE_PROVIDER", provider),
  460. ("HERMES_TUI_TOOLSETS", ",".join(_normalize_tui_toolsets(toolsets))),
  461. ("HERMES_TUI_SKILLS", skills_value),
  462. ("HERMES_TUI_QUERY", query), ("HERMES_TUI_IMAGE", image),
  463. ("HERMES_TUI_CHECKPOINTS", "1" if checkpoints else None),
  464. ("HERMES_TUI_PASS_SESSION_ID", "1" if pass_session_id else None),
  465. ("HERMES_TUI_MAX_TURNS", str(max_turns) if max_turns is not None else None),
  466. ("HERMES_TUI_TOOL_PROGRESS", "verbose" if verbose else "off" if quiet else None),
  467. ("HERMES_ACCEPT_HOOKS", "1" if accept_hooks else None)):
  468. if value:
  469. env[key] = value
  470. # Generous V8 heap (8GB target; default cap can fatal-OOM on long sessions),
  471. # sized below the cgroup limit by _resolve_tui_heap_mb() so V8 exits
  472. # gracefully instead of being reaped silently. Token-level merge respects a
  473. # user-supplied --max-old-space-size. --expose-gc is NOT added here: Node
  474. # rejects it in NODE_OPTIONS; _make_tui_argv() passes it as a direct flag.
  475. _tokens = env.get("NODE_OPTIONS", "").split()
  476. if not any(t.startswith("--max-old-space-size=") for t in _tokens):
  477. _tokens.append(f"--max-old-space-size={_resolve_tui_heap_mb()}")
  478. env["NODE_OPTIONS"] = " ".join(_tokens)
  479. # HERMES_TUI_RESUME is an internal hand-off to the Ink app. We start from a
  480. # full os.environ snapshot, so a stale exported value would make a plain
  481. # `hermes --tui` try to resume a non-existent session; only forward the id
  482. # argparse resolved for this invocation.
  483. env.pop("HERMES_TUI_RESUME", None)
  484. if resume_session_id:
  485. env["HERMES_TUI_RESUME"] = resume_session_id
  486. argv, cwd = _make_tui_argv(tui_dir, tui_dev)
  487. code: Optional[int] = None
  488. try:
  489. try:
  490. code = subprocess.call(argv, cwd=str(cwd), env=env)
  491. except KeyboardInterrupt:
  492. code = 130
  493. if code in {0, 130}:
  494. _print_tui_exit_summary(resume_session_id, active_session_file)
  495. finally:
  496. attached_session = _read_tui_active_session_file(active_session_file) or resume_session_id
  497. with contextlib.suppress(OSError):
  498. os.unlink(active_session_file)
  499. if wt_info and code in {0, 130}:
  500. from hermes_cli.worktree_exit import ask_exit_choice
  501. ask_exit_choice(wt_info)
  502. from hermes_cli.worktree_exit import apply_exit_choice
  503. if wt_info and apply_exit_choice(wt_info, print):
  504. wt_info = None # archived or discarded at the user's request
  505. if wt_info and _remove_idle_clean_tui_worktree(wt_info):
  506. wt_info = None # clean and idle: removed with its branch, as before the shared gateway
  507. if wt_info:
  508. # Quitting detaches a viewer; the gateway may still be executing in
  509. # this checkout and future resumes retain its frozen cwd.
  510. if attached_session:
  511. # The launch lock names this (exiting) pid; hand it to the session so a later
  512. # launch's stale prune keeps the tree while the session is resumable.
  513. from hermes_cli.config import get_hermes_home
  514. from hermes_cli.worktree_ops import _retain_worktree_for_session
  515. _retain_worktree_for_session(wt_info["repo_root"], wt_info["path"], attached_session,
  516. get_hermes_home() / "state.db")
  517. print(f"Worktree retained for this session: {wt_info['path']}", file=sys.stderr)
  518. # Exit code 42 = TUI requested an update. Relaunch as `hermes update`;
  519. # preserve_inherited=False keeps --tui and other flags out of the subcommand.
  520. if code == 42:
  521. from hermes_cli.relaunch import relaunch
  522. print("\n☤ Launching update...\n")
  523. relaunch(["update"], preserve_inherited=False)
  524. sys.exit(code)
  525. def _pin_kanban_board_env() -> None:
  526. """Pin the active kanban board into ``HERMES_KANBAN_BOARD`` so in-process tools and shelled-out
  527. ``hermes kanban`` calls agree even if a concurrent ``boards switch`` flips the file mid-turn.
  528. Without this, in-process tools (``kanban_*``) and shelled-out CLI calls (``hermes kanban …``) resolve
  529. the board on different paths: the env-pin if set, otherwise the global ``<root>/kanban/current`` file. A
  530. concurrent ``hermes kanban boards switch`` from another session can flip the file mid-turn, so the same
  531. chat sees its tool calls hit board A while its shell calls hit board B (#20074). Pinning at chat boot
  532. mirrors what the dispatcher already does for spawned workers.
  533. """
  534. if os.environ.get("HERMES_KANBAN_BOARD"):
  535. return
  536. with contextlib.suppress(Exception):
  537. from hermes_cli.kanban_db import get_current_board
  538. os.environ["HERMES_KANBAN_BOARD"] = get_current_board()
  539. def _sync_bundled_skills_quietly() -> None:
  540. """Seed ``~/.hermes/skills/`` with the bundled library (idempotent, milliseconds when synced).
  541. Failures are swallowed: skills are an enhancement, not a hard dependency."""
  542. with contextlib.suppress(Exception):
  543. from tools.skills_sync import sync_skills
  544. sync_skills(quiet=True)
  545. def _resolve_use_tui(args) -> bool:
  546. """Decide whether to launch the TUI: ``--cli`` → classic; ``--tui`` → TUI; no TTY → classic;
  547. ``HERMES_TUI=1`` → TUI; ``display.interface`` config; default classic.
  548. The TTY gate is load-bearing: ambient preferences must never hijack a piped
  549. ``hermes chat -q`` (kanban workers, cron) — the Ink no-TTY bail-out exits 0 and
  550. the worker dies with a protocol violation. Explicit ``--tui`` still bails out.
  551. """
  552. if getattr(args, "cli", False):
  553. return False
  554. if getattr(args, "tui", False) or getattr(args, "tui_native", False):
  555. return True
  556. try:
  557. if not (sys.stdin.isatty() and sys.stdout.isatty()):
  558. return False
  559. except Exception:
  560. return False
  561. if os.environ.get("HERMES_TUI") == "1":
  562. return True
  563. try:
  564. from hermes_cli.config import load_config
  565. iface = (load_config().get("display", {}) or {}).get("interface", "cli")
  566. return isinstance(iface, str) and iface.strip().lower() == "tui"
  567. except Exception:
  568. return False