Skip to content

The agent that grows with you

fix(process): stop re-waiting on a quiet background process; notify on exit instead

Teknium33a25058b200
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index a617aa15e33..59222a67c7f 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -431,6 +431,9 @@ terminal:
home_mode: "auto"
docker_mount_cwd_to_workspace: false # SECURITY: off by default. Opt in to mount the launch cwd into Docker /workspace.
lifetime_seconds: 300
+ # Two process_manage wait/poll calls in a row with no new output on a running background process
+ # turn on notify_on_complete for it and tell the agent to stop checking; false = poll as before.
+ process_wait_auto_notify: true
# A `hermes` / `hermes --tui` session's local tools (terminal, background processes, execute_code)
# start with the launching shell's toolchain: PATH, an activated venv and CONDA_* / NODE_* / NVM_* /
# PYENV_* (plus GOPATH, GOROOT, CARGO_HOME, RUSTUP_HOME, JAVA_HOME), for that session only, when
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 6bdd879736f..9efeaa94c72 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -320,9 +320,8 @@ DEFAULT_CONFIG = {
# immediately kills the delivery (e.g. Bot Mode handoff replies via message_agent /
# bot_relay). Plain background processes without notify_on_complete are never waited on. 0
# disables.
- # Bounded linger (seconds) for one-shot CLI runs (-q/-Q/-z) that exit while background processes
- # spawned with notify_on_complete=true are still running. See #90879.
"oneshot_completion_wait_seconds": 600.0,
+ "process_wait_auto_notify": True, # 2 unchanged wait/poll -> notify_on_complete + stop; False = old polling
# Env vars passed into sandboxed terminal/execute_code (plus skill-declared required_environment_variables).
"env_passthrough": [],
"client_env_passthrough": [], # Extra non-secret toolchain names a CLI/TUI client sends for its tools
diff --git a/tests/tools/test_process_wait_auto_notify.py b/tests/tools/test_process_wait_auto_notify.py
new file mode 100644
index 00000000000..1699336c083
--- /dev/null
+++ b/tests/tools/test_process_wait_auto_notify.py
@@ -0,0 +1,42 @@
+"""Repeated process_manage wait/poll on a silent running process promotes it to notify_on_complete."""
+
+import json
+
+import pytest
+
+import tools.process_registry as pr
+
+
+def sleeper(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ session = pr.process_registry.spawn_local("sleep 30", cwd=str(tmp_path), task_id="t-autonotify")
+ session.notify_on_complete = False
+ yield home, session
+ pr.process_registry.kill_process(session.id)
+
+
+def _wait(sid):
+ return json.loads(pr._handle_process({"action": "wait", "session_id": sid, "timeout": 1}))
+
+
+def test_second_unchanged_wait_enables_notify_and_tells_model_to_stop(sleeper):
+ _home, session = sleeper
+ first = _wait(session.id)
+ assert first["status"] == "timeout" and not session.notify_on_complete
+ second = _wait(session.id)
+ assert second["status"] == "timeout" and second["process_running"] is True
+ assert session.notify_on_complete is True
+ assert "Do NOT call process_manage wait or poll" in second["timeout_note"]
+
+
+def test_opt_out_keeps_plain_polling(sleeper):
+ home, session = sleeper
+ (home / "config.yaml").write_text("terminal:\n process_wait_auto_notify: false\n", encoding="utf-8")
+ for _ in range(3):
+ result = _wait(session.id)
+ assert result["status"] == "timeout"
+ assert "Poll again later" in result["timeout_note"] and "notify_on_complete" not in result
+ assert session.notify_on_complete is False
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 436f00b8f8a..e1949b6bbe2 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -2038,8 +2038,6 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
exited, finalizing = session.exited, self._reader_finalizing(session)
lines = full_output.splitlines()
total_lines = len(lines)
- # offset=None -> last N lines; an explicit offset=0 means the HEAD (don't
- # conflate the two via falsiness).
# An explicit offset=0 means "start from the first line" — previously it was conflated with the
# default and silently returned the TAIL instead of the head (same falsy-coercion class as the
# wait() timeout guard; salvaged from PR #60004, credit @isheng-eqi).
@@ -2753,7 +2751,8 @@ def _handle_process(args, **kw):
if not session_id:
return tool_error(f"session_id is required for {action}")
handler, redact = _SESSION_ACTIONS[action]
- result = handler(session_id, args)
+ from tools.process_registry_wait_policy import apply_wait_poll_policy
+ result = apply_wait_poll_policy(action, session_id, handler(session_id, args))
return json.dumps(_redact_process_result(result) if redact else result, ensure_ascii=False)
return tool_error(f"Unknown process action: {action}. Use: list, poll, log, wait, kill, write, submit, close, handoff")
diff --git a/tools/process_registry_wait_policy.py b/tools/process_registry_wait_policy.py
new file mode 100644
index 00000000000..1217acd95c2
--- /dev/null
+++ b/tools/process_registry_wait_policy.py
@@ -0,0 +1,130 @@
+"""Stop repeated ``process_manage`` wait/poll calls on a silent running process.
+
+Models re-issue byte-identical ``wait``/``poll`` calls on a background process that has printed
+nothing new; each repeat is a full model turn. After ``_PROMOTE_AFTER`` consecutive wait/poll results
+with no new output, this promotes the session to ``notify_on_complete`` (wiring gateway delivery when
+the process was started silently) and tells the model to stop checking: the exit arrives as a message.
+
+Only where a completion can actually reach this agent: one-shot runners (``hermes -z``), cron, Kanban
+workers, stateless HTTP sessions and delegated subagents keep the old result, since nothing would
+deliver the notice there. ``terminal.process_wait_auto_notify: false`` restores the old behaviour
+everywhere.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+
+logger = logging.getLogger(__name__)
+
+_PROMOTE_AFTER = 2
+_MAX_TRACKED = 512
+# session id -> (total_output_chars at the last wait/poll, consecutive unchanged count)
+_state: dict[str, tuple[int, int]] = {}
+_state_lock = threading.Lock()
+
+_STOP_NOTE = (
+ "The process is still running and has printed nothing new since your last check. Hermes has turned on "
+ "notify_on_complete for it: when it exits, a message with its exit code and final output starts a new turn "
+ "automatically, even after you end this turn. Do NOT call process_manage wait or poll on {sid} again, and do "
+ "not sleep or loop to wait for it. If you have other work, do it now; otherwise end your turn with a one-line "
+ "status and report the result when the completion message arrives."
+)
+
+
+def _enabled() -> bool:
+ """``terminal.process_wait_auto_notify`` (default true); true when config is unreadable."""
+ from tools.process_registry import ProcessRegistry
+ try:
+ return bool(ProcessRegistry._config_value("terminal", "process_wait_auto_notify", True))
+ except Exception: # a broken config.yaml must not break process_manage
+ logger.debug("process_wait_auto_notify unreadable; using default", exc_info=True)
+ return True
+
+
+def _forget(session_id: str) -> None:
+ with _state_lock:
+ _state.pop(session_id, None)
+
+
+def _count_unchanged(session) -> int:
+ """Record one still-running wait/poll observation; return the consecutive no-new-output count."""
+ total = int(getattr(session, "total_output_chars", 0) or 0)
+ with _state_lock:
+ # Baseline is the spawn (0 chars observed): the first check on a silent process already counts.
+ last_total, count = _state.get(session.id, (0, 0))
+ count = count + 1 if total == last_total else 0
+ _state[session.id] = (total, count)
+ while len(_state) > _MAX_TRACKED:
+ _state.pop(next(iter(_state)))
+ return count
+
+
+def _can_deliver_completion() -> bool:
+ """Whether a completion notice for this session can reach the agent that is waiting.
+
+ Finite turns (``hermes chat -q`` / ``-z``, as ``delegate_task`` decides inline execution) end
+ the run when the turn ends, so a promised notice would never arrive."""
+ from agent.delegation_context import is_delegated_child_context
+ from gateway.session_context import async_delivery_supported, get_session_env
+ from gateway.session_finite import finite_turn_required
+ finite = finite_turn_required()
+ if finite is True or (finite is None and get_session_env("HERMES_SINGLE_QUERY_SESSION") == "1"):
+ return False
+ return async_delivery_supported() and not is_delegated_child_context()
+
+
+def _promote(registry, session) -> None:
+ """Turn on completion delivery for a process spawned without it, on every surface.
+
+ CLI, TUI/Desktop and ``hermes chat -q`` drain ``completion_queue``, which the exit path fills
+ whenever the flag is set. The messaging gateway delivers only through a per-process watcher, so a
+ process started silently also needs the chat routing stamped and a watcher armed."""
+ from tools.terminal_tool_background import _register_completion_watcher, _stamp_gateway_routing
+ from gateway.session_context import get_session_env
+ session.notify_on_complete = True
+ if not session.watcher_platform:
+ _stamp_gateway_routing(session, get_session_env)
+ # watcher_interval is set only by _register_completion_watcher: 0 means no watcher yet.
+ if session.watcher_platform and not session.watcher_interval:
+ _register_completion_watcher(registry, session, session.session_key)
+ try:
+ registry._write_checkpoint()
+ except Exception:
+ logger.debug("checkpoint after auto-notify promotion failed", exc_info=True)
+ logger.info("process %s: repeated wait/poll with no new output; auto-enabled notify_on_complete", session.id)
+
+
+def apply_wait_poll_policy(action: str, session_id: str, result: dict) -> dict:
+ """Post-process one ``process_manage`` session action result (see module docstring)."""
+ if not isinstance(result, dict) or not _enabled():
+ return result
+ from tools.process_registry import process_registry
+ session = process_registry.get(session_id)
+ if session is None:
+ return result
+ if action == "wait":
+ running = result.get("status") == "timeout"
+ elif action == "poll":
+ running = result.get("status") == "running"
+ else:
+ running = False
+ if not running:
+ # Exit, any other action on the session, or a released/interrupted wait starts over.
+ if action not in ("wait", "poll") or result.get("status") != "interrupted":
+ _forget(session.id)
+ return result
+ if session.exited or _count_unchanged(session) < _PROMOTE_AFTER or not _can_deliver_completion():
+ return result
+ if not session.notify_on_complete:
+ _promote(process_registry, session)
+ note = _STOP_NOTE.format(sid=session.id)
+ result["notify_on_complete"] = True
+ if action == "wait":
+ clamp = result.get("timeout_note", "")
+ clamp = clamp.split(". Wait window", 1)[0] + ". " if clamp.startswith("Requested wait") else ""
+ result["timeout_note"] = clamp + note
+ else:
+ result["note"] = note
+ return result
diff --git a/website/docs/user-guide/features/tools.md b/website/docs/user-guide/features/tools.md
index e74d70b2f0f..f08b7a0557d 100644
--- a/website/docs/user-guide/features/tools.md
+++ b/website/docs/user-guide/features/tools.md
@@ -245,6 +245,25 @@ wrappers, command substitutions (`$(...)`, backticks, `<(...)`) and commands
whose approval category would change without the `&` are still refused with
guidance, because Hermes cannot safely tell which part should keep running.
+### Repeated waits on a quiet process
+
+When the agent calls `process(action="wait")` or `process(action="poll")` twice in a row on a
+process that is still running and has printed nothing new, Hermes turns on `notify_on_complete`
+for that process and the result tells the agent to stop checking: the exit (code and final output)
+arrives later as its own message, so the agent can do other work or end its turn instead of
+spending a model call on every unchanged check. New output, the process exiting, or any other
+action on that process resets the count.
+
+This applies where a completion can reach the agent: the interactive CLI, the TUI and desktop app,
+`hermes chat -q`, and messaging chats. One-shot `hermes -z` runs, cron jobs, Kanban workers,
+stateless API requests and delegated subagents cannot receive a later completion, so they keep the
+previous behaviour. To keep plain polling everywhere, set:
+
+```yaml
+terminal:
+ process_wait_auto_notify: false
+```
+
Completed background commands retain their exit status and captured output in the
active profile. Resume the conversation that launched the command (or its
compressed continuation), then use the original `session_id` with