Skip to content

The agent that grows with you

fix(gateway): configure turn lease timeout via yaml

texasichb3e9e91709a5
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 3b76ba4a8a2..09b33164f89 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -826,6 +826,12 @@ agent:
# API responses. Only fires after the agent has been idle for this duration.
# gateway_timeout: 1800
+ # Maximum time an alias routing key waits for an active turn holding the same
+ # resolved session lease. On expiry Hermes rejects this inbound message and
+ # asks the user to resend rather than running it without serialization.
+ # Non-positive values fall back to the 1800-second default.
+ # gateway_turn_lease_timeout: 1800
+
# Staged warning: send a warning before escalating to full timeout.
# Fires once per run when inactivity reaches this threshold (seconds).
# Set to 0 to disable the warning.
diff --git a/gateway/run.py b/gateway/run.py
index e17721c091a..9064ed001f9 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2029,6 +2029,15 @@ def _platform_has_bot_credential(platform: "Platform", platform_config: "Platfor
_DOCKER_VOLUME_SPEC_RE = re.compile(r"^(?P<host>.+):(?P<container>/[^:]+?)(?::(?P<options>[^:]+))?$")
_DOCKER_MEDIA_OUTPUT_CONTAINER_PATHS = {"/output", "/outputs"}
+# This env var is internal bridge plumbing, not a user-facing configuration
+# source. Initialize it from the canonical config default after dotenv loading
+# so an ambient process/.env value can never control lease safety on its own.
+from hermes_cli.config_defaults import DEFAULT_CONFIG as _DEFAULT_CONFIG
+
+os.environ["HERMES_TURN_LEASE_TIMEOUT"] = str(
+ _DEFAULT_CONFIG["agent"]["gateway_turn_lease_timeout"]
+)
+
# Bridge config.yaml values into the environment so os.getenv() picks them up.
# config.yaml is authoritative for terminal settings — overrides .env.
_config_path = _hermes_home / 'config.yaml'
@@ -2173,6 +2182,10 @@ if _config_path.exists():
os.environ["HERMES_MAX_ITERATIONS"] = str(_agent_cfg["max_turns"])
if "gateway_timeout" in _agent_cfg:
os.environ["HERMES_AGENT_TIMEOUT"] = str(_agent_cfg["gateway_timeout"])
+ if "gateway_turn_lease_timeout" in _agent_cfg:
+ os.environ["HERMES_TURN_LEASE_TIMEOUT"] = str(
+ _agent_cfg["gateway_turn_lease_timeout"]
+ )
if "gateway_timeout_warning" in _agent_cfg:
os.environ["HERMES_AGENT_TIMEOUT_WARNING"] = str(_agent_cfg["gateway_timeout_warning"])
if "gateway_notify_interval" in _agent_cfg:
diff --git a/gateway/turn_lease.py b/gateway/turn_lease.py
index 26688fdc68d..23053d39ef6 100644
--- a/gateway/turn_lease.py
+++ b/gateway/turn_lease.py
@@ -62,9 +62,10 @@ logger = logging.getLogger(__name__)
DEFAULT_MAX_LEASES = 512
# Fallback wait (seconds) when the caller passes no positive timeout. The
-# gateway exposes this independently as HERMES_TURN_LEASE_TIMEOUT because lease
-# contention is not agent inactivity. A caller that reaches this bound must
-# reject the turn rather than run it concurrently with the holder.
+# gateway carries this independently through its internal
+# HERMES_TURN_LEASE_TIMEOUT bridge because lease contention is not agent
+# inactivity. A caller that reaches this bound must reject the turn rather than
+# run it concurrently with the holder.
DEFAULT_LEASE_WAIT = 1800.0
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 41c493383ba..01fe5bfe0fc 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -35,6 +35,11 @@ DEFAULT_CONFIG = {
# tools or receiving API responses. Only fires when the agent has
# been completely idle for this duration. 0 = unlimited.
"gateway_timeout": 1800,
+ # Maximum time an alias routing key waits for the active turn holding
+ # the same resolved session lease. On expiry the inbound message is
+ # rejected with a resend notice rather than run without serialization.
+ # Non-positive values fall back to 1800 seconds.
+ "gateway_turn_lease_timeout": 1800,
# Force-interrupt budget once gateway stop()/drain has begun
# (seconds). Applies to SIGTERM/external stop and to the final
# phase of in-band restart after any after-turn wait. 0 = interrupt
diff --git a/tests/gateway/test_config_env_bridge_authority.py b/tests/gateway/test_config_env_bridge_authority.py
index 35e277664dc..20a30246410 100644
--- a/tests/gateway/test_config_env_bridge_authority.py
+++ b/tests/gateway/test_config_env_bridge_authority.py
@@ -21,7 +21,9 @@ import pytest
PROJECT_ROOT = Path(__file__).resolve().parents[2]
-def _run_gateway_import(hermes_home: Path, initial_env: dict[str, str]) -> dict[str, str]:
+def _run_gateway_import(
+ hermes_home: Path, initial_env: dict[str, str]
+) -> dict[str, str]:
"""Import gateway.run in a clean subprocess and return the post-import env.
The bridge runs at module-import time, so simply importing is enough
@@ -44,6 +46,7 @@ def _run_gateway_import(hermes_home: Path, initial_env: dict[str, str]) -> dict[
"HERMES_MAX_ITERATIONS",
"HERMES_AGENT_TIMEOUT",
"HERMES_AGENT_TIMEOUT_WARNING",
+ "HERMES_TURN_LEASE_TIMEOUT",
"HERMES_SESSION_STALL_TIMEOUT",
"HERMES_GATEWAY_BUSY_INPUT_MODE",
"HERMES_GATEWAY_BUSY_TEXT_MODE",
@@ -57,8 +60,23 @@ def _run_gateway_import(hermes_home: Path, initial_env: dict[str, str]) -> dict[
)
env = dict(initial_env)
env["HERMES_HOME"] = str(hermes_home)
- # Keep PATH / PYTHONPATH so venv imports resolve.
- for k in ("PATH", "PYTHONPATH", "VIRTUAL_ENV", "HOME"):
+ # Keep interpreter paths plus the Windows bootstrap variables required by
+ # stdlib platform detection and native dependency loading. The child is
+ # otherwise intentionally clean so stale Hermes settings cannot leak in.
+ for k in (
+ "PATH",
+ "PYTHONPATH",
+ "VIRTUAL_ENV",
+ "HOME",
+ "USERPROFILE",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "LOCALAPPDATA",
+ "APPDATA",
+ "SYSTEMROOT",
+ "TEMP",
+ "TMP",
+ ):
if k in os.environ and k not in env:
env[k] = os.environ[k]
@@ -82,9 +100,15 @@ def _run_gateway_import(hermes_home: Path, initial_env: dict[str, str]) -> dict[
return out
-def _write_config(home: Path, agent_cfg: dict | None = None, display_cfg: dict | None = None,
- timezone: str | None = None, gateway_cfg: dict | None = None) -> None:
+def _write_config(
+ home: Path,
+ agent_cfg: dict | None = None,
+ display_cfg: dict | None = None,
+ timezone: str | None = None,
+ gateway_cfg: dict | None = None,
+) -> None:
import yaml
+
cfg: dict = {}
if agent_cfg:
cfg["agent"] = agent_cfg
@@ -94,12 +118,12 @@ def _write_config(home: Path, agent_cfg: dict | None = None, display_cfg: dict |
cfg["gateway"] = gateway_cfg
if timezone:
cfg["timezone"] = timezone
- (home / "config.yaml").write_text(yaml.safe_dump(cfg))
+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")
def _write_env(home: Path, entries: dict[str, str]) -> None:
lines = [f"{k}={v}\n" for k, v in entries.items()]
- (home / ".env").write_text("".join(lines))
+ (home / ".env").write_text("".join(lines), encoding="utf-8")
@pytest.fixture
@@ -111,16 +135,22 @@ def hermes_home(tmp_path: Path) -> Path:
def test_config_gateway_timeout_wins_over_stale_env(hermes_home: Path) -> None:
"""Every agent.* bridge key must be config-authoritative, not .env-authoritative."""
- _write_config(hermes_home, agent_cfg={
- "gateway_timeout": 1800,
- "gateway_timeout_warning": 900,
- "session_stall_timeout": 300,
- })
- _write_env(hermes_home, {
- "HERMES_AGENT_TIMEOUT": "60",
- "HERMES_AGENT_TIMEOUT_WARNING": "30",
- "HERMES_SESSION_STALL_TIMEOUT": "15",
- })
+ _write_config(
+ hermes_home,
+ agent_cfg={
+ "gateway_timeout": 1800,
+ "gateway_timeout_warning": 900,
+ "session_stall_timeout": 300,
+ },
+ )
+ _write_env(
+ hermes_home,
+ {
+ "HERMES_AGENT_TIMEOUT": "60",
+ "HERMES_AGENT_TIMEOUT_WARNING": "30",
+ "HERMES_SESSION_STALL_TIMEOUT": "15",
+ },
+ )
env = _run_gateway_import(hermes_home, initial_env={})
@@ -129,7 +159,46 @@ def test_config_gateway_timeout_wins_over_stale_env(hermes_home: Path) -> None:
assert env.get("HERMES_SESSION_STALL_TIMEOUT") == "300"
-def test_config_platform_connect_timeout_supplies_env_when_unset(hermes_home: Path) -> None:
+def test_config_turn_lease_timeout_wins_over_stale_env(hermes_home: Path) -> None:
+ """The user-facing lease wait budget belongs to config.yaml."""
+ _write_config(
+ hermes_home,
+ agent_cfg={"gateway_turn_lease_timeout": 600},
+ )
+ _write_env(
+ hermes_home,
+ {"HERMES_TURN_LEASE_TIMEOUT": "60"},
+ )
+
+ env = _run_gateway_import(hermes_home, initial_env={})
+
+ assert env.get("HERMES_TURN_LEASE_TIMEOUT") == "600"
+
+
+def test_default_turn_lease_timeout_overrides_stale_env_when_key_is_omitted(
+ hermes_home: Path,
+) -> None:
+ """The internal env mirror must never become a second config source."""
+ _write_env(
+ hermes_home,
+ {"HERMES_TURN_LEASE_TIMEOUT": "60"},
+ )
+
+ env = _run_gateway_import(hermes_home, initial_env={})
+
+ assert env.get("HERMES_TURN_LEASE_TIMEOUT") == "1800"
+
+
+def test_default_turn_lease_timeout_matches_the_runtime_fallback() -> None:
+ """The advertised config default must match the fail-closed runtime."""
+ from hermes_cli.config import DEFAULT_CONFIG
+
+ assert DEFAULT_CONFIG["agent"]["gateway_turn_lease_timeout"] == 1800
+
+
+def test_config_platform_connect_timeout_supplies_env_when_unset(
+ hermes_home: Path,
+) -> None:
"""config.yaml:gateway.platform_connect_timeout supplies the env var when
it isn't already set (#19776 — config surface for the Discord connect
timeout, replacing the undocumented env-var-only workaround)."""
diff --git a/tests/gateway/test_turn_lease.py b/tests/gateway/test_turn_lease.py
index 5f25b1f4369..aeb26530773 100644
--- a/tests/gateway/test_turn_lease.py
+++ b/tests/gateway/test_turn_lease.py
@@ -102,6 +102,7 @@ def test_timeout_fails_closed_instead_of_authorizing_an_unserialized_turn():
The two turns could then load the same history base and interleave their
transcript writes, defeating the serialization invariant this lease owns.
"""
+
async def scenario():
registry = SessionTurnLeaseRegistry()
holder = await registry.acquire(
@@ -226,7 +227,9 @@ def test_rebind_moves_serialization_to_new_session_id():
async def scenario():
registry = SessionTurnLeaseRegistry()
- token = await registry.acquire("parent", owner_key="key-a", generation=1, timeout=5)
+ token = await registry.acquire(
+ "parent", owner_key="key-a", generation=1, timeout=5
+ )
assert registry.rebind(token, "child") is True
assert token is not None and token.session_id == "child"
diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md
index 7ee3b7de797..bae4a6166c2 100644
--- a/website/docs/reference/environment-variables.md
+++ b/website/docs/reference/environment-variables.md
@@ -805,7 +805,6 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us
| `HERMES_STREAM_RETRIES` | Number of mid-stream reconnect attempts on transient network errors (default: `3`). |
| `HERMES_STREAM_STALE_GIVEUP` | Cross-turn circuit breaker: after this many consecutive stale kills (streaming or non-streaming) with no completed response, abort each call immediately with an actionable error instead of re-waiting out the stale timeout (default: `5`, `0` disables). Resets on any completed response, `/model` switch, fallback activation, or turn-start primary restore. |
| `HERMES_AGENT_TIMEOUT` | Gateway inactivity timeout for a running agent in seconds (default: `1800`, 30 minutes). Resets on every tool call and streamed token. Set to `0` to disable. |
-| `HERMES_TURN_LEASE_TIMEOUT` | Maximum time in seconds an alias routing key waits for the active turn on the same resolved session before Hermes rejects the message with a resend notice (default: `1800`). This is independent of agent inactivity; non-positive values use the default. |
| `HERMES_GATEWAY_MAX_STARTS` | Respawn-storm circuit breaker: maximum gateway (re)starts allowed within the window before an exponential backoff is slept to break the storm (default: `5`, `0` disables). Also configurable via `gateway.respawn_storm.max_starts` in `config.yaml`. |
| `HERMES_GATEWAY_START_WINDOW_S` | Respawn-storm breaker window in seconds (default: `120`). Also configurable via `gateway.respawn_storm.window_seconds` in `config.yaml`. |
| `HERMES_AGENT_TIMEOUT_WARNING` | Gateway: send a warning message after this many seconds of inactivity (default: 75% of `HERMES_AGENT_TIMEOUT`). |
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index a8e9e44386a..9db34761afa 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -883,6 +883,24 @@ Points at a custom OpenAI-compatible endpoint. Uses `OPENAI_API_KEY` for auth.
The summary model **must** have a context window at least as large as your main agent model's. The compressor sends the full middle section of the conversation to the summary model — if that model's context window is smaller than the main model's, the summarization call will fail with a context length error. When this happens, the middle turns are **dropped without a summary**, losing conversation context silently. If you override the model, verify its context length meets or exceeds your main model's.
:::
+## Gateway Turn Lease Timeout
+
+The gateway serializes turns by their resolved session ID so two routing keys
+cannot load and write the same transcript concurrently. Configure the maximum
+lease wait independently of the ordinary agent inactivity timeout:
+
+```yaml
+agent:
+ gateway_turn_lease_timeout: 1800
+```
+
+If another turn still holds the session lease when this budget expires, Hermes
+fails closed: it does not load the transcript or run the model for the waiting
+message. The user receives a rejection notice and must resend. Hermes does not
+automatically requeue the message because doing so without durable ordering and
+idempotency could process it twice. Non-positive values use the 1800-second
+default.
+
## Session Stall Watchdog
The gateway runs a notify-only stall watchdog (`agent.session_stall_timeout`, default `300` seconds, `0` = disabled). When a busy session has a **pending inbound follow-up** and the agent's shared activity clock has been idle for at least this long, the gateway logs a WARNING and sends the user a one-shot notification: