Skip to content

The agent that grows with you

feat(terminal): heartbeat notifications for long background processes

teknium165b0ff38eaf4
diff --git a/gateway/run.py b/gateway/run.py
index f5b6050130c..376873ad48d 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3057,7 +3057,7 @@ def _format_gateway_process_notification(evt: dict) -> "str | None":
text += "]"
return text
- if evt_type == "async_delegation":
+ if evt_type in ("async_delegation", "heartbeat"):
from tools.process_registry_notifications import format_process_notification
return format_process_notification(evt)
@@ -3076,7 +3076,8 @@ def _drain_gateway_watch_events(completion_queue) -> "list[dict]":
break
evt_type = evt.get("type", "completion")
if evt_type in {
- "watch_match", "watch_disabled", "watch_overflow_tripped", "watch_overflow_released"}:
+ "watch_match", "watch_disabled", "watch_overflow_tripped", "watch_overflow_released",
+ "heartbeat"}:
watch_events.append(evt)
elif evt_type == "async_delegation":
requeue.append(evt)
diff --git a/tests/tools/test_process_heartbeat.py b/tests/tools/test_process_heartbeat.py
new file mode 100644
index 00000000000..7c5f9626f72
--- /dev/null
+++ b/tests/tools/test_process_heartbeat.py
@@ -0,0 +1,82 @@
+"""Heartbeat notifications for long background processes.
+
+A ``heartbeat`` on a background process emits a periodic "still running + output since the last
+heartbeat" event on the completion queue so the agent stays current on a long bounded job (merge
+train, full suite, deploy) without polling. Invariants: each heartbeat carries only NEW output,
+heartbeats stop at exit, and the normal completion notice still fires.
+"""
+import json
+import queue
+import time
+
+import pytest
+
+import tools.process_registry as pr
+from tools.process_registry import ProcessRegistry
+
+
+def _drain(q: "queue.Queue") -> list:
+ out = []
+ while True:
+ try:
+ out.append(q.get_nowait())
+ except queue.Empty:
+ return out
+
+
+def _wait_until(pred, timeout: float, interval: float = 0.05) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if pred():
+ return True
+ time.sleep(interval)
+ return pred()
+
+
+def test_heartbeat_carries_only_new_output_and_stops_at_exit(tmp_path, monkeypatch):
+ monkeypatch.setattr(pr, "HEARTBEAT_MIN_SECONDS", 1)
+ monkeypatch.setattr(pr, "HEARTBEAT_TICK_SECONDS", 0.1)
+ registry = ProcessRegistry()
+ session = registry.spawn_local("echo first; sleep 2.5; echo second; sleep 2.5", cwd=str(tmp_path))
+ session.notify_on_complete = True
+ assert registry.arm_heartbeat(session, 1) == 1
+
+ assert _wait_until(lambda: registry.poll(session.id)["status"] != "running", timeout=20)
+ # Give the completion event a moment to be enqueued after the reader observes EOF.
+ assert _wait_until(lambda: any(e.get("type") == "completion" for e in list(registry.completion_queue.queue)),
+ timeout=5)
+ events = _drain(registry.completion_queue)
+ beats = [e for e in events if e["type"] == "heartbeat"]
+ completion = [e for e in events if e["type"] == "completion"]
+
+ assert len(beats) >= 2, events
+ assert [b["seq"] for b in beats] == list(range(1, len(beats) + 1))
+ assert all(b["session_id"] == session.id and b["interval"] == 1 for b in beats)
+ # Output is a delta: every produced line appears in exactly one heartbeat, never twice.
+ joined = "".join(b["output"] for b in beats)
+ assert joined.count("first") == 1 and joined.count("second") == 1, [b["output"] for b in beats]
+ assert len(completion) == 1
+ # Heartbeats never outlive the process: nothing after the completion notice.
+ assert events.index(completion[0]) > events.index(beats[-1])
+ assert not _wait_until(lambda: any(e.get("type") == "heartbeat" for e in list(registry.completion_queue.queue)),
+ timeout=2.5)
+
+
+def test_terminal_dispatch_heartbeat_implies_notify_and_refuses_foreground(monkeypatch):
+ from tools import terminal_tool as tt
+
+ captured = {}
+
+ def fake_terminal_tool(**kwargs):
+ captured.update(kwargs)
+ return json.dumps({"output": "Background process started", "session_id": "proc_x", "exit_code": 0})
+
+ monkeypatch.setattr(tt, "terminal_tool", fake_terminal_tool)
+ dispatch = tt._handle_terminal
+ fg = json.loads(dispatch({"command": "sleep 1", "heartbeat": 120}))
+ assert fg.get("error") and "background" in fg["error"]
+
+ bg = json.loads(dispatch({"command": "sleep 1", "background": True, "heartbeat": 120}))
+ assert "error" not in bg or not bg["error"]
+ assert captured["heartbeat"] == 120 and captured["notify_on_complete"] is True
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 588342f6fd1..922bb26685b 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -140,7 +140,7 @@ processes are killed at its teardown and their notices are suppressed in the par
(`process_registry.transfer_ownership`) so the completion routes and reaps by the new owner; un-handed leftovers land on
the result as `orphaned_processes`, exited-but-never-read notify processes as `unread_completions` (`_ChildRun.account_background_processes`, before `cleanup` kills them). **Child kernels:** a child's `execute_code` kernels are keyed `<parent-owner>::child::<child-session-id>`, pinned against the `max_session_kernels` LRU cap while the child runs and disposed by `cleanup` (`code_kernel.shutdown_kernels_for_delegated_child`) — never let a finished child's kernel squat the cap. **output_schema:** a miss after the one retry keeps `status: completed` with the raw text in `summary` plus `schema_valid: false` / `schema_errors` / `schema_note` — never discard a child's result. **Durability:** background
delegation is process-local; work that must survive restart uses `cronjob` or
-`terminal(background=True, notify_on_complete=True)`. **Stop fan-out:** a turn's hard interrupt reaches only
+`terminal(background=True, notify_on_complete=True)`. `heartbeat=N` on the same spawn emits a `heartbeat` event (type on the completion queue; delta output only, `HEARTBEAT_MIN_SECONDS` floor, one daemon timer thread for all sessions in `process_registry.py::ProcessRegistry._heartbeat_loop`) — every surface that renders `watch_match` must render `heartbeat` (`process_registry_notifications.py`, `gateway/run.py::_drain_gateway_watch_events`, `tui_gateway/session_notifications.py::_DEDUP_EXTRA_FIELDS`). **Stop fan-out:** a turn's hard interrupt reaches only
`_active_children`; background units are detached at dispatch, so every stop surface (gateway `/stop` busy AND
idle paths, TUI `session.interrupt`, ACP `cancel`, CLI `/stop` via `interrupt_all`) calls
`async_delegation.interrupt_for_session` too. Depth>0 delegations are always synchronous
diff --git a/tools/process_registry.py b/tools/process_registry.py
index fd37db9f879..be771756c08 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -74,6 +74,14 @@ WATCH_STRIKE_LIMIT = 3
# delivered this many matches over its whole life we disable it and fall back to notify_on_complete, same as
# the strike-limit path.
WATCH_LIFETIME_MAX_HITS = 8
+# Heartbeat: an opt-in periodic "still running, here is the output since last time" event for
+# long bounded jobs (merge trains, full test suites, deploys). Unlike watch patterns it is
+# time-driven, so it is bounded by construction (≤ 3600/HEARTBEAT_MIN_SECONDS events per hour
+# per process) and needs no strike/lifetime breaker. The floor exists so a model cannot turn
+# it into a 5-second poll; the output slice is capped like a completion notice.
+HEARTBEAT_MIN_SECONDS = 60
+HEARTBEAT_OUTPUT_CHARS = 2000
+HEARTBEAT_TICK_SECONDS = 5
# Global circuit breaker across all sessions so concurrent siblings can't collectively
# flood the user even when each is under its own cap.
WATCH_GLOBAL_MAX_PER_WINDOW = 15
@@ -536,6 +544,11 @@ class ProcessSession:
notify_on_complete: bool = False # Queue agent notification on exit
completion_output_chars: int = 0 # Output chars the completion carries; 0 = COMPLETION_OUTPUT_CHARS
watch_patterns: List[str] = field(default_factory=list)
+ heartbeat_seconds: int = 0 # 0 = off; else a "heartbeat" event every N s while running
+ total_output_chars: int = 0 # Chars ever ingested (the buffer is a rolling tail)
+ _heartbeat_last: float = field(default=0.0, repr=False) # time of the last heartbeat (or spawn)
+ _heartbeat_total_at_last: int = field(default=0, repr=False) # total_output_chars at that moment
+ _heartbeat_seq: int = field(default=0, repr=False)
_watch_hits: int = field(default=0, repr=False) # total matches delivered
_watch_suppressed: int = field(default=0, repr=False) # matches dropped by rate limit
_watch_disabled: bool = field(default=False, repr=False) # permanently killed after strike limit
@@ -552,6 +565,7 @@ class ProcessSession:
"""Append to the rolling output buffer under the session lock, keeping the tail."""
with self._lock:
self.output_buffer += text
+ self.total_output_chars += len(text)
if len(self.output_buffer) > self.max_output_chars:
self.output_buffer = self.output_buffer[-self.max_output_chars:]
@@ -574,7 +588,8 @@ _CHECKPOINT_FIELDS = (
"command", "pid", "pid_scope", "host_start_time", "systemd_unit", "cwd",
"started_at", "task_id", "owner_task_id", "session_key",
*(f"watcher_{k}" for k in _WATCHER_ROUTE_KEYS), "watcher_interval",
- "parent_session_id", "notify_on_complete", "completion_output_chars", "watch_patterns")
+ "parent_session_id", "notify_on_complete", "completion_output_chars", "watch_patterns",
+ "heartbeat_seconds")
_CHECKPOINT_DEFAULTS = {
f.name: ([] if f.name == "watch_patterns" else f.default)
for f in ProcessSession.__dataclass_fields__.values()
@@ -626,6 +641,60 @@ class ProcessRegistry(ProcessCheckpointMixin):
# a read-only terminal tab without killing the process.
self.on_output = None
self.on_close = None
+ self._heartbeat_thread: Optional[threading.Thread] = None
+
+ # ── heartbeat ───────────────────────────────────────────────────────────
+ def arm_heartbeat(self, session: ProcessSession, seconds: int) -> int:
+ """Enable periodic heartbeat events for ``session``; returns the effective interval."""
+ seconds = max(int(seconds), HEARTBEAT_MIN_SECONDS)
+ session.heartbeat_seconds = seconds
+ session._heartbeat_last = time.time()
+ session._heartbeat_total_at_last = session.total_output_chars
+ self._ensure_heartbeat_thread()
+ return seconds
+
+ def _ensure_heartbeat_thread(self) -> None:
+ with self._lock:
+ if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive():
+ return
+ self._heartbeat_thread = threading.Thread(
+ target=self._heartbeat_loop, name="process-heartbeat", daemon=True)
+ self._heartbeat_thread.start()
+
+ def _heartbeat_loop(self) -> None:
+ """One daemon thread for every heartbeat session: reader threads block on the pipe and
+ cannot keep time, and a per-process timer would leak one thread per job."""
+ while True:
+ time.sleep(HEARTBEAT_TICK_SECONDS)
+ now = time.time()
+ with self._lock:
+ due = [s for s in self._running.values()
+ if s.heartbeat_seconds > 0 and not s.exited
+ and now - s._heartbeat_last >= s.heartbeat_seconds]
+ for session in due:
+ self._emit_heartbeat(session, now)
+
+ def _emit_heartbeat(self, session: ProcessSession, now: float) -> None:
+ with session._lock:
+ delta = session.total_output_chars - session._heartbeat_total_at_last
+ output = session.output_buffer[-delta:] if delta > 0 else ""
+ session._heartbeat_total_at_last = session.total_output_chars
+ if len(output) > HEARTBEAT_OUTPUT_CHARS:
+ cut = len(output) - HEARTBEAT_OUTPUT_CHARS
+ output = f"...({cut} earlier characters omitted)\n" + output[-HEARTBEAT_OUTPUT_CHARS:]
+ session._heartbeat_last = now
+ session._heartbeat_seq += 1
+ notification = {
+ **self._watch_event_base(session),
+ "type": "heartbeat",
+ "seq": session._heartbeat_seq,
+ "interval": session.heartbeat_seconds,
+ "elapsed": int(now - session.started_at) if session.started_at else 0,
+ "output": output,
+ "started_at": session.started_at,
+ }
+ _redact_process_result(notification)
+ self.completion_queue.put(notification)
@staticmethod
def _clean_shell_noise(text: str) -> str:
diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py
index 5301fcc640c..14494a2cec3 100644
--- a/tools/process_registry_notifications.py
+++ b/tools/process_registry_notifications.py
@@ -413,6 +413,13 @@ def format_process_notification(evt: dict) -> "str | None":
if evt.get("handoff_note"):
_attribution = f"Handed off to you by a subagent before it finished. Purpose: {evt['handoff_note']}"
attribution = f"{_attribution}\n" if _attribution else ""
+ if evt_type == "heartbeat":
+ _out = evt.get("output") or "(no new output since the last heartbeat)"
+ return (
+ f"[Background process {_sid} heartbeat #{evt.get('seq', '?')} — still running after "
+ f"{_format_age(float(evt.get('elapsed') or 0))} (next in {evt.get('interval', '?')}s; "
+ f"you will also be told when it exits).\n"
+ f"{attribution}Command: {_cmd}\nOutput since last heartbeat:\n{_out}]")
if evt_type == "watch_match":
_sup = evt.get("suppressed", 0)
return (
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 0fd053439ce..c80938c34df 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -1234,6 +1234,7 @@ def terminal_tool(
watch_patterns: Optional[List[str]] = None,
_host_local: bool = False,
_completion_output_chars: int = 0,
+ heartbeat: int = 0,
) -> str:
"""Execute *command* in the configured terminal environment; returns a JSON string.
@@ -1244,7 +1245,9 @@ def terminal_tool(
background-only flags: on conflict watch_patterns is dropped. watch_patterns
is hard rate-limited (1 notification / 15s / process) and auto-disabled
after repeated strikes or a lifetime cap, promoting to notify_on_complete —
- use it only for rare one-shot signals on long-lived processes.
+ use it only for rare one-shot signals on long-lived processes. ``heartbeat`` (seconds,
+ background-only, implies notify_on_complete) emits a "still running + output since last
+ time" event every N seconds so the agent stays current on a long job without polling.
``_completion_output_chars`` (internal) sizes the completion notification's output for a
spawner whose output is the payload (a bot DM's reply); 0 keeps the usual tail.
``_host_local`` forces the local backend for Hermes-owned control-plane
@@ -1312,6 +1315,7 @@ def terminal_tool(
watch_patterns=watch_patterns, approval_note=verdict.note,
pty_disabled_reason=_PTY_DISABLED_REASON if pty_disabled else None,
completion_output_chars=_completion_output_chars,
+ heartbeat_seconds=heartbeat,
)
if plan.promoted_from_foreground_timeout is not None:
result = _with_promoted_note(result, plan.promoted_from_foreground_timeout)
@@ -1379,6 +1383,11 @@ TERMINAL_SCHEMA = {
{"type": "boolean"},
{"type": "array", "items": {"type": "string"}}
]
+ },
+ "heartbeat": {
+ "type": "integer",
+ "minimum": 60,
+ "description": "With background=true: every N seconds (min 60) you get a heartbeat notification carrying the output produced since the last one, plus the normal exit notification (implies notify=true). Use it for long bounded jobs you must stay on top of (a merge train, a full test suite, a deploy) so you react to a failure within N seconds instead of at exit; leave it off for short jobs and silent daemons."
}
# Legacy aliases (unadvertised, still accepted): notify_on_complete
# (bool) and watch_patterns (list). notify=true|[...] maps onto
@@ -1407,11 +1416,14 @@ def _handle_terminal(args, **kw):
notify = args.get("notify")
notify_on_complete = args.get("notify_on_complete", False)
watch_patterns = args.get("watch_patterns")
+ heartbeat = args.get("heartbeat") or 0
+ if not isinstance(heartbeat, int) or isinstance(heartbeat, bool) or heartbeat < 0:
+ return tool_error("heartbeat must be a whole number of seconds (min 60).")
if not args.get("background", False):
- if notify or watch_patterns or notify_on_complete:
+ if notify or watch_patterns or notify_on_complete or heartbeat:
return tool_error(
- "notify only applies to background commands (foreground "
- "results return directly). Either drop notify, or run as "
+ "notify/heartbeat only apply to background commands (foreground "
+ "results return directly). Either drop them, or run as "
"terminal(command=..., background=true, notify=...)."
)
if args.get("pty", False):
@@ -1433,6 +1445,8 @@ def _handle_terminal(args, **kw):
"notify must be true/false (notify on exit) or a list of "
"strings (notify on output pattern match)."
)
+ if heartbeat:
+ notify_on_complete = True # the heartbeat rides the completion delivery path
return terminal_tool(
command=args.get("command"),
background=args.get("background", False),
@@ -1443,6 +1457,7 @@ def _handle_terminal(args, **kw):
pty=args.get("pty", False),
notify_on_complete=notify_on_complete,
watch_patterns=watch_patterns,
+ heartbeat=heartbeat,
)
diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.py
index 7ec5b735846..4fe822a7744 100644
--- a/tools/terminal_tool_background.py
+++ b/tools/terminal_tool_background.py
@@ -144,6 +144,7 @@ def spawn_background_process(
notify_on_complete: bool, watch_patterns: Optional[List[str]], approval_note: Optional[str],
completion_output_chars: int = 0,
pty_disabled_reason: Optional[str],
+ heartbeat_seconds: int = 0,
) -> str:
"""Spawn *command* as a tracked background process and return the JSON result.
@@ -196,6 +197,12 @@ def spawn_background_process(
if is_delegated_child_context():
result_data["notify_on_complete"] = False
result_data["subagent_note"] = _SUBAGENT_NOTIFY_NOTE
+ elif heartbeat_seconds:
+ # Heartbeats ride the same delivery path as the completion notice, so they are
+ # only armed where that notice can actually reach the agent.
+ result_data["heartbeat_seconds"] = process_registry.arm_heartbeat(proc_session, heartbeat_seconds)
+ elif heartbeat_seconds:
+ result_data["heartbeat_ignored"] = "heartbeat needs notify=true delivery, which this session cannot receive"
if watch_patterns:
proc_session.watch_patterns = list(watch_patterns)
result_data["watch_patterns"] = proc_session.watch_patterns
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index b771e8c8205..74818a4c3fa 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -112,6 +112,7 @@ def _notification_event_requires_owner(evt: dict) -> bool:
# one process can match patterns many times, so their content is part of the key.
_DEDUP_EXTRA_FIELDS = {
"watch_match": ("command", "pattern", "output", "suppressed", "message_id"),
+ "heartbeat": ("seq",),
"watch_disabled": ("command", "message", "suppressed"),
"watch_overflow_": ("command", "message", "suppressed"), # prefix match
}
diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.md
index d79d5f3663b..6f8213b443e 100644
--- a/website/docs/reference/tools-reference.md
+++ b/website/docs/reference/tools-reference.md
@@ -197,7 +197,7 @@ Tools for driving desktop [Projects](../user-guide/cli.md) — named, multi-fold
| Tool | Description | Requires environment |
|------|-------------|----------------------|
| `process_manage` | Manage background processes started with terminal(background=true). Actions: 'list' (show all), 'poll' (check status + new output), 'log' (full output with pagination), 'wait' (block until done or timeout), 'kill' (terminate), 'write' (sen… | — |
-| `terminal` | Execute shell commands on a Linux environment. Filesystem persists between calls. Set `background=true` for long-running servers. Set `notify_on_complete=true` (with `background=true`) to get an automatic notification when the process finishes — no polling needed. Do NOT use cat/head/tail — use read_file. Do NOT use grep/rg/find — use search_files. | — |
+| `terminal` | Execute shell commands on a Linux environment. Filesystem persists between calls. Set `background=true` for long-running servers. Set `notify_on_complete=true` (with `background=true`) to get an automatic notification when the process finishes — no polling needed. Add `heartbeat=N` (seconds, min 60) to also receive a periodic notification carrying the output produced since the previous one — for long bounded jobs such as a merge train or a full test suite, so a failure is seen within N seconds instead of at exit. Do NOT use cat/head/tail — use read_file. Do NOT use grep/rg/find — use search_files. | — |
## `desktop_ui` toolset