terminal_breadcrumbs.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """Per-terminal session breadcrumbs for ``hermes -c`` / ``--continue``. Strictly best-effort: no
  2. function raises; without a stable terminal identity (no tty, no known multiplexer env var) ``-c``
  3. falls back to latest-session. Gated by ``session.terminal_continue`` (default true)."""
  4. from __future__ import annotations
  5. import json
  6. import os
  7. import re
  8. import sys
  9. import time
  10. from pathlib import Path
  11. from typing import Optional
  12. from utils import atomic_json_write, unlink_files_older_than
  13. # Multiplexer / terminal-emulator identity env vars, checked in order when no real tty path is
  14. # available (e.g. stdin piped but stdout still a pty owned by a known terminal).
  15. _TERMINAL_ENV_VARS = ("ZELLIJ_PANE_ID", "TMUX_PANE", "KITTY_WINDOW_ID", "WEZTERM_PANE", "TERM_SESSION_ID", "WT_SESSION")
  16. # Breadcrumbs older than this are pruned opportunistically on each write — a pane id from a tmux
  17. # server restarted last month means nothing today.
  18. _STALE_AFTER_SECONDS = 30 * 24 * 60 * 60
  19. _SANITIZE_RE = re.compile(r"[^A-Za-z0-9._-]")
  20. def _breadcrumbs_dir() -> Path:
  21. from hermes_constants import get_hermes_home
  22. return get_hermes_home() / "terminal-sessions"
  23. def _sanitize(raw: str) -> str:
  24. """Make an id safe to use as a filename (``/dev/pts/3`` -> ``dev-pts-3``)."""
  25. return _SANITIZE_RE.sub("-", raw.strip().strip("/"))[:120]
  26. def get_terminal_id() -> Optional[str]:
  27. """Stable identity for this terminal: the tty device path (stdin, then stdout), else the first
  28. present multiplexer/emulator env var; ``None`` when neither exists (callers skip breadcrumbs)."""
  29. for fd in (sys.stdin, sys.stdout):
  30. try:
  31. name = os.ttyname(fd.fileno())
  32. except Exception:
  33. continue
  34. if name:
  35. return f"tty-{_sanitize(name)}"
  36. for var in _TERMINAL_ENV_VARS:
  37. val = os.environ.get(var)
  38. if val:
  39. return f"{var.lower()}-{_sanitize(val)}"
  40. return None
  41. def is_enabled() -> bool:
  42. """Config gate: ``session.terminal_continue`` (default true)."""
  43. try:
  44. from hermes_cli.config import load_config
  45. return bool((load_config().get("session") or {}).get("terminal_continue", True))
  46. except Exception:
  47. return True
  48. def write_breadcrumb(session_id: str, cwd: Optional[str] = None) -> None:
  49. """Record that this terminal's live session is ``session_id``. Never raises; no-op when the
  50. feature is disabled, the session id is empty, or no terminal identity exists."""
  51. try:
  52. if not session_id or not is_enabled():
  53. return
  54. terminal_id = get_terminal_id()
  55. if not terminal_id:
  56. return
  57. directory = _breadcrumbs_dir()
  58. from hermes_constants import mkdir_under_hermes_home
  59. mkdir_under_hermes_home(directory)
  60. now = time.time()
  61. payload = {"session_id": session_id, "cwd": cwd or os.getcwd(), "ts": now}
  62. atomic_json_write(directory / terminal_id, payload, indent=None)
  63. unlink_files_older_than(directory, "*", _STALE_AFTER_SECONDS, now=now)
  64. except Exception:
  65. pass
  66. def read_breadcrumb() -> Optional[dict]:
  67. """This terminal's breadcrumb payload, or ``None`` (missing, corrupt, or stale). Never raises."""
  68. try:
  69. terminal_id = get_terminal_id()
  70. if not terminal_id:
  71. return None
  72. path = _breadcrumbs_dir() / terminal_id
  73. data = json.loads(path.read_text(encoding="utf-8-sig"))
  74. if not isinstance(data, dict) or not str(data.get("session_id") or "").strip():
  75. return None
  76. ts = data.get("ts")
  77. if isinstance(ts, (int, float)) and time.time() - ts > _STALE_AFTER_SECONDS:
  78. return None
  79. return data
  80. except Exception:
  81. return None
  82. def resolve_breadcrumb_session() -> Optional[str]:
  83. """Resolve a bare ``-c`` for this terminal, or ``None`` to fall back. The breadcrumb's session
  84. id counts only if it still exists in the DB, projected through the compression chain so the
  85. resume lands on the live tip (same projection as ``main._resolve_session_by_name_or_id``)."""
  86. if not is_enabled():
  87. return None
  88. crumb = read_breadcrumb()
  89. if not crumb:
  90. return None
  91. session_id = str(crumb.get("session_id") or "").strip()
  92. if not session_id:
  93. return None
  94. try:
  95. from hermes_state import SessionDB
  96. from hermes_constants import get_hermes_home
  97. db = SessionDB(db_path=get_hermes_home() / "state.db", read_only=True)
  98. except Exception:
  99. return None
  100. try:
  101. if not db.get_session(session_id):
  102. return None # session was deleted — fall back to latest
  103. try:
  104. return db.get_compression_tip(session_id) or session_id
  105. except Exception:
  106. return session_id
  107. except Exception:
  108. return None
  109. finally:
  110. try:
  111. db.close()
  112. except Exception:
  113. pass