Skip to content

The agent that grows with you

feat: session temp root moves off tmpfs /tmp to ~/.hermes/cache/terminal by default; auto-pruned after 72h

Teknium95cf7dc9e8e9
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..5e51a112c67
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1 @@
+rahlquist
diff --git a/gateway/run.py b/gateway/run.py
index e85cd3b0e06..79383c25dca 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -30736,6 +30736,7 @@ def _start_gateway_housekeeping(stop_event: threading.Event, adapters=None, loop
cleanup_video_cache,
)
from tools.tool_result_storage import cleanup_spillover_cache
+ from tools.environments.local import cleanup_terminal_temp_cache
from tools.bot_mode_dm import cleanup_bot_dm_cache
from tools.bot_relay import cleanup_bot_relay_artifacts
from hermes_cli.debug import _sweep_expired_pastes
@@ -30757,6 +30758,7 @@ def _start_gateway_housekeeping(stop_event: threading.Event, adapters=None, loop
("Video", cleanup_video_cache),
("Screenshot", cleanup_screenshot_cache),
("Spillover", cleanup_spillover_cache),
+ ("Terminal temp", cleanup_terminal_temp_cache),
("Bot DM", cleanup_bot_dm_cache),
("Bot relay", cleanup_bot_relay_artifacts),
)
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index c378d3030d0..864e9fe6899 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -383,11 +383,13 @@ DEFAULT_CONFIG = {
"degraded_mode": "warn",
"cwd": ".", # Use current directory
# Root directory for Hermes' terminal session temp files (background
- # logs/pid/exit files, code-execution sandboxes, etc.). Defaults to the
- # OS temp root. Set this to a path on real storage when /tmp is a small
- # tmpfs and Hermes runs out of space — e.g. on RAM-based tmpfs setups
- # common to some Arch-based distros. Must be an absolute POSIX path;
- # relative or empty values fall back to the default temp resolution.
+ # logs/pid/exit files, code-execution sandboxes, etc.). When empty,
+ # Hermes uses TMPDIR/TMP/TEMP if set, otherwise a managed dir on real
+ # storage at HERMES_HOME/cache/terminal (auto-pruned after 72h) — NOT
+ # tmpfs /tmp, which is RAM-capped and small on many distros (e.g.
+ # Arch-based setups) and fills up under load. Set this to redirect
+ # session temp anywhere else; must be an absolute POSIX path that
+ # exists. User-set paths are never auto-pruned.
"temp_dir": "",
# Terminal font family for the desktop app's embedded xterm.js terminal.
# When set (e.g. "'CaskaydiaCoveNerdFont', 'JetBrains Mono', monospace"),
diff --git a/tests/tools/test_local_temp_dir.py b/tests/tools/test_local_temp_dir.py
index 30a45730234..c0e79a1d20c 100644
--- a/tests/tools/test_local_temp_dir.py
+++ b/tests/tools/test_local_temp_dir.py
@@ -56,5 +56,71 @@ def test_temp_dir_empty_falls_through(tmp_path, monkeypatch):
assert env.get_temp_dir() == str(tmp_path)
+def test_default_is_hermes_cache_not_tmp(tmp_path, monkeypatch):
+ """With no overrides at all, the default temp root is real storage under
+ HERMES_HOME (cache/terminal), NOT tmpfs /tmp."""
+ import hermes_constants # noqa: F401 — resolves HERMES_HOME per call
+
+ for var in ("TERMINAL_TEMP_DIR", "TMPDIR", "TMP", "TEMP"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ env = _make_local_env({})
+ result = env.get_temp_dir()
+ assert result == str(tmp_path / ".hermes" / "cache" / "terminal")
+ assert os.path.isdir(result)
+
+
+def test_tmpdir_still_beats_default(tmp_path, monkeypatch):
+ """An explicit TMPDIR keeps winning over the managed default."""
+ monkeypatch.delenv("TERMINAL_TEMP_DIR", raising=False)
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ env = _make_local_env({})
+ assert env.get_temp_dir() == str(tmp_path)
+
+
+def test_cleanup_terminal_temp_cache(tmp_path, monkeypatch):
+ """Old artifacts are pruned; fresh ones and live bg groups survive."""
+ import time
+
+ from tools.environments import local as local_mod
+
+ root = tmp_path / "cache" / "terminal"
+ root.mkdir(parents=True)
+ monkeypatch.setattr(local_mod, "_default_terminal_temp_dir", lambda: root)
+
+ old = time.time() - 100 * 3600
+ fresh = time.time()
+
+ # Stale loose artifact — pruned.
+ stale = root / "hermes-snap-deadbeef.sh"
+ stale.write_text("x")
+ os.utime(stale, (old, old))
+
+ # Fresh artifact — kept.
+ keep = root / "hermes-snap-cafef00d.sh"
+ keep.write_text("x")
+
+ # Live bg group: stale .pid but fresh .log — WHOLE group kept.
+ live_pid = root / "hermes_bg_live1.pid"
+ live_pid.write_text("123")
+ os.utime(live_pid, (old, old))
+ live_log = root / "hermes_bg_live1.log"
+ live_log.write_text("running")
+ os.utime(live_log, (fresh, fresh))
+
+ # Dead bg group: everything stale — pruned.
+ for suffix in ("log", "pid", "exit"):
+ f = root / f"hermes_bg_dead1.{suffix}"
+ f.write_text("x")
+ os.utime(f, (old, old))
+
+ removed = local_mod.cleanup_terminal_temp_cache(max_age_hours=72)
+ assert removed == 4 # stale snap + 3 dead-group files
+ assert keep.exists()
+ assert live_pid.exists() and live_log.exists()
+ assert not stale.exists()
+ assert not (root / "hermes_bg_dead1.log").exists()
+
+
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 0ccd5a32b6b..d4792b69bac 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -10,6 +10,7 @@ import signal
import subprocess
import sys
import tempfile
+import threading
import time
from collections.abc import Mapping
from pathlib import Path
@@ -22,6 +23,105 @@ _IS_WINDOWS = platform.system() == "Windows"
logger = logging.getLogger(__name__)
+# --- Terminal temp-cache pruning -------------------------------------------
+#
+# get_temp_dir() now defaults to HERMES_HOME/cache/terminal (real storage)
+# instead of tmpfs /tmp, so stale session artifacts no longer disappear on
+# reboot for free. Prune them ourselves: the gateway housekeeping loop calls
+# cleanup_terminal_temp_cache() hourly (same contract as the other
+# cleanup_*_cache helpers), and a once-per-process best-effort sweep covers
+# CLI-only installs that never run the gateway.
+#
+# Background-process artifacts come in triplets (hermes_bg_<id>.log/.pid/
+# .exit). A long-running server's .pid file never changes mtime while its
+# .log keeps updating — so age is judged per GROUP (newest mtime among files
+# sharing a stem) to avoid yanking the pid/exit files out from under a
+# still-live background session.
+TERMINAL_TEMP_MAX_AGE_HOURS = 72
+
+_terminal_temp_prune_lock = threading.Lock()
+_terminal_temp_pruned_once = False
+
+_BG_GROUP_RE = re.compile(r"^(hermes_bg_[A-Za-z0-9_-]+)\.(log|pid|exit)$")
+
+
+def _default_terminal_temp_dir() -> "Path | None":
+ """Return HERMES_HOME/cache/terminal, or None if unresolvable."""
+ try:
+ from hermes_constants import get_hermes_home
+ return get_hermes_home() / "cache" / "terminal"
+ except Exception:
+ return None
+
+
+def cleanup_terminal_temp_cache(
+ max_age_hours: int = TERMINAL_TEMP_MAX_AGE_HOURS,
+) -> int:
+ """Delete session temp artifacts older than *max_age_hours*.
+
+ Same contract as the ``cleanup_*_cache`` helpers in
+ ``gateway.platforms.base`` — returns the number of entries removed — so
+ the gateway housekeeping loop can prune this dir on its hourly cadence.
+
+ Only prunes the managed default dir (``HERMES_HOME/cache/terminal``).
+ User-pointed ``terminal.temp_dir`` locations are the user's to manage —
+ we never bulk-delete inside a directory we don't own.
+ """
+ root = _default_terminal_temp_dir()
+ if root is None:
+ return 0
+ cutoff = time.time() - (max_age_hours * 3600)
+ removed = 0
+ try:
+ entries = list(root.iterdir())
+ except OSError:
+ return 0
+
+ # Newest mtime per hermes_bg_<id> group, so a live server's fresh .log
+ # protects its stale-looking .pid/.exit siblings.
+ group_newest: dict[str, float] = {}
+ for f in entries:
+ m = _BG_GROUP_RE.match(f.name)
+ if m:
+ try:
+ mt = f.stat().st_mtime
+ except OSError:
+ continue
+ key = m.group(1)
+ group_newest[key] = max(group_newest.get(key, 0.0), mt)
+
+ for f in entries:
+ try:
+ mt = f.stat().st_mtime
+ except OSError:
+ continue
+ m = _BG_GROUP_RE.match(f.name)
+ effective = group_newest.get(m.group(1), mt) if m else mt
+ if effective >= cutoff:
+ continue
+ try:
+ if f.is_dir():
+ shutil.rmtree(f, ignore_errors=True)
+ else:
+ f.unlink()
+ removed += 1
+ except OSError:
+ continue
+ return removed
+
+
+def _prune_terminal_temp_once() -> None:
+ """Best-effort prune, at most once per process (CLI-only installs)."""
+ global _terminal_temp_pruned_once
+ with _terminal_temp_prune_lock:
+ if _terminal_temp_pruned_once:
+ return
+ _terminal_temp_pruned_once = True
+ try:
+ cleanup_terminal_temp_cache()
+ except Exception as exc:
+ logger.debug("Terminal temp prune failed: %s", exc)
+
def _msys_to_windows_path(cwd: str) -> str:
"""Translate a Git Bash / MSYS-style POSIX path (``/c/Users/x``) to the
@@ -1764,8 +1864,19 @@ class LocalEnvironment(BaseEnvironment):
resolves to a POSIX path.
Check the environment configured for this backend first so callers can
- override the temp root explicitly (for example via terminal.env or a
- custom TMPDIR), then fall back to the host process environment.
+ override the temp root explicitly (for example via terminal.temp_dir,
+ terminal.env, or a custom TMPDIR), then fall back to the host process
+ environment.
+
+ **Default (no override set):** a dedicated cache dir under
+ ``HERMES_HOME`` (``~/.hermes/cache/terminal``) rather than ``/tmp``.
+ On several distros (Arch and friends) ``/tmp`` is a small RAM-backed
+ tmpfs, and Hermes session artifacts — background-process logs,
+ code-execution sandboxes, spilled tool results — can fill it under
+ load. Real storage is the safer default; stale artifacts are pruned
+ by ``cleanup_terminal_temp_cache`` (gateway housekeeping + a
+ once-per-process best-effort sweep) since we no longer get tmpfs
+ reboot wipes for free.
**Windows:** hardcoded ``/tmp`` is wrong in two ways — native Python
can't open the path, and the Windows default temp (``%TEMP%``) often
@@ -1786,6 +1897,7 @@ class LocalEnvironment(BaseEnvironment):
except Exception:
cache_dir = Path(tempfile.gettempdir()) / "hermes_terminal"
cache_dir.mkdir(parents=True, exist_ok=True)
+ _prune_terminal_temp_once()
# Force forward slashes so the same string serves both contexts.
return str(cache_dir).replace("\\", "/")
@@ -1801,6 +1913,20 @@ class LocalEnvironment(BaseEnvironment):
if candidate and candidate.startswith("/"):
return candidate.rstrip("/") or "/"
+ # Default: HERMES_HOME/cache/terminal — real storage, mirroring the
+ # Windows branch above. /tmp is only a last-resort fallback now
+ # because RAM-backed tmpfs /tmp fills up under Hermes load.
+ try:
+ from hermes_constants import get_hermes_home
+ cache_dir = get_hermes_home() / "cache" / "terminal"
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ resolved = str(cache_dir)
+ if resolved.startswith("/") and os.access(resolved, os.W_OK | os.X_OK):
+ _prune_terminal_temp_once()
+ return resolved.rstrip("/") or "/"
+ except Exception:
+ pass
+
if os.path.isdir("/tmp") and os.access("/tmp", os.W_OK | os.X_OK):
return "/tmp"
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index c9dee244d32..9123a5cfdfe 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -174,6 +174,7 @@ Hermes supports seven terminal backends. Each determines where the agent's shell
terminal:
backend: local # local | docker | ssh | modal | daytona | vercel_sandbox | singularity
cwd: "." # Gateway/cron working directory (CLI always uses launch dir)
+ temp_dir: "" # Session temp root; empty = TMPDIR, else ~/.hermes/cache/terminal
font_family: "" # Desktop terminal font; e.g. "MesloLGS NF"
timeout: 180 # Per-command timeout in seconds
home_mode: auto # auto | real | profile — subprocess HOME policy
@@ -183,6 +184,18 @@ terminal:
daytona_image: "nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Daytona backend
```
+`terminal.temp_dir` controls where Hermes puts session temp artifacts on the
+local backend — background-process logs/pid/exit files, code-execution
+sandboxes, and spilled tool results. When it's empty (the default), Hermes
+honors an explicit `TMPDIR`/`TMP`/`TEMP` from the environment and otherwise
+uses a managed directory on real storage at `~/.hermes/cache/terminal`
+instead of `/tmp` — on many distros (Arch-based setups in particular) `/tmp`
+is a small RAM-backed tmpfs that Hermes session artifacts can fill under
+load. The managed directory is auto-pruned: artifacts older than 72 hours are
+swept hourly by gateway housekeeping and once per process on CLI-only
+installs. Set `temp_dir` to an existing absolute path to redirect session
+temp anywhere else; user-set paths are never auto-pruned.
+
`terminal.font_family` controls the embedded terminal in Hermes Desktop. It accepts either one locally installed family name (for example, `MesloLGS NF`) or a CSS font stack. Hermes appends its bundled JetBrains Mono stack as a fallback, and an empty value keeps the default. You can edit the same profile-scoped setting in **Settings → Appearance → Terminal Font**; no Google Fonts download or system-font permission is required.
For cloud sandboxes such as Modal, Daytona, and Vercel Sandbox, `container_persistent: true` means Hermes will try to preserve filesystem state across sandbox recreation. It does not promise that the same live sandbox, PID space, or background processes will still be running later.
@@ -371,6 +384,7 @@ Every key under `terminal:` has an env-var override of the form `TERMINAL_<KEY_U
| `TERMINAL_CONTAINER_DISK` | `container_disk` | MB |
| `TERMINAL_CONTAINER_PERSISTENT` | `container_persistent` | `true` / `false` — controls the bind-mount workspace dirs, distinct from `docker_persist_across_processes` |
| `TERMINAL_LIFETIME_SECONDS` | `lifetime_seconds` | Idle reaper window |
+| `TERMINAL_TEMP_DIR` | `temp_dir` | Session temp root (local backend) |
| `TERMINAL_TIMEOUT` | `timeout` | Per-command timeout |
| `HERMES_DOCKER_BINARY` | _none_ | Force a specific docker/podman binary path |