Skip to content

The agent that grows with you

fix(gateway): an auto-started gateway exits once nothing needs it

Teknium2107ea5f90ed
diff --git a/gateway/run.py b/gateway/run.py
index 3bb8113aecc..9bf5928af59 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -5144,10 +5144,10 @@ async def _host_attach_or_none(replace: bool, force: bool = False) -> Optional[b
async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,
- verbosity: Optional[int] = 0, force: bool = False) -> bool:
+ verbosity: Optional[int] = 0, force: bool = False, idle_exit: bool = False) -> bool:
"""Run the process lifecycle; the runner facade remains the public entrypoint."""
from gateway.run_bootstrap import start_gateway as bootstrap
- return await bootstrap(config, replace, verbosity, force)
+ return await bootstrap(config, replace, verbosity, force, idle_exit)
def _guard_corrupt_user_config() -> None:
diff --git a/gateway/run_api.py b/gateway/run_api.py
index 1049044b43b..ffdd9566123 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -124,7 +124,9 @@ class GatewayRuntimeAPI:
if scope['type'] == 'http':
# Capture before Uvicorn's proxy middleware rewrites scope.client.
scope['hermes.gateway_socket_peer'] = scope.get('client')
+ from gateway.run_idle_exit import attached_client, note_client_activity
if scope['type'] != 'websocket' or scope['path'] != '/api/ws':
+ note_client_activity(self.runner) # dashboard/API traffic keeps an idle-exit gateway up
return await self.app(scope, receive, send)
original_receive = receive
allow_draining = False
@@ -181,7 +183,7 @@ class GatewayRuntimeAPI:
from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
from tui_gateway.ws import handle_ws
from gateway.session_authorities import owner_scope
- with owner_scope(authority):
+ with owner_scope(authority), attached_client(self.runner):
await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local',
'profile_id': grant['profile_id'],
'instance_id': grant['instance_id'],
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index 7b2ad16fca8..d8f1d707e00 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -261,6 +261,8 @@ async def _start_gateway_start_control_socket(runner):
"served_profiles", "parked_profiles", "capabilities") if key in descriptor})
if getattr(runner, '_draining', False):
payload.update(state='draining', capabilities=[])
+ if payload.get('state') == 'draining' and descriptor.get('drain_reason'):
+ payload['drain_reason'] = descriptor['drain_reason']
payload["supervisor"] = {"manual": "none", "desktop": "none"}.get(
payload.get("supervisor"), payload.get("supervisor", "none"))
return payload
@@ -612,10 +614,11 @@ async def _start_gateway_run_runner(runner, _signal_initiated_shutdown: list) ->
async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,
- verbosity: Optional[int] = 0, force: bool = False) -> bool:
+ verbosity: Optional[int] = 0, force: bool = False, idle_exit: bool = False) -> bool:
"""Start the gateway and run until interrupted; False if it failed to start (non-zero exit so
systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop
- deadlocks); ``force`` starts without consulting the host owner at all."""
+ deadlocks); ``force`` starts without consulting the host owner at all; ``idle_exit`` arms the
+ unmanaged idle exit (``gateway.run_idle_exit``) for a client-started daemon."""
from gateway.run import (
GatewayRunner,
_best_effort,
@@ -775,6 +778,9 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
from gateway.run_runtime import publish_gateway_runtime_ready
publish_gateway_runtime_ready(runner)
runner._start_systemd_watchdog()
+ if idle_exit:
+ from gateway.run_idle_exit import arm_unmanaged_idle_exit
+ arm_unmanaged_idle_exit(runner)
from gateway.run_runtime import wait_gateway_runtime
try:
diff --git a/gateway/run_idle_exit.py b/gateway/run_idle_exit.py
new file mode 100644
index 00000000000..e07fc1d9f93
--- /dev/null
+++ b/gateway/run_idle_exit.py
@@ -0,0 +1,222 @@
+"""Idle exit for an auto-started (unmanaged) gateway.
+
+A client that finds no gateway for its home starts a detached ``gateway run --idle-exit``
+(``hermes_cli.gateway_runtime_start``). Nothing else ever stops that process, so every throwaway home
+(scripts, tests, one-shot ``chat -q``) used to leave a ~270 MB daemon behind. This watcher ends it once
+it has served nobody and has nothing to do for ``gateway.unmanaged_idle_exit_seconds`` (default 600,
+``0`` disables):
+
+- no attached client (live ticketed WebSocket, outstanding ticket, or recent HTTP/WS activity);
+- no messaging adapter configured, connected or reconnecting (any profile);
+- no runnable cron job and no kanban task the dispatcher must act on;
+- no queued/started admission, live managed worker, in-flight agent/cron/API run, background
+ process or async delegation, active heartbeat/loop, pending handoff or hosted-room task.
+
+Every probe fails CLOSED: an unreadable source counts as work, so the gateway stays up. A gateway with
+a supervisor (systemd/launchd/Desktop/external) or started without ``--idle-exit`` (installed services,
+``hermes gateway run`` by hand, ``hermes gateway ensure`` from Desktop) never arms this. The exit
+publishes ``draining`` with ``drain_reason: idle_exit`` before anything else, so a client that races it
+waits for the process to go and starts a fresh one instead of failing.
+"""
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+import sqlite3
+import time
+from pathlib import Path
+
+logger = logging.getLogger("gateway.run")
+
+DEFAULT_IDLE_EXIT_SECONDS = 600.0
+IDLE_EXIT_REASON = "idle_exit"
+# Kanban statuses the embedded dispatcher acts on without a human (promotion, spawn, reclaim).
+_KANBAN_DUE_STATUSES = ("scheduled", "ready", "running", "review")
+
+
+def idle_exit_seconds(runner) -> float:
+ """``gateway.unmanaged_idle_exit_seconds`` from the launch home; 0 disables, junk keeps the default."""
+ from gateway.run import _load_gateway_config
+ section = (_load_gateway_config() or {}).get("gateway")
+ value = section.get("unmanaged_idle_exit_seconds") if isinstance(section, dict) else None
+ if value is None:
+ return DEFAULT_IDLE_EXIT_SECONDS
+ try:
+ seconds = float(value)
+ except (TypeError, ValueError):
+ logger.warning("gateway.unmanaged_idle_exit_seconds=%r is not a number; using %.0f", value,
+ DEFAULT_IDLE_EXIT_SECONDS)
+ return DEFAULT_IDLE_EXIT_SECONDS
+ return max(0.0, seconds)
+
+
+def note_client_activity(runner) -> None:
+ runner._idle_exit_last_activity = time.monotonic()
+
+
+def attached_client(runner):
+ """Count one live client connection for the idle check (and stamp activity on both ends)."""
+ note_client_activity(runner)
+ runner._idle_exit_clients = getattr(runner, "_idle_exit_clients", 0) + 1
+ try:
+ yield
+ finally:
+ runner._idle_exit_clients -= 1
+ note_client_activity(runner)
+
+
+def _messaging_busy(runner) -> str | None:
+ from gateway.config import Platform
+ local = {Platform.LOCAL}
+ live = [p for p in (getattr(runner, "adapters", None) or {}) if p not in local]
+ for adapters in (getattr(runner, "_profile_adapters", None) or {}).values():
+ live.extend(adapters)
+ for pending in (getattr(runner, "_profile_failed_platforms", None) or {}).values():
+ live.extend(pending or {})
+ live.extend(getattr(runner, "_failed_platforms", None) or {})
+ config = getattr(runner, "config", None)
+ if config is not None:
+ live.extend(p for p, cfg in config.platforms.items() if p not in local and getattr(cfg, "enabled", False))
+ return f"messaging {sorted({getattr(p, 'value', str(p)) for p in live})}" if live else None
+
+
+def _served_homes(runner) -> list[Path]:
+ from gateway.run import _cron_tick_profile_homes
+ from gateway.session_authorities import all_authorities
+ homes = {Path(a.profile_id) for a in all_authorities(runner)}
+ homes.update(Path(h) for _name, h in _cron_tick_profile_homes(runner.config))
+ return sorted(homes)
+
+
+def _cron_busy(homes) -> str | None:
+ from cron.jobs import is_job_runnable, is_terminal_job, load_jobs, use_cron_store
+ from cron.scheduler import get_running_job_ids
+ if get_running_job_ids():
+ return "cron job running"
+ for home in homes:
+ if not (home / "cron" / "jobs.json").exists():
+ continue
+ with use_cron_store(home):
+ jobs = load_jobs()
+ if any(is_job_runnable(job) and not is_terminal_job(job) for job in jobs):
+ return f"cron jobs scheduled in {home}"
+ return None
+
+
+def _kanban_busy() -> str | None:
+ from hermes_cli import kanban_db
+ marks = ",".join("?" * len(_KANBAN_DUE_STATUSES))
+ for meta in kanban_db.list_boards(include_archived=False):
+ path = kanban_db.kanban_db_path(board=meta.get("slug"))
+ if not path.exists():
+ continue
+ with contextlib.closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=2)) as conn:
+ if conn.execute(f"SELECT 1 FROM tasks WHERE status IN ({marks}) LIMIT 1",
+ _KANBAN_DUE_STATUSES).fetchone():
+ return f"kanban work on board {meta.get('slug')}"
+ return None
+
+
+def _ledger_busy(runner) -> str | None:
+ from gateway.session_authorities import all_authorities
+ for authority in all_authorities(runner):
+ db = authority.db
+ if db._read_all("SELECT 1 FROM session_admissions WHERE status IN ('queued','started') LIMIT 1"):
+ return f"admissions pending in {authority.profile_id}"
+ if db._read_all("SELECT 1 FROM worker_executions WHERE status != 'terminal' LIMIT 1"):
+ return f"managed worker live in {authority.profile_id}"
+ service = getattr(authority, "hosted_room_service", None)
+ if service is not None:
+ status = service.status()
+ if status.get("current_tasks") or status.get("leased_rooms"):
+ return f"hosted-room work in {authority.profile_id}"
+ return None
+
+
+def _store_gates_busy(homes) -> str | None:
+ from gateway.run_idle_gates import (
+ profile_has_active_heartbeat, profile_has_active_loop, profile_has_pending_handoff)
+ for home in homes:
+ for label, gate in (("heartbeat", profile_has_active_heartbeat), ("loop", profile_has_active_loop),
+ ("handoff", profile_has_pending_handoff)):
+ if gate(home):
+ return f"active {label} in {home}"
+ return None
+
+
+def busy_reason(runner, *, window: float) -> str | None:
+ """Why the gateway must stay up, or None when it may exit. Fails closed on any error."""
+ try:
+ clients = getattr(runner, "_idle_exit_clients", 0)
+ if clients:
+ return f"{clients} client(s) attached"
+ tickets = getattr(runner, "session_ticket_store", None)
+ if tickets is not None and tickets.outstanding():
+ return "client attaching"
+ quiet = time.monotonic() - getattr(runner, "_idle_exit_last_activity", 0.0)
+ if quiet < window:
+ return f"client activity {quiet:.0f}s ago"
+ if runner._draining or not runner._running:
+ return "already stopping"
+ if runner._active_work_count():
+ return "agent work in flight"
+ if runner._scale_to_zero_has_live_background_work():
+ return "background work in flight"
+ homes = _served_homes(runner)
+ return (_messaging_busy(runner) or _ledger_busy(runner) or _cron_busy(homes) or _kanban_busy()
+ or _store_gates_busy(homes))
+ except Exception as exc:
+ logger.debug("idle-exit probe failed; staying up", exc_info=True)
+ return f"idle probe failed ({type(exc).__name__})"
+
+
+def _begin_idle_exit(runner, window: float) -> None:
+ """Withdraw admission synchronously (no await between the last idle check and here), then stop."""
+ runner._draining = True
+ runner.session_runtime_descriptor.update(state="draining", capabilities=[], drain_reason=IDLE_EXIT_REASON)
+ runner._exit_reason = f"auto-started gateway idle for {window:.0f}s (gateway.unmanaged_idle_exit_seconds)"
+ logger.info("Exiting: %s; the next client starts a fresh gateway", runner._exit_reason)
+ runner._idle_exit_stop_task = asyncio.ensure_future(runner.stop())
+
+
+async def unmanaged_idle_exit_watcher(runner) -> None:
+ window = idle_exit_seconds(runner)
+ if window <= 0:
+ logger.info("Auto-started gateway idle exit disabled (gateway.unmanaged_idle_exit_seconds=0)")
+ return
+ logger.info("Auto-started gateway: exits after %.0fs with no clients, adapters, cron/kanban work or "
+ "admissions (gateway.unmanaged_idle_exit_seconds)", window)
+ interval = min(30.0, max(0.5, window / 4))
+ idle_since = None
+ while runner._running and not runner._draining:
+ await asyncio.sleep(interval)
+ window = idle_exit_seconds(runner)
+ if window <= 0:
+ idle_since = None
+ continue
+ # The store/cron/kanban reads touch disk; keep them off the loop, then re-check the
+ # loop-only facts (clients, tickets, draining) synchronously right before acting.
+ reason = await asyncio.to_thread(busy_reason, runner, window=window)
+ if reason is not None:
+ idle_since = None
+ continue
+ idle_since = idle_since or time.monotonic()
+ if time.monotonic() - idle_since < interval and window > interval:
+ continue # two consecutive idle readings, so one racing write cannot slip between them
+ if busy_reason(runner, window=window) is None:
+ _begin_idle_exit(runner, window)
+ return
+
+
+def arm_unmanaged_idle_exit(runner) -> bool:
+ """Start the watcher for an ``--idle-exit`` launch that no supervisor owns. Returns whether it armed."""
+ from gateway.control_socket import _detect_supervisor
+ supervisor = _detect_supervisor()
+ if supervisor != "manual":
+ logger.info("Auto-started gateway idle exit not armed: supervised by %s", supervisor)
+ return False
+ note_client_activity(runner)
+ runner._spawn_supervised(lambda: unmanaged_idle_exit_watcher(runner), "unmanaged_idle_exit_watcher")
+ return True
diff --git a/gateway/runtime_bootstrap.py b/gateway/runtime_bootstrap.py
index 76e55154708..b9499f0dadc 100644
--- a/gateway/runtime_bootstrap.py
+++ b/gateway/runtime_bootstrap.py
@@ -67,6 +67,12 @@ class TicketStore:
del self._entries[key]
return dict(grant)
+ def outstanding(self) -> bool:
+ """An unexpired ticket was minted and not yet redeemed: a client is attaching right now."""
+ with self._lock:
+ now = time.monotonic()
+ return any(expires > now for expires, _grant in self._entries.values())
+
def revoke(self) -> None:
with self._lock:
self._entries.clear()
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 1fc63df433a..3f7df745508 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2098,6 +2098,11 @@ DEFAULT_CONFIG = {
"export": {"otlp": {"enabled": False, "endpoint": "", "headers_env": {}}},
},
"gateway": { # Gateway settings (messaging platforms: Telegram, Discord, Slack, ...).
+ # A gateway a client auto-started (no service installed: `hermes chat`, `chat -q`, the TUI)
+ # exits after this many seconds with no attached client, no messaging adapter, no cron /
+ # kanban work due and no queued turn; the next client starts it again. Never applies to an
+ # installed service, a Desktop-started or a hand-run `hermes gateway run`. 0 disables.
+ "unmanaged_idle_exit_seconds": 600,
# Seconds to let a SIGTERM-interrupted gateway agent unwind before adapter/database
# teardown. Keep short so service-manager shutdowns don't exhaust their stop budget.
"signal_interrupt_grace_timeout": 1,
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 05c133225c6..238558091a9 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -4539,9 +4539,12 @@ def _respawn_storm_backoff() -> None:
logger.debug("respawn-storm breaker check failed (non-fatal): %s", _be)
-def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, force: bool = False):
+def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, force: bool = False,
+ idle_exit: bool = False):
"""Run the gateway in foreground. verbose 1=INFO/2+=DEBUG on stderr; quiet: no stderr logs; replace:
- kill an existing instance first (avoids systemd restart loops); force: skip the supervised guard."""
+ kill an existing instance first (avoids systemd restart loops); force: skip the supervised guard;
+ idle_exit: a client auto-started this unsupervised gateway, so it exits once idle
+ (``gateway.unmanaged_idle_exit_seconds``)."""
_guard_official_docker_root_gateway()
_attach_to_host_gateway_or_guard(force=force, replace=replace)
_guard_supervised_gateway_conflict(force=force)
@@ -4608,7 +4611,8 @@ def run_gateway(verbose: int = 0, quiet: bool = False, replace: bool = False, fo
success = False
try:
- success = asyncio.run(start_gateway(replace=replace, force=force, verbosity=verbosity))
+ success = asyncio.run(start_gateway(replace=replace, force=force, verbosity=verbosity,
+ idle_exit=idle_exit))
_exit_diag("asyncio.run.returned", success=success)
except KeyboardInterrupt:
# Detached Windows runs absorb SIGINT above; keep the handler for console runs.
@@ -5035,6 +5039,7 @@ def _cmd_run(args):
run_gateway(
getattr(args, "verbose", 0), quiet=getattr(args, "quiet", False),
replace=getattr(args, "replace", False), force=getattr(args, "force", False),
+ idle_exit=getattr(args, "idle_exit", False),
)
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index 89d16130ce4..581d3d04e5f 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -197,7 +197,9 @@ async def connect_gateway():
url = remote
else:
home = get_hermes_home().resolve()
- result = await asyncio.to_thread(ensure_gateway_runtime, home)
+ # A client's own start: the daemon it may launch ends itself once idle (no client, adapter,
+ # cron/kanban work or admission), and the next client starts a fresh one.
+ result = await asyncio.to_thread(ensure_gateway_runtime, home, idle_exit=True)
if result.state != "ready" or result.endpoint is None:
detail = getattr(result, "detail", None)
if result.reason_code == "runtime_exited" and detail:
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index 7a473f5ce19..68011755925 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -68,7 +68,10 @@ def _endpoint(payload: dict, home: Path, control_home: Path | None = None) -> Ga
return GatewayDiscovery("inaccessible", reason_code="profile_mismatch")
state = payload.get("state")
if state in {"starting", "draining", "conflict"}:
- return GatewayDiscovery(state)
+ # An auto-started gateway ending through its idle exit names that, so its clients wait
+ # for it to go and start a fresh one instead of reporting a refusal.
+ idle = state == "draining" and payload.get("drain_reason") == "idle_exit"
+ return GatewayDiscovery(state, reason_code="idle_exit" if idle else None)
if state != "ready":
return GatewayDiscovery("inaccessible", reason_code="invalid_runtime_state")
capabilities = payload.get("capabilities")
@@ -213,11 +216,15 @@ def _update_fenced(homes) -> bool:
return False
-def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT_ENSURE_TIMEOUT) -> GatewayDiscovery:
+def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT_ENSURE_TIMEOUT,
+ idle_exit: bool = False) -> GatewayDiscovery:
"""Ensure once, never install/replace; pending remains pending at deadline.
A successful service command or Popen is not session readiness. After an
owner/start request is observed this invocation never launches another.
+ ``idle_exit``: an unmanaged daemon this call starts ends itself once idle (client entrypoints:
+ chat, TUI, cron/kanban/ACP clients). A gateway that is ending that way reports ``draining``
+ (``idle_exit``); this call waits for it to go and starts the replacement transparently.
"""
import time
from hermes_cli.gateway_runtime_service import (
@@ -233,6 +240,10 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
requested = False
child = None
child_home, child_offset = home, 0
+ # A gateway ending through its own idle exit is not a refusal: wait for it to go (its lock is
+ # still held for a moment after its control socket closes, which reads as "starting"), then
+ # start the replacement this call owes the client.
+ retiring = False
delay = 0.025
try:
while True:
@@ -245,6 +256,10 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
observed = discover_gateway_endpoint(home, timeout=remaining(deadline))
if observed.reason_code == "control_timeout":
return GatewayDiscovery("starting", reason_code="deadline")
+ if observed.state == "draining" and observed.reason_code == "idle_exit":
+ retiring, requested, child = True, False, None
+ time.sleep(min(0.1, remaining(deadline)))
+ continue
if observed.state not in {"absent", "starting"}:
return observed
if status is not None and observed.state == "absent":
@@ -253,9 +268,11 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
# Its own (redacted) output is the answer the user needs, not a pointer to a file.
from hermes_cli.gateway_runtime_start import startup_failure_report
return GatewayDiscovery("inaccessible", reason_code="runtime_exited",
- detail=startup_failure_report(child_home, child_offset, status))
- if observed.state == "starting":
+ detail=startup_failure_report(child_home, child_offset, status, child.pid))
+ if observed.state == "starting" and not retiring:
requested = True
+ if observed.state == "absent":
+ retiring = False
# A default multiplexer that is still starting will serve this named profile; never
# spawn a competing per-profile daemon while its reservation is pending.
if observed.state == "absent" and not requested and _multiplexer_starting(home):
@@ -281,7 +298,7 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULT
else:
from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway, stdio_log_size
child_home, child_offset = target, stdio_log_size(target)
- child = spawn_unmanaged_gateway(target, deadline=deadline)
+ child = spawn_unmanaged_gateway(target, deadline=deadline, idle_exit=idle_exit)
requested = True
time.sleep(min(delay, remaining(deadline)))
delay = min(delay * 1.5, 0.25)
diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.py
index 00a243a250f..ecd7ac4990e 100644
--- a/hermes_cli/gateway_runtime_start.py
+++ b/hermes_cli/gateway_runtime_start.py
@@ -10,11 +10,13 @@ from hermes_cli._subprocess_compat import windows_detach_popen_kwargs, _WINDOWS_
from hermes_cli.gateway_runtime_service import RuntimeStartError, remaining
-def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float) -> subprocess.Popen:
+def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: bool = False) -> subprocess.Popen:
"""Request a daemon, not readiness. Refuse Windows no-breakaway fallback.
No --replace, persistence, login changes, elevation, shell, or inherited stdio.
The gateway runtime's own exclusive ownership fence arbitrates racing starts.
+ ``idle_exit``: the daemon ends itself once idle (a chat/TUI/cron client's own start; never
+ Desktop's ``gateway ensure``, which keeps its attached gateway for the app's lifetime).
"""
home = profile_home.resolve()
root = Path(__file__).resolve().parent.parent
@@ -22,7 +24,8 @@ def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float) -> subproces
# _apply_profile_override follows the sticky active_profile and boots the wrong
# profile's daemon. A <root>/profiles/<name> home is already trusted as-is.
selector = [] if home.parent.name == "profiles" else ["--profile", "default"]
- command = [sys.executable, "-m", "hermes_cli.main", *selector, "gateway", "run", "--quiet"]
+ command = [sys.executable, "-m", "hermes_cli.main", *selector, "gateway", "run", "--quiet",
+ *(["--idle-exit"] if idle_exit else [])]
env = dict(os.environ)
if sys.platform == "win32":
from hermes_cli.gateway_windows import windowless_gateway_restart_spec
@@ -71,7 +74,7 @@ _TAIL_LINES = 15
_TAIL_BYTES = 64 * 1024
-def startup_failure_report(profile_home: Path, offset: int, status: int) -> str:
+def startup_failure_report(profile_home: Path, offset: int, status: int, pid: int | None = None) -> str:
"""What a client prints when the gateway it started died before serving: the exit status, the
redacted tail of THIS launch's stdio (the traceback lives there, written before logging is up and
before the detached-stdio redactor is installed) and the command that shows the whole log."""
@@ -84,6 +87,14 @@ def startup_failure_report(profile_home: Path, offset: int, status: int) -> str:
text = ""
lines = [line.rstrip() for line in text.splitlines()
if line.strip() and not line.lstrip().startswith(_BANNER_PREFIXES)][-_TAIL_LINES:]
+ if not lines:
+ # A clean refusal (config/credential verdict, exit 78) is logged, not printed: the runtime
+ # status file names it.
+ from gateway.status import read_runtime_status
+ status_file = read_runtime_status(profile_home / "gateway_state.json") or {}
+ if status_file.get("exit_reason") and pid is not None and status_file.get("pid") == pid:
+ lines = [str(status_file["exit_reason"])[:2000]]
+ path = profile_home / "logs" / "gateway.log"
from agent.redact import redact_sensitive_text
tail = redact_sensitive_text("\n".join(lines), force=True, redact_url_credentials=True)
see = f'type "{path}"' if sys.platform == "win32" else f"tail -n 200 '{path}'"
diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.py
index c201fc6f83b..67c659ca363 100644
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@ -106,6 +106,9 @@ def build_gateway_parser(
"gateway. In-chat restarts and updates exit back to that manager "
"instead of spawning a detached replacement. Use this when a "
"launchd/systemd wrapper strips its native environment markers.")
+ # Internal: set only by a client that auto-starts its own gateway (chat, TUI, cron/kanban
+ # clients). Never in service units, Desktop's `gateway ensure` start or a hand-run gateway.
+ _flag(gateway_run, "--idle-exit", help=argparse.SUPPRESS)
add_accept_hooks_flag(gateway_run)
add_accept_hooks_flag(gateway_parser)
diff --git a/tests/gateway/test_unmanaged_idle_exit.py b/tests/gateway/test_unmanaged_idle_exit.py
new file mode 100644
index 00000000000..61e10f76068
--- /dev/null
+++ b/tests/gateway/test_unmanaged_idle_exit.py
@@ -0,0 +1,91 @@
+"""An auto-started (``--idle-exit``) gateway exits once idle; anything it serves keeps it up.
+
+Real SQLite ledger rows, a real cron store and real asyncio; the runner is a stand-in exposing
+only what the idle predicate reads.
+"""
+from __future__ import annotations
+
+import asyncio
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import run_idle_exit
+from gateway.config import Platform
+from gateway.runtime_bootstrap import TicketStore
+from gateway.session_authorities import SessionAuthorities
+from hermes_state import SessionDB
+from hermes_state_runtime import admit_session_input, begin_runtime_epoch, cancel_session_input
+
+
+def _runner(tmp_path, monkeypatch, *, window=0.2):
+ home = tmp_path / "home"
+ home.mkdir()
+ db = SessionDB(db_path=home / "state.db")
+ registry = SessionAuthorities(home)
+ registry.add(home, SimpleNamespace(profile_id=str(home), db=db))
+ stops = []
+
+ async def stop():
+ stops.append(True)
+ runner._running = False
+ runner = SimpleNamespace(
+ _running=True, _draining=False, session_authorities=registry, adapters={Platform.LOCAL: object()},
+ _profile_adapters={}, _profile_failed_platforms={}, _failed_platforms={},
+ config=SimpleNamespace(platforms={}), session_ticket_store=TicketStore("i", frozenset({str(home)})),
+ session_runtime_descriptor={"state": "ready", "capabilities": ["x"]}, _exit_reason=None,
+ _active_work_count=lambda: 0, _scale_to_zero_has_live_background_work=lambda: False, stop=stop)
+ monkeypatch.setattr(run_idle_exit, "idle_exit_seconds", lambda r: window)
+ monkeypatch.setattr("gateway.run._cron_tick_profile_homes", lambda config: [("default", home)])
+ monkeypatch.setattr(run_idle_exit, "_kanban_busy", lambda: None)
+ monkeypatch.setattr(run_idle_exit, "_store_gates_busy", lambda homes: None)
+ run_idle_exit.note_client_activity(runner)
+ runner._idle_exit_last_activity -= 10
+ return runner, home, db, stops
+
+
+async def test_idle_auto_started_gateway_exits_and_publishes_why(tmp_path, monkeypatch):
+ runner, _home, db, stops = _runner(tmp_path, monkeypatch)
+ try:
+ await asyncio.wait_for(run_idle_exit.unmanaged_idle_exit_watcher(runner), 10)
+ await runner._idle_exit_stop_task
+ assert stops == [True]
+ assert runner.session_runtime_descriptor["state"] == "draining"
+ assert runner.session_runtime_descriptor["drain_reason"] == run_idle_exit.IDLE_EXIT_REASON
+ finally:
+ db.close()
+
+
+async def test_queued_work_clients_adapters_and_cron_each_keep_it_up(tmp_path, monkeypatch):
+ """Fail-closed predicate: every class of pending work, a live client and a configured adapter
+ keep the gateway up; only when all are gone is it idle."""
+ runner, home, db, _stops = _runner(tmp_path, monkeypatch)
+ try:
+ assert run_idle_exit.busy_reason(runner, window=0.2) is None
+ db.create_session("s", source="cli")
+ epoch = begin_runtime_epoch(db, instance_id="owner")
+ row = admit_session_input(db, epoch=epoch, principal_id="p", session_id="s", request_id="r",
+ payload={"text": "queued while idle"})
+ assert "admissions pending" in run_idle_exit.busy_reason(runner, window=0.2)
+ cancel_session_input(db, epoch=epoch, admission_id=row["admission_id"])
+ with run_idle_exit.attached_client(runner):
+ assert "client(s) attached" in run_idle_exit.busy_reason(runner, window=0.2)
+ assert "client activity" in run_idle_exit.busy_reason(runner, window=60)
+ runner._idle_exit_last_activity -= 120
+ runner.session_ticket_store.mint(profile_id=str(home), subject="u", purpose="interactive")
+ assert run_idle_exit.busy_reason(runner, window=0.2) == "client attaching"
+ runner.session_ticket_store.revoke()
+ runner.config.platforms[Platform.TELEGRAM] = SimpleNamespace(enabled=True)
+ assert "messaging" in run_idle_exit.busy_reason(runner, window=0.2)
+ runner.config.platforms.clear()
+ from cron.jobs import create_job, use_cron_store
+ with use_cron_store(home):
+ create_job("ping", "every 1h", name="j")
+ assert "cron jobs scheduled" in run_idle_exit.busy_reason(runner, window=0.2)
+ monkeypatch.setattr("cron.jobs.load_jobs", lambda: (_ for _ in ()).throw(OSError("unreadable")))
+ assert "idle probe failed" in run_idle_exit.busy_reason(runner, window=0.2)
+ finally:
+ db.close()
diff --git a/tests/tui_gateway/test_gateway_bootstrap_recover.py b/tests/tui_gateway/test_gateway_bootstrap_recover.py
index 297c16038ec..513af8fc791 100644
--- a/tests/tui_gateway/test_gateway_bootstrap_recover.py
+++ b/tests/tui_gateway/test_gateway_bootstrap_recover.py
@@ -39,9 +39,9 @@ def test_recover_reensures_only_a_crashed_owner(monkeypatch, tmp_path, record, e
lambda h, timeout=5: SimpleNamespace(state="absent", endpoint=None, reason_code=None))
calls = []
- def ensure(h, timeout=30):
+ def ensure(h, timeout=30, idle_exit=False):
calls.append(Path(h))
- return SimpleNamespace(state="starting", endpoint=None, reason_code="deadline")
+ return SimpleNamespace(state="starting", endpoint=None, reason_code="deadline", detail=None)
monkeypatch.setattr(gateway_runtime, "ensure_gateway_runtime", ensure)
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index f929b69c405..b6301ee60db 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -40,10 +40,10 @@ def bootstrap(start: bool, recover: bool = False) -> dict:
"HERMES_CWD", "TERMINAL_CWD", "HERMES_YOLO", "HERMES_ACCEPT_HOOKS",
"HERMES_TUI_CHECKPOINTS", "HERMES_TUI_PASS_SESSION_ID"):
os.environ.pop(key, None)
- receipt = (ensure_gateway_runtime(home, timeout=30) if start
+ receipt = (ensure_gateway_runtime(home, timeout=30, idle_exit=True) if start
else discover_gateway_endpoint(home, timeout=5))
if not start and recover and receipt.state == "absent" and owner_crashed(home):
- receipt = ensure_gateway_runtime(home, timeout=30)
+ receipt = ensure_gateway_runtime(home, timeout=30, idle_exit=True)
if receipt.state != "ready" or receipt.endpoint is None:
detail = f"\n{receipt.detail}" if receipt.reason_code == "runtime_exited" and receipt.detail else ""
raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}{detail}")