Skip to content

The agent that grows with you

fix(gateway): human-delay pacing comes from each profile's human_delay config, not process env

teknium186a599cbaebc
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index af0fdeed9d1..2a24934662f 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1902,6 +1902,9 @@ class BasePlatformAdapter(ABC):
self._busy_text_mode: str = "interrupt"
self._busy_text_debounce_seconds: float = DEFAULT_BUSY_TEXT_DEBOUNCE_SECONDS
self._busy_text_hard_cap_seconds: float = DEFAULT_BUSY_TEXT_HARD_CAP_SECONDS
+ # ``human_delay`` pacing range in ms, or None (off); per-profile config installed by the
+ # runner, never process env (#116895).
+ self._human_delay_range_ms: Optional[tuple[int, int]] = None
self._text_debounce: dict[str, TextDebounceState] = {}
# handle_message() tasks; shutdown cancels them so a replaced gateway stops working.
self._background_tasks: set[asyncio.Task] = set()
@@ -4000,20 +4003,13 @@ class BasePlatformAdapter(ABC):
merge_text=event.message_type == MessageType.TEXT)
event._gateway_accepted = True
- @staticmethod
- def _get_human_delay() -> float:
- """Random human-like pacing delay (s) from HERMES_HUMAN_DELAY_MODE: "off" (default) |
- "natural" 800-2500ms | "custom" via HERMES_HUMAN_DELAY_MIN_MS /
- HERMES_HUMAN_DELAY_MAX_MS."""
- mode = os.getenv("HERMES_HUMAN_DELAY_MODE", "off").lower()
- if mode == "off":
+ def _get_human_delay(self) -> float:
+ """Random human-like pacing delay (s) from this adapter's ``human_delay`` config range
+ (ms), installed per profile by the runner (``_wire_adapter_handlers``); ``None`` = off."""
+ bounds = self._human_delay_range_ms
+ if not bounds:
return 0.0
- lo, hi = 800, 2500
- if mode != "natural": # custom mode tolerates malformed env vars
- lo = _or_default(lambda: int(os.getenv("HERMES_HUMAN_DELAY_MIN_MS", str(lo))), lo)
- hi = _or_default(lambda: int(os.getenv("HERMES_HUMAN_DELAY_MAX_MS", str(hi))), hi)
- if lo < 0 or hi < 0 or lo > hi:
- lo, hi = 800, 2500
+ lo, hi = bounds
return random.uniform(lo / 1000.0, hi / 1000.0)
async def _synthesize_auto_tts(self, text_content: str) -> Tuple[List[str], Optional[str]]:
diff --git a/gateway/run.py b/gateway/run.py
index 11e03fafddf..c658a82da3e 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3488,6 +3488,8 @@ class GatewayRunner(
self._busy_text_modes_by_profile: Dict[str, str] = {}
self._busy_text_timing = self._busy_text_timing_from_config(_load_gateway_config())
self._busy_text_timing_by_profile: Dict[str, tuple[float, float]] = {}
+ self._human_delay = self._human_delay_from_config(_load_gateway_config())
+ self._human_delay_by_profile: Dict[str, Optional[tuple[int, int]]] = {}
self._restart_drain_timeout = self._load_restart_drain_timeout()
# Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at
# boot — launchd fixes it at load — and applied only to signal-driven stops, which are the
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index b72ae600dd0..921e7d83088 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -33,6 +33,7 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+_UNSET = object() # "no per-profile human_delay snapshot": fall back to the primary's value
class GatewayAdapterLifecycleMixin:
@@ -1106,6 +1107,7 @@ class GatewayAdapterLifecycleMixin:
self, adapter: BasePlatformAdapter, *, message_handler=None, fatal_error_handler=None,
busy_session_handler=None, authorization_check=None, platform_event_handler=None,
busy_text_mode: Optional[str] = None, busy_text_timing: Optional[tuple[float, float]] = None,
+ human_delay: Optional[tuple[int, int]] | object = _UNSET,
) -> None:
"""Install the runner callbacks every adapter needs (defaults = primary handlers;
secondary wiring passes profile-scoped variants). ``set_reaction_handler`` is optional."""
@@ -1125,6 +1127,8 @@ class GatewayAdapterLifecycleMixin:
timing = busy_text_timing or getattr(self, "_busy_text_timing", None)
if timing:
adapter._busy_text_debounce_seconds, adapter._busy_text_hard_cap_seconds = timing
+ adapter._human_delay_range_ms = (
+ getattr(self, "_human_delay", None) if human_delay is _UNSET else human_delay)
def _configure_profile_adapter(
self, adapter: BasePlatformAdapter, profile_name: str, platform: Platform
@@ -1141,6 +1145,7 @@ class GatewayAdapterLifecycleMixin:
# connect time; see #75198).
text_modes = getattr(self, "_busy_text_modes_by_profile", None)
timings = getattr(self, "_busy_text_timing_by_profile", None)
+ delays = getattr(self, "_human_delay_by_profile", None)
self._wire_adapter_handlers(
adapter,
message_handler=self._make_profile_message_handler(profile_name),
@@ -1154,6 +1159,7 @@ class GatewayAdapterLifecycleMixin:
else self._busy_text_mode
),
busy_text_timing=(timings.get(profile_name) if isinstance(timings, dict) else None),
+ human_delay=(delays.get(profile_name, _UNSET) if isinstance(delays, dict) else _UNSET),
)
# Voice transcripts from this bot's channels dispatch through THIS adapter.
self._bind_voice_input_callback(adapter)
diff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.py
index 2bc225783b1..ad07ef1c1f2 100644
--- a/gateway/run_config_loaders.py
+++ b/gateway/run_config_loaders.py
@@ -37,6 +37,8 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+DEFAULT_HUMAN_DELAY_RANGE_MS: tuple[int, int] = (800, 2500)
+
_BUSY_INPUT_MODES = {"interrupt", "queue", "steer"}
@@ -294,8 +296,39 @@ class GatewayConfigLoadersMixin:
out.append(value)
return out[0], out[1]
+ @staticmethod
+ def _human_delay_from_config(config: dict) -> Optional[tuple[int, int]]:
+ """``human_delay.{mode,min_ms,max_ms}`` for one profile as a ``(lo_ms, hi_ms)`` range, or
+ ``None`` when off (#116895). ``natural`` is the fixed 800-2500 range; ``custom`` reads the
+ bounds and rejects non-integer, negative or inverted values with a warning naming the key,
+ falling back to the natural range instead of letting ``random.uniform`` raise at send."""
+ mode = str(cfg_get(config, "human_delay", "mode", default="off") or "off").strip().lower()
+ if mode == "off":
+ return None
+ lo, hi = DEFAULT_HUMAN_DELAY_RANGE_MS
+ if mode != "natural":
+ if mode != "custom":
+ logger.warning("human_delay.mode=%r is not off/natural/custom; using natural", mode)
+ return DEFAULT_HUMAN_DELAY_RANGE_MS
+ bounds = []
+ for key, default in (("min_ms", lo), ("max_ms", hi)):
+ raw = cfg_get(config, "human_delay", key, default=None)
+ try:
+ value = default if raw is None or raw == "" else int(raw)
+ if value < 0:
+ raise ValueError(raw)
+ except (TypeError, ValueError):
+ logger.warning("human_delay.%s=%r is not a non-negative integer; using %s", key, raw, default)
+ value = default
+ bounds.append(value)
+ lo, hi = bounds
+ if lo > hi:
+ logger.warning("human_delay.min_ms=%s exceeds human_delay.max_ms=%s; using natural range", lo, hi)
+ lo, hi = DEFAULT_HUMAN_DELAY_RANGE_MS
+ return lo, hi
+
def _snapshot_profile_busy_modes(self, profile_name: str, config: dict) -> None:
- """Cache a routed profile's busy policy for this gateway lifetime."""
+ """Cache a routed profile's busy policy and pacing for this gateway lifetime."""
input_mode, text_mode = self._busy_modes_from_config(
config, fallback_input=getattr(self, "_busy_input_mode", "interrupt"),
fallback_text=getattr(self, "_busy_text_mode", "interrupt"),
@@ -304,6 +337,8 @@ class GatewayConfigLoadersMixin:
self.__dict__.setdefault("_busy_text_modes_by_profile", {})[profile_name] = text_mode
self.__dict__.setdefault("_busy_text_timing_by_profile", {})[profile_name] = (
self._busy_text_timing_from_config(config))
+ self.__dict__.setdefault("_human_delay_by_profile", {})[profile_name] = (
+ self._human_delay_from_config(config))
def _busy_profile_name_for_source(self, source: SessionSource) -> Optional[str]:
"""Return the routed profile whose busy policy applies, if any."""
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index bd8022a2291..220884319f8 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -206,7 +206,7 @@ class GatewayProfileReconcileMixin:
# Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.
_write_runtime_status_quiet(drop_profile_platforms=name)
for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile",
- "_busy_text_timing_by_profile"):
+ "_busy_text_timing_by_profile", "_human_delay_by_profile"):
store = getattr(self, attr, None)
if isinstance(store, dict):
store.pop(name, None)
diff --git a/tests/gateway/test_multiplex_busy_input_mode.py b/tests/gateway/test_multiplex_busy_input_mode.py
index 0005b991892..ed4a3af0838 100644
--- a/tests/gateway/test_multiplex_busy_input_mode.py
+++ b/tests/gateway/test_multiplex_busy_input_mode.py
@@ -548,3 +548,33 @@ def test_busy_text_timing_rejects_non_numeric_config(caplog):
{"display": {"busy_text_debounce_seconds": "fast", "busy_text_hard_cap_seconds": -3}})
assert timing == (0.35, 1.0)
assert "busy_text_debounce_seconds" in caplog.text and "busy_text_hard_cap_seconds" in caplog.text
+
+
+async def test_secondary_human_delay_follows_profile_config_not_process_env(tmp_path, monkeypatch):
+ """``human_delay`` pacing is per-profile config (#116895): the launch-process env must not reach
+ any adapter, and each profile keeps its own range across A->B->A."""
+ monkeypatch.setenv("HERMES_HUMAN_DELAY_MODE", "custom")
+ monkeypatch.setenv("HERMES_HUMAN_DELAY_MIN_MS", "1")
+ monkeypatch.setenv("HERMES_HUMAN_DELAY_MAX_MS", "2")
+ runner = _runner()
+ runner._human_delay = None
+ homes = {"alpha": tmp_path / "alpha", "beta": tmp_path / "beta"}
+ for name, body in {"alpha": "human_delay:\n mode: custom\n min_ms: 100\n max_ms: 200\n",
+ "beta": "human_delay:\n mode: natural\n"}.items():
+ homes[name].mkdir()
+ (homes[name] / "config.yaml").write_text(body, encoding="utf-8")
+
+ seen = {}
+ for name in ("alpha", "beta", "alpha"):
+ assert await runner._start_one_profile_adapters(name, homes[name], {}) == 0
+ adapter = _adapter()
+ runner._profile_adapters[name][Platform.TELEGRAM] = adapter
+ runner._configure_profile_adapter(adapter, name, Platform.TELEGRAM)
+ seen.setdefault(name, []).append(adapter._human_delay_range_ms)
+
+ assert seen["alpha"] == [(100, 200), (100, 200)]
+ assert seen["beta"] == [(800, 2500)]
+ # A fresh adapter is off until the runner installs a range; env is never consulted.
+ fresh = _adapter()
+ assert fresh._human_delay_range_ms is None and fresh._get_human_delay() == 0.0
diff --git a/tests/gateway/test_platform_base.py b/tests/gateway/test_platform_base.py
index 8609fecfb23..c53b3a2b236 100644
--- a/tests/gateway/test_platform_base.py
+++ b/tests/gateway/test_platform_base.py
@@ -1,7 +1,9 @@
"""Tests for gateway/platforms/base.py — MessageEvent, media extraction, message truncation."""
+import logging
import os
import time
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -1160,69 +1162,43 @@ class TestTruncateMessage:
class TestGetHumanDelay:
+ """``human_delay`` is per-profile config (#116895): the adapter only consumes the range the
+ runner installed; the bounds are validated in ``GatewayRunner._human_delay_from_config``."""
+ @staticmethod
+ def _adapter_with(range_ms):
+ adapter = SimpleNamespace(_human_delay_range_ms=range_ms)
+ adapter._get_human_delay = lambda: BasePlatformAdapter._get_human_delay(adapter)
+ return adapter
- def test_natural_mode_ignores_malformed_custom_env_vars(self):
- env = {
- "HERMES_HUMAN_DELAY_MODE": "natural",
- "HERMES_HUMAN_DELAY_MIN_MS": "oops",
- "HERMES_HUMAN_DELAY_MAX_MS": "still-bad",
- }
- with patch.dict(os.environ, env):
- delay = BasePlatformAdapter._get_human_delay()
- assert 0.8 <= delay <= 2.5
-
-
- def test_custom_mode_tolerates_malformed_env_vars(self):
- env = {
- "HERMES_HUMAN_DELAY_MODE": "custom",
- "HERMES_HUMAN_DELAY_MIN_MS": "oops",
- "HERMES_HUMAN_DELAY_MAX_MS": "still-bad",
- }
- with patch.dict(os.environ, env):
- # falls back to the custom-mode defaults instead of crashing
- delay = BasePlatformAdapter._get_human_delay()
- assert 0.8 <= delay <= 2.5
-
- def test_custom_mode_rejects_negative_bounds(self):
- env = {
- "HERMES_HUMAN_DELAY_MODE": "custom",
- "HERMES_HUMAN_DELAY_MIN_MS": "-1",
- "HERMES_HUMAN_DELAY_MAX_MS": "1000",
- }
- with patch.dict(os.environ, env), patch(
- "gateway.platforms.base.random.uniform", return_value=1.0
- ) as uniform:
- delay = BasePlatformAdapter._get_human_delay()
- assert delay == 1.0
- uniform.assert_called_once_with(0.8, 2.5)
-
- def test_custom_mode_rejects_inverted_bounds(self):
- env = {
- "HERMES_HUMAN_DELAY_MODE": "custom",
- "HERMES_HUMAN_DELAY_MIN_MS": "3000",
- "HERMES_HUMAN_DELAY_MAX_MS": "1000",
- }
- with patch.dict(os.environ, env), patch(
- "gateway.platforms.base.random.uniform", return_value=1.0
- ) as uniform:
- delay = BasePlatformAdapter._get_human_delay()
- assert delay == 1.0
- uniform.assert_called_once_with(0.8, 2.5)
-
- def test_custom_mode_preserves_valid_bounds(self):
- env = {
- "HERMES_HUMAN_DELAY_MODE": "custom",
- "HERMES_HUMAN_DELAY_MIN_MS": "1000",
- "HERMES_HUMAN_DELAY_MAX_MS": "2000",
- }
+ def test_off_and_installed_range_never_touch_process_env(self):
+ env = {"HERMES_HUMAN_DELAY_MODE": "custom", "HERMES_HUMAN_DELAY_MIN_MS": "10",
+ "HERMES_HUMAN_DELAY_MAX_MS": "20"}
with patch.dict(os.environ, env), patch(
"gateway.platforms.base.random.uniform", return_value=1.5
) as uniform:
- delay = BasePlatformAdapter._get_human_delay()
- assert delay == 1.5
+ assert self._adapter_with(None)._get_human_delay() == 0.0
+ uniform.assert_not_called()
+ assert self._adapter_with((1000, 2000))._get_human_delay() == 1.5
uniform.assert_called_once_with(1.0, 2.0)
+ @pytest.mark.parametrize("cfg, expected, warned_key", [
+ ({"human_delay": {"mode": "off", "min_ms": -5}}, None, None),
+ ({"human_delay": {"mode": "natural", "min_ms": "oops", "max_ms": "bad"}}, (800, 2500), None),
+ ({"human_delay": {"mode": "custom", "min_ms": 1000, "max_ms": 2000}}, (1000, 2000), None),
+ ({"human_delay": {"mode": "custom", "min_ms": "oops", "max_ms": 1000}}, (800, 1000), "human_delay.min_ms"),
+ ({"human_delay": {"mode": "custom", "min_ms": -1, "max_ms": 1000}}, (800, 1000), "human_delay.min_ms"),
+ ({"human_delay": {"mode": "custom", "min_ms": 3000, "max_ms": 1000}}, (800, 2500), "human_delay.max_ms=1000"),
+ ])
+ def test_config_bounds_are_validated_with_a_warning_naming_the_key(self, cfg, expected, warned_key, caplog):
+ from gateway.run import GatewayRunner
+ with caplog.at_level(logging.WARNING, logger="gateway.run"):
+ assert GatewayRunner._human_delay_from_config(cfg) == expected
+ if warned_key is None:
+ assert "human_delay" not in caplog.text
+ else:
+ assert warned_key in caplog.text
+
# ---------------------------------------------------------------------------
# utf16_len / _prefix_within_utf16_limit / truncate_message with len_fn
diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md
index 33cc4aa318b..02f934f62e2 100644
--- a/website/docs/reference/environment-variables.md
+++ b/website/docs/reference/environment-variables.md
@@ -825,9 +825,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us
| `HERMES_SAFE_MODE` | Troubleshooting mode: disable ALL customizations — skips plugin discovery, MCP server loading, and shell-hook registration. Set automatically by `--safe-mode` (which also sets the two flags above). |
| `HERMES_TOOL_PROGRESS` | Unsupported since the config-v12 support floor — the variable is ignored. Use `display.tool_progress` in `config.yaml`. |
| `HERMES_TOOL_PROGRESS_MODE` | Deprecated compatibility variable for tool progress mode (still read by the gateway as a fallback). Prefer `display.tool_progress` in `config.yaml`. |
-| `HERMES_HUMAN_DELAY_MODE` | Response pacing: `off`/`natural`/`custom` |
-| `HERMES_HUMAN_DELAY_MIN_MS` | Custom delay range minimum (ms) |
-| `HERMES_HUMAN_DELAY_MAX_MS` | Custom delay range maximum (ms) |
+| `HERMES_HUMAN_DELAY_MODE` / `HERMES_HUMAN_DELAY_MIN_MS` / `HERMES_HUMAN_DELAY_MAX_MS` | No longer read. Response pacing is the `human_delay` section of each profile's `config.yaml` (`mode`, `min_ms`, `max_ms`), so multiplexed profiles keep independent pacing. |
| `HERMES_QUIET` | Suppress non-essential output (`true`/`false`) |
| `CODEX_HOME` | When [Codex app-server runtime](../user-guide/features/codex-app-server-runtime) is enabled, override the directory Codex CLI reads its config + auth from (default: `~/.codex`). Hermes' migration writes the managed block to `<CODEX_HOME>/config.toml`. |
| `HERMES_KANBAN_TASK` | Set by the kanban dispatcher when spawning a worker (task UUID). Workers and the spawned `hermes-tools` MCP subprocess inherit it so kanban tools gate correctly. Don't set manually. |
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index a83f6f48dad..ae268412e85 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -2641,6 +2641,8 @@ human_delay:
max_ms: 2500 # Maximum delay (custom mode)
```
+Each profile's own `config.yaml` is read, so multiplexed profiles keep independent pacing; there is no process-environment override. In `custom` mode a non-integer, negative or inverted `min_ms`/`max_ms` pair is rejected with a warning naming the key and the `natural` range (800–2500 ms) is used instead.
+
## Code Execution
Configure the `execute_code` tool: