Skip to content

The agent that grows with you

fix(terminal): make persistent_shell / TERMINAL_*_PERSISTENT actually work

Teknium89963452ee1b
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 9fa095eefc9..40ff809da2c 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -386,8 +386,8 @@ DEFAULT_CONFIG = {
"docker_snap_compat": False,
# Trusted profiles sharing one Docker container identity; empty = per-profile boundary.
"docker_shared_container_key": "",
- # Keep a long-lived bash shell across execute() calls so cwd/env/shell variables survive.
- # Applies to non-local backends (SSH); local is opt-in via TERMINAL_LOCAL_PERSISTENT env.
+ # SSH: carry exported env vars between commands (cwd always carries; plain vars/functions
+ # never do). false = each command starts from the login env. Local: TERMINAL_LOCAL_PERSISTENT.
"persistent_shell": True,
},
diff --git a/tests/tools/test_local_persistent_shell.py b/tests/tools/test_local_persistent_shell.py
new file mode 100644
index 00000000000..de2a7dece23
--- /dev/null
+++ b/tests/tools/test_local_persistent_shell.py
@@ -0,0 +1,47 @@
+"""TERMINAL_LOCAL_PERSISTENT end to end on a real local bash: on (the default) carries exported
+env vars between commands, off starts every command from the login-time env. cwd carries in
+both modes (file tools rely on it); plain shell vars never carry."""
+
+import json
+
+import pytest
+
+from tools.terminal_tool import _get_env_config, _resolve_container_task_id, terminal_tool
+from tools.terminal_tool_lifecycle import cleanup_vm
+
+
[email protected]("linux", "macos")
[email protected]("setting, exported", [(None, "yes"), ("true", "yes"), ("false", "none")])
+def test_local_persistent_controls_exports_but_cwd_always_carries(monkeypatch, tmp_path, setting, exported):
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))
+ if setting is None:
+ monkeypatch.delenv("TERMINAL_LOCAL_PERSISTENT", raising=False)
+ else:
+ monkeypatch.setenv("TERMINAL_LOCAL_PERSISTENT", setting)
+ task_id = f"local-persist-{setting}"
+ (tmp_path / "sub").mkdir()
+
+ def run(cmd):
+ return json.loads(terminal_tool(cmd, task_id=task_id))["output"].strip()
+
+ try:
+ run("cd sub && export HERMES_LP_EXPORT=yes; HERMES_LP_PLAIN=yes")
+ assert run("echo ${HERMES_LP_EXPORT:-none} ${HERMES_LP_PLAIN:-none}") == f"{exported} none"
+ assert run("pwd -P") == str((tmp_path / "sub").resolve())
+ finally:
+ cleanup_vm(_resolve_container_task_id(task_id))
+
+
+def test_local_persistent_defaults_on_and_reaches_the_environment(monkeypatch, tmp_path):
+ from tools.terminal_tool_lifecycle import _create_configured_env
+
+ monkeypatch.delenv("TERMINAL_LOCAL_PERSISTENT", raising=False)
+ config = _get_env_config()
+ assert config["local_persistent"] is True
+ env = _create_configured_env({**config, "local_persistent": False}, "local", image="", cwd=str(tmp_path),
+ timeout=30, task_id="local-persist-config", host_cwd=None)
+ try:
+ assert env._persist_env is False
+ finally:
+ env.cleanup()
diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.py
index eb6ba79ef27..b68ebf91733 100644
--- a/tests/tools/test_ssh_environment.py
+++ b/tests/tools/test_ssh_environment.py
@@ -206,6 +206,26 @@ class TestTerminalToolConfig:
from tools.terminal_tool import _get_env_config
assert _get_env_config()["ssh_persistent"] is False
+ @requires_ssh
+ @pytest.mark.parametrize("setting, expected", [(None, True), ("false", False)])
+ def test_ssh_persistent_reaches_the_environment(self, monkeypatch, setting, expected):
+ """terminal.persistent_shell (bridged to TERMINAL_PERSISTENT_SHELL) reaches SSHEnvironment."""
+ from tools.terminal_tool import _get_env_config
+ from tools.terminal_tool_lifecycle import _create_configured_env
+ _setup_ssh_env(monkeypatch, persistent=True)
+ monkeypatch.delenv("TERMINAL_SSH_PERSISTENT")
+ if setting is None:
+ monkeypatch.delenv("TERMINAL_PERSISTENT_SHELL", raising=False)
+ else:
+ monkeypatch.setenv("TERMINAL_PERSISTENT_SHELL", setting)
+ config = _get_env_config()
+ env = _create_configured_env(config, "ssh", image="", cwd="~", timeout=30,
+ task_id="ssh-persist-config", host_cwd=None)
+ try:
+ assert env._persist_env is expected
+ finally:
+ env.cleanup()
+
class TestSSHPreflight:
def test_ensure_ssh_available_raises_clear_error_when_missing(self, monkeypatch):
@@ -342,14 +362,12 @@ class TestOneShotSSH:
assert "hello" in r["output"]
- @pytest.mark.xfail(strict=True, reason=(
- "TERMINAL_SSH_PERSISTENT=false is a dead knob: _get_env_config() reads it into "
- "ssh_config['persistent'], but SSHEnvironment never takes it since the spawn-per-call "
- "rewrite, so every SSH session persists exported env through its snapshot."))
def test_state_does_not_persist(self):
- _run("export HERMES_ONESHOT_TEST=yes")
- r = _run("echo $HERMES_ONESHOT_TEST")
- assert r["output"].strip() == ""
+ """Exports stay in their own command; cwd still carries (file tools rely on it)."""
+ home = _run("pwd")["output"].strip()
+ _run("mkdir -p oneshot && cd oneshot && export HERMES_ONESHOT_TEST=yes")
+ r = _run("echo ${HERMES_ONESHOT_TEST:-unset}; pwd")
+ assert r["output"].split() == ["unset", f"{home}/oneshot"]
@requires_ssh
diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py
index bb03874653f..2198c5ab711 100644
--- a/tools/code_execution_tool.py
+++ b/tools/code_execution_tool.py
@@ -405,7 +405,8 @@ def _call(tool_name, args):
def _get_or_create_env(task_id: str):
"""``(env, env_type)`` — the environment the terminal/file tools share for *task_id*, created on
first use (same double-checked per-task lock pattern as file_tools._get_file_ops)."""
- from tools.terminal_tool_backends import _container_config_from_config, _create_environment, _ssh_config_from_config
+ from tools.terminal_tool_backends import (_container_config_from_config, _create_environment,
+ _local_config_from_config, _ssh_config_from_config)
from tools.terminal_tool import (
_active_environments, _env_lock, _get_env_config, _last_activity,
_start_cleanup_thread, _creation_locks, _creation_locks_lock, _task_env_overrides,
@@ -442,7 +443,7 @@ def _get_or_create_env(task_id: str):
cwd=overrides.get("cwd") or config["cwd"], timeout=config["timeout"],
ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None,
container_config=container_config,
- local_config={"persistent": config.get("local_persistent", False)} if env_type == "local" else None,
+ local_config=_local_config_from_config(config) if env_type == "local" else None,
task_id=effective_task_id, host_cwd=_resolve_task_host_cwd(config, task_id),
)
with _env_lock:
diff --git a/tools/environments/base.py b/tools/environments/base.py
index c550081e1c5..0a3cc4c3d20 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -240,6 +240,9 @@ class BaseEnvironment(ABC):
# Snapshot creation timeout (override for slow cold-starts).
_snapshot_timeout: int = 30
+ # Re-dump exported env into the snapshot after each command (see __init__).
+ _persist_env: bool = True
+
# Opt in only when a timed-out probe can kill its command without tearing
# down the whole backend. SDK adapters cancel by stopping the sandbox.
_sudo_nopasswd_probe_supported: bool = False
@@ -257,10 +260,13 @@ class BaseEnvironment(ABC):
"""
return "/tmp" # no-tmp: ok — sandbox-side (remote container) temp dir, not the host
- def __init__(self, cwd: str, timeout: int, env: dict | None = None):
+ def __init__(self, cwd: str, timeout: int, env: dict | None = None, persist_env: bool = True):
self.cwd = cwd
self.timeout = timeout
self.env = env or {}
+ # False: each command sources only the login-time snapshot, so exported vars do not
+ # carry over (terminal.persistent_shell / TERMINAL_LOCAL_PERSISTENT). CWD still does.
+ self._persist_env = persist_env
self._session_id = uuid.uuid4().hex[:12]
temp_dir = self.get_temp_dir().rstrip("/") or "/"
@@ -420,6 +426,7 @@ class BaseEnvironment(ABC):
command,
passthrough_names=self._snapshot_excluded_passthrough_names(),
snapshot_ready=self._snapshot_ready,
+ persist_env=self._persist_env,
**self._snapshot_script_kwargs(cwd))
@staticmethod
diff --git a/tools/environments/base_session_env.py b/tools/environments/base_session_env.py
index 64fb24c99ef..3b5630b1174 100644
--- a/tools/environments/base_session_env.py
+++ b/tools/environments/base_session_env.py
@@ -131,8 +131,11 @@ def _passthrough_save_restore(names: Iterable[str]) -> tuple[list[str], list[str
def _wrap_command_script(
command: str, *, quoted_cwd: str, quoted_snap: str, snap_tmp_template: str,
- passthrough_names: Iterable[str], snapshot_ready: bool, cwd_marker: str) -> str:
+ passthrough_names: Iterable[str], snapshot_ready: bool, cwd_marker: str,
+ persist_env: bool = True) -> str:
"""Per-command bash script: source snapshot, cd, run, re-dump env, emit CWD marker.
+ ``persist_env=False`` skips the re-dump, so every command starts from the login-time
+ snapshot and exports from one command never reach the next (the CWD marker still runs).
``source`` stdout goes to /dev/null because macOS bash 3.2 / some Homebrew builds echo
``declare -x`` lines when sourcing. AI_AGENT/HERMES_AGENT advertise the harness to remote
backends (whose env is not inherited); ``${VAR:-default}`` never clobbers an outer harness.
@@ -156,7 +159,7 @@ def _wrap_command_script(
f"eval '{escaped}'",
"__hermes_ec=$?",
"umask 077"]
- if snapshot_ready:
+ if snapshot_ready and persist_env:
parts.append(
f"__hermes_snap_tmp=$(mktemp {snap_tmp_template}) && "
f"{{ {_export_dump_excluding_session_vars(_SNAP_TMP, passthrough_names)} "
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 41a7c16229c..5a9d39af73b 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -967,8 +967,8 @@ def _kill_process_windows(proc) -> None:
class LocalEnvironment(BaseEnvironment):
"""Run commands directly on the host: every execute() spawns a fresh bash;
- the session snapshot preserves env vars across calls; CWD persists via the
- stdout marker."""
+ the session snapshot preserves exported env vars across calls (unless
+ ``persistent=False``); CWD persists via the stdout marker."""
_sudo_nopasswd_probe_supported = True
_profile_scoped_passthrough = True
@@ -987,8 +987,8 @@ class LocalEnvironment(BaseEnvironment):
name for name in merged
if isinstance(name, str) and _matches_terminal_first_party_prefix(name)))
- def __init__(self, cwd: str = "", timeout: int = 60, env: dict | None = None):
- super().__init__(cwd=_resolve_local_initial_cwd(cwd), timeout=timeout, env=env)
+ def __init__(self, cwd: str = "", timeout: int = 60, env: dict | None = None, persistent: bool = True):
+ super().__init__(cwd=_resolve_local_initial_cwd(cwd), timeout=timeout, env=env, persist_env=persistent)
self.init_session()
def get_temp_dir(self) -> str:
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index 12dc717e589..1ece284eb5b 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -46,7 +46,8 @@ class SSHEnvironment(BaseEnvironment):
"""Run commands on a remote machine over SSH.
Spawn-per-call: every execute() spawns a fresh ``ssh ... bash -c`` process.
- Session snapshot preserves env vars across calls; CWD persists via in-band
+ Session snapshot preserves exported env vars across calls (unless
+ ``persistent=False``); CWD persists via in-band
stdout markers. Uses SSH ControlMaster for connection reuse.
"""
@@ -57,8 +58,8 @@ class SSHEnvironment(BaseEnvironment):
def __init__(self, host: str, user: str, cwd: str = "~",
timeout: int = 60, port: int = 22, key_path: str = "",
- probe_only: bool = False, sync_files: bool = True):
- super().__init__(cwd=cwd, timeout=timeout)
+ probe_only: bool = False, sync_files: bool = True, persistent: bool = True):
+ super().__init__(cwd=cwd, timeout=timeout, persist_env=persistent)
self.host, self.user, self.port, self.key_path = host, user, port, key_path
self.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"
self.control_dir.mkdir(parents=True, exist_ok=True)
diff --git a/tools/file_tools.py b/tools/file_tools.py
index f334d8b0d3f..237d97d87e6 100644
--- a/tools/file_tools.py
+++ b/tools/file_tools.py
@@ -306,7 +306,6 @@ def _create_terminal_env_for_file_ops(raw_task_id: str, task_id: str):
config, env_type, image=_select_image(env_type, overrides, config), cwd=cwd,
timeout=config["timeout"], task_id=task_id,
host_cwd=host_cwd,
- local_config={"persistent": config.get("local_persistent", False)} if env_type == "local" else None,
)
return env_type, terminal_env
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 410d94f7a43..17d280988f4 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -762,12 +762,12 @@ def _get_env_config() -> dict[str, Any]:
"ssh_user": _tenv("TERMINAL_SSH_USER", ""),
"ssh_port": _parse_env_var("TERMINAL_SSH_PORT", "22"),
"ssh_key": _tenv("TERMINAL_SSH_KEY", ""),
- # Persistent shell: SSH defaults to the config-level persistent_shell
- # setting; local is always opt-in. Per-backend env vars override.
+ # Exported env carries across commands (cwd always does). SSH follows
+ # terminal.persistent_shell; local has its own knob. Both default on.
"ssh_persistent": _tenv_bool(
"TERMINAL_SSH_PERSISTENT", _tenv("TERMINAL_PERSISTENT_SHELL", "true"),
),
- "local_persistent": _tenv_bool("TERMINAL_LOCAL_PERSISTENT", "false"),
+ "local_persistent": _tenv_bool("TERMINAL_LOCAL_PERSISTENT", "true"),
# Container resources (MB); ignored for local/ssh.
"container_cpu": container_cpu,
"container_memory": container_memory,
@@ -1213,10 +1213,6 @@ def _acquire_env(plan: _ExecPlan, task_id: Optional[str]) -> Any:
new_env = _create_configured_env(
plan.config, env_type, image=plan.image, cwd=plan.cwd,
timeout=plan.effective_timeout, task_id=eff, host_cwd=plan.host_cwd,
- local_config=(
- {"persistent": plan.config.get("local_persistent", False)}
- if env_type == "local" else None
- ),
)
except ImportError as e:
raise _Rejected(_error_json(
diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.py
index 0d1130cc682..c3230af339a 100644
--- a/tools/terminal_tool_backends.py
+++ b/tools/terminal_tool_backends.py
@@ -56,7 +56,7 @@ _BUILTIN_BACKENDS = "local, docker, singularity, modal, daytona, vercel_sandbox,
# Config -> kwargs shapers, driven by (out_key, config_key, default) tables. The container table's
# (key, default) literal is intentionally greppable; tools/terminal_tool.py keeps its own for the AST test.
_SSH_KEYS = (("host", "ssh_host", ""), ("user", "ssh_user", ""), ("port", "ssh_port", 22),
- ("key", "ssh_key", ""), ("persistent", "ssh_persistent", False))
+ ("key", "ssh_key", ""), ("persistent", "ssh_persistent", True))
_RESOURCE_KEYS = (("cpu", "container_cpu", 1), ("memory", "container_memory", 5120),
("disk", "container_disk", 51200), ("persistent_filesystem", "container_persistent", True))
_CONTAINER_KEYS = (
@@ -83,6 +83,11 @@ def _ssh_config_from_config(config: dict[str, Any]) -> dict:
return {out: config.get(key, default) for out, key, default in _SSH_KEYS}
+def _local_config_from_config(config: dict[str, Any]) -> dict:
+ """``local_config`` for :func:`_create_environment` (TERMINAL_LOCAL_PERSISTENT, default on)."""
+ return {"persistent": config.get("local_persistent", True)}
+
+
def _container_config_from_config(config: dict[str, Any]) -> dict:
"""``container_config`` for :func:`_create_environment` (shared with the lazy ``ensure_task_env``)."""
return {k: config.get(k, d) for k, d in _CONTAINER_KEYS}
@@ -125,10 +130,10 @@ def _modal_unavailable_reason(modal_state: dict[str, Any]) -> tuple[str, str]:
f"Modal backend selected but no direct Modal credentials/config {found}.")
-# --- Environment builders. Signature: (*, image, cwd, timeout, cc, task_id, ssh_config, host_cwd)
+# --- Environment builders. Signature: (*, image, cwd, timeout, cc, task_id, ssh_config, local_config, host_cwd)
# (env_type is only forwarded to the plugin-registry fallback, not to the built-in builders.)
-def _build_local_env(*, cwd, timeout, **_):
- return _LocalEnvironment(cwd=cwd, timeout=timeout)
+def _build_local_env(*, cwd, timeout, local_config=None, **_):
+ return _LocalEnvironment(cwd=cwd, timeout=timeout, persistent=(local_config or {}).get("persistent", True))
def _build_docker_env(*, image, cwd, timeout, cc, task_id, host_cwd, **_):
@@ -205,7 +210,8 @@ def _build_ssh_env(*, cwd, timeout, ssh_config, probe_only=False, **_):
if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"):
raise ValueError("SSH environment requires ssh_host and ssh_user to be configured")
return _SSHEnvironment(host=ssh_config["host"], user=ssh_config["user"], port=ssh_config.get("port", 22),
- key_path=ssh_config.get("key", ""), cwd=cwd, timeout=timeout, probe_only=probe_only)
+ key_path=ssh_config.get("key", ""), cwd=cwd, timeout=timeout, probe_only=probe_only,
+ persistent=ssh_config.get("persistent", True))
def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_):
@@ -245,7 +251,7 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int,
connection with no remote setup/sync (the prompt-time probe). Unknown types fall through to plugin backends."""
builder = _ENV_BUILDERS.get(env_type)
kwargs = dict(image=image, cwd=cwd, timeout=timeout, cc=container_config or {}, task_id=task_id,
- ssh_config=ssh_config, host_cwd=host_cwd, probe_only=probe_only)
+ ssh_config=ssh_config, local_config=local_config, host_cwd=host_cwd, probe_only=probe_only)
if builder is not None:
env = builder(**kwargs)
else:
diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.py
index baf217566f2..59d3646f59e 100644
--- a/tools/terminal_tool_lifecycle.py
+++ b/tools/terminal_tool_lifecycle.py
@@ -18,6 +18,7 @@ from typing import Any, Dict, Optional
from tools.environments.singularity import _get_scratch_dir
from tools.terminal_tool_backends import (
_container_config_from_config,
+ _local_config_from_config,
_ssh_config_from_config,
)
from tools.terminal_tool_config import _quiet
@@ -65,10 +66,10 @@ def _check_disk_usage_warning():
def _create_configured_env(
config: dict[str, Any], env_type: str, *, image: str, cwd: str, timeout: int,
- task_id: str, host_cwd: Optional[str], local_config: Optional[dict] = None,
+ task_id: str, host_cwd: Optional[str],
):
- """``_create_environment`` with the ssh/container kwargs shaped from *config*
- (shared by the terminal tool and the lazy :func:`ensure_task_env` bring-up)."""
+ """``_create_environment`` with the ssh/local/container kwargs shaped from *config*
+ (shared by the terminal tool, the file tools and the lazy :func:`ensure_task_env` bring-up)."""
from tools.terminal_tool_backends import _create_environment
from tools.terminal_tool_config import _is_container_backend
return _create_environment(
@@ -77,7 +78,8 @@ def _create_configured_env(
container_config=(
_container_config_from_config(config) if _is_container_backend(env_type) else None
),
- local_config=local_config, task_id=task_id, host_cwd=host_cwd,
+ local_config=_local_config_from_config(config) if env_type == "local" else None,
+ task_id=task_id, host_cwd=host_cwd,
)
diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md
index 691c06571d4..2367cd40e15 100644
--- a/website/docs/reference/environment-variables.md
+++ b/website/docs/reference/environment-variables.md
@@ -275,7 +275,6 @@ For cloud sandbox backends, persistence is filesystem-oriented. `TERMINAL_LIFETI
| `TERMINAL_SSH_USER` | SSH username |
| `TERMINAL_SSH_PORT` | SSH port (default: 22) |
| `TERMINAL_SSH_KEY` | Path to private key |
-| `TERMINAL_SSH_PERSISTENT` | Override persistent shell for SSH (default: follows `TERMINAL_PERSISTENT_SHELL`) |
## Container Resources (Docker, Singularity, Modal, Daytona)
@@ -289,11 +288,13 @@ For cloud sandbox backends, persistence is filesystem-oriented. `TERMINAL_LIFETI
## Persistent Shell
+Exported env vars carry from one command to the next while on; the working directory always carries. See [Persistent Shell](../user-guide/configuration.md#persistent-shell).
+
| Variable | Description |
|----------|-------------|
-| `TERMINAL_PERSISTENT_SHELL` | Enable persistent shell for non-local backends (default: `true`). Also settable via `terminal.persistent_shell` in config.yaml |
-| `TERMINAL_LOCAL_PERSISTENT` | Enable persistent shell for local backend (default: `false`) |
-| `TERMINAL_SSH_PERSISTENT` | Override persistent shell for SSH backend (default: follows `TERMINAL_PERSISTENT_SHELL`) |
+| `TERMINAL_PERSISTENT_SHELL` | SSH backend: carry exported env vars between commands (default: `true`). Also settable via `terminal.persistent_shell` in config.yaml |
+| `TERMINAL_SSH_PERSISTENT` | SSH backend override; wins over `TERMINAL_PERSISTENT_SHELL` (default: follows it) |
+| `TERMINAL_LOCAL_PERSISTENT` | Local backend: carry exported env vars between commands (default: `true`) |
## Egress proxy (sandbox-injected)
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index fef1919ef0b..a7bbbf01f88 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -470,12 +470,12 @@ Every key under `terminal:` has an env-var override of the form `TERMINAL_<KEY_U
### SSH Backend
-Runs commands on a remote server over SSH. Uses ControlMaster for connection reuse (5-minute idle keepalive). Persistent shell is enabled by default — state (cwd, env vars) survives across commands.
+Runs commands on a remote server over SSH. Uses ControlMaster for connection reuse (5-minute idle keepalive). Each command is a fresh `ssh … bash -c`; the working directory always carries over, and exported environment variables carry over while `persistent_shell` is on (the default). See [Persistent Shell](#persistent-shell).
```yaml
terminal:
backend: ssh
- persistent_shell: true # Keep a long-lived bash session (default: true)
+ persistent_shell: true # Carry exported env vars between commands (default: true)
```
**Required environment variables:**
@@ -491,9 +491,9 @@ TERMINAL_SSH_USER=ubuntu
|----------|---------|-------------|
| `TERMINAL_SSH_PORT` | `22` | SSH port |
| `TERMINAL_SSH_KEY` | (system default) | Path to SSH private key |
-| `TERMINAL_SSH_PERSISTENT` | `true` | Enable persistent shell |
+| `TERMINAL_SSH_PERSISTENT` | follows `terminal.persistent_shell` (`true`) | Carry exported env vars between commands |
-**How it works:** Connects at init time with `BatchMode=yes` and `StrictHostKeyChecking=accept-new`. Persistent shell keeps a single `bash -l` process alive on the remote host, communicating via temporary files. Commands that need `stdin_data` or `sudo` automatically fall back to one-shot mode.
+**How it works:** Connects at init time with `BatchMode=yes` and `StrictHostKeyChecking=accept-new`, then captures the remote login shell's environment once into a snapshot file. Every command runs as a fresh `bash -c` that sources that snapshot, `cd`s to the tracked working directory, and runs your command.
**Skill / config env passthrough:** variables a skill declares in `required_environment_variables`, or that you list under `terminal.env_passthrough`, are forwarded with OpenSSH `SendEnv` — the names go on the `ssh` command line and the values travel in the client's environment, never in the remote command text. The remote `sshd` must accept them; add to `/etc/ssh/sshd_config` on the server and reload sshd:
@@ -742,43 +742,33 @@ A host path in `terminal.cwd` (for example `C:\Users\me\project` on Windows, or
### Persistent Shell
-By default, each terminal command runs in its own subprocess — working directory, environment variables, and shell variables reset between commands. When **persistent shell** is enabled, a single long-lived bash process is kept alive across `execute()` calls so that state survives between commands.
+Every terminal command on the **local** and **SSH** backends runs in a fresh `bash` process. Hermes captures your login shell's environment once (PATH, exports from your profile, functions, aliases) and every command starts from that snapshot. The persistence setting decides whether **exported environment variables** set by one command reach the next.
-This is most useful for the **SSH backend**, where it also eliminates per-command connection overhead. Persistent shell is **enabled by default for SSH** and disabled for the local backend.
+| What | Setting on (default) | Setting off |
+|------|----------------------|-------------|
+| Working directory (`cd ~/project`) | carries over | carries over |
+| Exported env vars (`export FOO=bar`) | carry over | reset to the login environment |
+| Plain shell vars (`MY_VAR=hello`) | do **not** carry over | do not carry over |
+| Functions / aliases defined mid-session | do **not** carry over | do not carry over |
+| Login environment (PATH, profile exports) | always present | always present |
-```yaml
-terminal:
- persistent_shell: true # default — enables persistent shell for SSH
-```
+The working directory always carries over because the file tools resolve relative paths against it. To make a variable stick in either mode, `export` it (setting on) or put it in your shell profile or `terminal.env_passthrough`.
-To disable:
+The SSH backend reads `terminal.persistent_shell`; the local backend has its own switch. Both default to on. To make each command start from the login environment:
```bash
-hermes config set terminal.persistent_shell false
+hermes config set terminal.persistent_shell false # SSH
+export TERMINAL_LOCAL_PERSISTENT=false # local
```
-**What persists across commands:**
-- Working directory (`cd ~/project` sticks for the next command)
-- Exported environment variables (`export FOO=bar`)
-- Shell variables (`MY_VAR=hello`)
-
**Precedence:**
-| Level | Variable | Default |
-|-------|----------|---------|
-| Config | `terminal.persistent_shell` | `true` |
-| SSH override | `TERMINAL_SSH_PERSISTENT` | follows config |
-| Local override | `TERMINAL_LOCAL_PERSISTENT` | `false` |
-
-Per-backend environment variables take highest precedence. If you want persistent shell on the local backend too:
+| Backend | Variable | Default |
+|---------|----------|---------|
+| SSH | `TERMINAL_SSH_PERSISTENT`, else `terminal.persistent_shell` (`TERMINAL_PERSISTENT_SHELL`) | `true` |
+| Local | `TERMINAL_LOCAL_PERSISTENT` | `true` |
-```bash
-export TERMINAL_LOCAL_PERSISTENT=true
-```
-
-:::note
-Commands that require `stdin_data` or sudo automatically fall back to one-shot mode, since the persistent shell's stdin is already occupied by the IPC protocol.
-:::
+Docker, Singularity, Modal, Daytona, Vercel Sandbox and plugin backends ignore these settings.
See [Code Execution](features/code-execution.md) and the [Terminal section of the README](features/tools.md) for details on each backend.