Skip to content

The agent that grows with you

fix: wake idle process watches on their owning profile transport

Teknium9ee3d129b419
diff --git a/evals/gateway_completion/README.md b/evals/gateway_completion/README.md
new file mode 100644
index 00000000000..9c819dca714
--- /dev/null
+++ b/evals/gateway_completion/README.md
@@ -0,0 +1,21 @@
+# Completion delivery lifecycle probe
+
+Run with a fresh HOME and HERMES_HOME using the repository virtualenv:
+
+```sh
+probe=$(mktemp -d)
+HOME="$probe" HERMES_HOME="$probe/state" .venv/bin/python evals/gateway_completion/delivery_lifecycle.py
+```
+
+No remote model or Discord credentials are used. The probe starts actual terminal subprocesses,
+process-reader threads and async delegation workers; it uses the actual DiscordAdapter and
+runner lifecycle with only outbound transport and model boundary replaced locally. It checks
+notify completion, idle watch matching, raw notice-only behavior, async completion delivery,
+and unavailable raw API-owner retention. `HERMES_EVAL_REPO` selects another checkout for A/B.
+
+On base 03f3b09222b: terminal notify control succeeds, idle watch stays queued with zero turns
+and the probe fails. Fixed: idle watch wakes once, the later post-turn hook adds no duplicate,
+normal async Discord completion is delivered, and missing API transport remains pending at zero
+attempts. Durable restart evidence additionally used ten fresh subprocesses sharing SQLite:
+base exhausted eight attempts and dropped; fixed stayed pending/zero then delivered both batch
+siblings at one attempt, with one API delivery row and no model turn.
diff --git a/evals/gateway_completion/delivery_lifecycle.py b/evals/gateway_completion/delivery_lifecycle.py
new file mode 100644
index 00000000000..0908c9765a1
--- /dev/null
+++ b/evals/gateway_completion/delivery_lifecycle.py
@@ -0,0 +1,226 @@
+import os, sys, asyncio, json, tempfile, types
+from pathlib import Path
+
+ROOT = os.environ.get("HERMES_EVAL_REPO", str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, ROOT)
+HOME = Path(os.environ["HERMES_HOME"])
+HOME.mkdir(parents=True, exist_ok=True)
+(HOME / "config.yaml").write_text(
+ "display:\n background_process_notifications: concise\n"
+)
+from gateway.run import GatewayRunner
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from plugins.platforms.discord.adapter import DiscordAdapter
+from gateway.platforms.base import SendResult
+from gateway.session_context import set_session_vars, clear_session_vars
+from tools.terminal_tool_background import spawn_background_process
+from tools.process_registry import process_registry as pr
+import gateway.run_notifications as rn
+
+print("SOURCE", rn.__file__, "HOME", HOME)
+
+
+async def main():
+ runner = GatewayRunner(GatewayConfig())
+ adapter = DiscordAdapter(PlatformConfig())
+ runner.adapters[Platform.DISCORD] = adapter
+ turns = []
+ sends = []
+
+ async def agent_boundary(event, *args, **kwargs):
+ turns.append({
+ "text": event.text,
+ "internal": event.internal,
+ "chat": event.source.chat_id,
+ })
+ return "FAKE_MODEL_BOUNDARY reached"
+
+ async def send_boundary(chat_id, content, *args, **kwargs):
+ sends.append({"chat": chat_id, "text": content})
+ return SendResult(success=True, message_id=str(len(sends)))
+
+ async def typing_boundary(*a, **kw):
+ pass
+
+ runner._handle_message_with_agent = agent_boundary
+ adapter.send = send_boundary
+ adapter.send_typing = typing_boundary
+ adapter.set_message_handler(runner._handle_message)
+ runner._running = True
+ idle = asyncio.create_task(runner._async_delegation_watcher(interval=0.05))
+ key = "agent:main:discord:dm:123"
+
+ def spawn(label, notify=False, patterns=None):
+ tokens = set_session_vars(
+ platform="discord",
+ chat_id="123",
+ chat_type="dm",
+ session_key=key,
+ user_id="456",
+ )
+ try:
+ result = json.loads(
+ spawn_background_process(
+ command=f'sleep 0.3; printf "{label}\\n"',
+ env=types.SimpleNamespace(env=None),
+ env_type="local",
+ effective_task_id=label,
+ task_id=label,
+ session_key=key,
+ workdir=str(HOME),
+ cwd=str(HOME),
+ effective_pty=False,
+ notify_on_complete=notify,
+ watch_patterns=patterns,
+ approval_note=None,
+ pty_disabled_reason=None,
+ )
+ )
+ finally:
+ clear_session_vars(tokens)
+ assert "session_id" in result, result
+ return result
+
+ async def settle():
+ for _ in range(200):
+ if not adapter._background_tasks:
+ return
+ await asyncio.sleep(0.025)
+ raise RuntimeError("adapter tasks did not settle")
+
+ # Real spawn, reader thread, durable process output and actual post-turn scheduling.
+ result = spawn("NOTIFY_OK", notify=True)
+ await runner._hmwa_post_turn_hooks({}, {}, "")
+ await asyncio.sleep(5.5)
+ await settle()
+ print("NOTIFY_TRUE", json.dumps({"spawn": result, "turns": turns, "sends": sends}))
+ assert len(turns) == 1 and turns[0]["internal"] and "NOTIFY_OK" in turns[0]["text"]
+ turns.clear()
+ sends.clear()
+ # Pattern arrives after post-turn drain while idle watcher remains running.
+ result = spawn("READY_AUDIT", patterns=["READY_AUDIT"])
+ await runner._hmwa_post_turn_hooks({}, {}, "")
+ await asyncio.sleep(1)
+ print(
+ "WATCH_IDLE",
+ json.dumps({
+ "spawn": result,
+ "turns": turns,
+ "queue_types": [e["type"] for e in list(pr.completion_queue.queue)],
+ }),
+ )
+ assert len(turns) == 1
+ assert not any(e["type"] == "watch_match" for e in list(pr.completion_queue.queue))
+ # Same hook that a subsequent user turn executes, with no synthetic queue fabrication.
+ await runner._hmwa_post_turn_hooks({}, {}, "")
+ await settle()
+ print("WATCH_AFTER_NEXT_POST_TURN", json.dumps({"turns": turns, "sends": sends}))
+ assert len(turns) == 1 and "READY_AUDIT" in turns[0]["text"]
+ turns.clear()
+ sends.clear()
+ # Raw legacy/restored watcher deliberately only sends a notice without a model turn.
+ result = spawn("RAW_NOTICE")
+ await runner._run_process_watcher({
+ "session_id": result["session_id"],
+ "check_interval": 0.05,
+ "session_key": key,
+ "platform": "discord",
+ "chat_id": "123",
+ "notify_on_complete": False,
+ })
+ await settle()
+ print(
+ "RAW_NOTIFICATION_ONLY",
+ json.dumps({"turns": turns, "sends": sends, "spawn": result}),
+ )
+ assert not turns and len(sends) == 1
+ # Real async executor/ledger/queue; only child model replaced by a local subprocess.
+ from tools.async_delegation import dispatch_async_delegation, get_durable_delegation
+ import subprocess
+
+ def local_child():
+ output = subprocess.check_output(
+ ["/bin/sh", "-c", "printf CHILD_LOCAL_DONE"], text=True
+ )
+ (HOME / "child-artifact.txt").write_text(output)
+ return {"summary": output, "status": "completed", "api_calls": 0}
+
+ async def dispatch_case(route):
+ h = dispatch_async_delegation(
+ goal="local lifecycle",
+ context=None,
+ toolsets=None,
+ role="leaf",
+ model=None,
+ session_key=route,
+ runner=local_child,
+ )
+ for _ in range(100):
+ row = get_durable_delegation(h["delegation_id"])
+ if row and row.get("delivery_attempts", 0) > 0:
+ break
+ await asyncio.sleep(0.05)
+ await settle()
+ return h, get_durable_delegation(h["delegation_id"])
+
+ turns.clear()
+ sends.clear()
+ h, row = await dispatch_case(key)
+ print(
+ "ASYNC_DISCORD_IDLE",
+ json.dumps({
+ "handle": h,
+ "delivery_state": row["delivery_state"],
+ "attempts": row["delivery_attempts"],
+ "turns": turns,
+ }),
+ )
+ assert len(turns) == 1 and row["delivery_state"] == "delivered"
+ turns.clear()
+ sends.clear()
+ h, row = await dispatch_case("raw_session_without_api_adapter")
+ print(
+ "ASYNC_RAW_NO_TRANSPORT",
+ json.dumps({
+ "handle": h,
+ "delivery_state": row["delivery_state"],
+ "attempts": row["delivery_attempts"],
+ "queue_size": pr.completion_queue.qsize(),
+ "turns": turns,
+ }),
+ )
+ assert (
+ not turns
+ and row["delivery_state"] == "pending"
+ and row["delivery_attempts"] == 0
+ and not pr.completion_queue.empty()
+ )
+ # Two real adapters: private completion must never enter the primary bot.
+ secondary = DiscordAdapter(PlatformConfig())
+ secondary_turns = []
+
+ async def secondary_boundary(event):
+ secondary_turns.append(event.source.profile)
+ return None
+
+ secondary.set_message_handler(secondary_boundary)
+ secondary.send_typing = typing_boundary
+ runner._profile_adapters = {"research": {Platform.DISCORD: secondary}}
+ turns.clear()
+ evt = {"session_key": "agent:research:discord:dm:123", "type": "completion"}
+ assert await runner._inject_watch_notification("private completion", evt) is True
+ for task in list(secondary._background_tasks):
+ await task
+ assert secondary_turns == ["research"] and not turns
+ runner._profile_adapters = {}
+ assert await runner._inject_watch_notification("private completion", evt) is False
+ assert not turns
+ print("MULTIPLEX", json.dumps({"secondary": secondary_turns, "primary": turns}))
+ runner._running = False
+ idle.cancel()
+ await asyncio.gather(idle, return_exceptions=True)
+ await runner._cancel_process_completion_batch_tasks()
+ print("PASS all lifecycle assertions")
+
+
+asyncio.run(main())
diff --git a/gateway/AGENTS.md b/gateway/AGENTS.md
index 21ee4f3c250..df8b2dfd5ee 100644
--- a/gateway/AGENTS.md
+++ b/gateway/AGENTS.md
@@ -64,6 +64,13 @@ completion and triggers a new agent turn. Verbosity: `display.background_process
tail), `all` (running updates + final raw output), `result` (final raw output only), `error`
(final raw output only on non-zero exit), `off`.
+The idle completion watcher also drains `watch_match` / `watch_disabled`; no user follow-up is
+required. Notify-off drains these without waking. Transport failures are retried; unavailable
+durable completion owners/transports do not spend delivery attempts. Profile-namespaced process
+events keep their owning adapter, including raw progress/final notices. Adapter acceptance is
+at-least-once admission, not proof that a model turn or final outbound reply completed. API-server
+async completions remain durable delivery rows, never autonomous new model turns.
+
Cron deliveries are NOT mirrored into the target gateway session — they land in their own cron
session with a header/footer frame so the main conversation's role alternation stays intact
(`cron/AGENTS.md`).
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index d4eda13ee5f..060786947e0 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -762,6 +762,8 @@ class GatewayNotificationsMixin:
from gateway.run import _parse_session_key
session_key = str(evt.get("session_key") or "").strip()
derived = {}
+ parts = session_key.split(":")
+ profile = parts[1] if len(parts) >= 5 and parts[0] == "agent" and parts[1] != "main" else None
if session_key:
try:
self.session_store._ensure_loaded()
@@ -773,7 +775,8 @@ class GatewayNotificationsMixin:
cached_source = self._get_cached_session_source(session_key)
if cached_source is not None:
return cached_source
- derived = _parse_session_key(session_key) or {}
+ parse_key = ":".join(["agent", "main", *parts[2:]]) if profile else session_key
+ derived = _parse_session_key(parse_key) or {}
platform_name = str(evt.get("platform") or derived.get("platform") or "").strip().lower()
chat_type = str(evt.get("chat_type") or derived.get("chat_type") or "").strip().lower()
chat_id = str(evt.get("chat_id") or derived.get("chat_id") or "").strip()
@@ -812,7 +815,7 @@ class GatewayNotificationsMixin:
)
return SessionSource(
platform=platform, chat_id=chat_id, chat_type=chat_type, thread_id=_opt("thread_id"),
- user_id=_opt("user_id"), user_name=_opt("user_name"), scope_id=scope_id,
+ user_id=_opt("user_id"), user_name=_opt("user_name"), scope_id=scope_id, profile=profile,
)
async def _drain_watch_notifications(self, completion_queue) -> None:
@@ -831,8 +834,13 @@ class GatewayNotificationsMixin:
synth_text = _format_gateway_process_notification(evt)
if not synth_text:
continue
- with _log_suppressed(logging.ERROR, "Watch notification injection error: %s"):
- await self._inject_watch_notification(synth_text, evt)
+ try:
+ delivered = await self._inject_watch_notification(synth_text, evt)
+ except Exception:
+ logger.exception("Watch notification injection error")
+ delivered = False
+ if delivered is False:
+ completion_queue.put(evt)
def _adapter_by_platform_value(self, platform_name: str):
"""Literal ``p.value == platform_name`` scan over connected adapters (native adapters only)."""
@@ -865,18 +873,28 @@ class GatewayNotificationsMixin:
logger.warning(fail, raw_sid, e)
return False
- def _resolve_injection_adapter(self, platform_name: str):
+ def _resolve_injection_adapter(self, platform_name: str, source=None):
"""Adapter for a synthetic-event platform: alias-aware transport resolver first (one
Platform.RELAY adapter fronts N logical platforms; native wins), literal ``p.value`` scan as
fallback for minimal runner stubs / exotic platform strings when the resolver can't run."""
from gateway.delivery import resolve_delivery_transport
+ if source is not None:
+ owner = self._transport_owner(source)
+ if owner is not None:
+ return owner[0]
+ if getattr(source, "delivered_via_upstream_relay", False) is True:
+ return self.adapters.get(Platform.RELAY)
+ profile = getattr(source, "profile", None)
+ adapters = self.adapters
+ if profile and profile not in ("default", getattr(self, "_primary_profile_name", None)):
+ adapters = (getattr(self, "_profile_adapters", None) or {}).get(profile, {})
try:
- _transport = resolve_delivery_transport(Platform(platform_name), self.config, self.adapters)
+ _transport = resolve_delivery_transport(Platform(platform_name), self.config, adapters)
except Exception:
_transport = None
if _transport is not None:
return _transport.adapter
- return self._adapter_by_platform_value(platform_name)
+ return next((a for p, a in adapters.items() if p.value == platform_name), None)
async def _inject_watch_notification(self, synth_text: str, evt: dict) -> Optional[bool]:
"""Inject a watch/completion notification as a synthetic message event.
@@ -899,19 +917,19 @@ class GatewayNotificationsMixin:
if adapter is not None and not adapter_supports_push(adapter):
return await self._self_post_api_server(adapter, synth_text, raw_sid, evt)
logger.warning(
- "Dropping watch notification for raw session %s: no api_server adapter to self-post through",
+ "Deferring watch notification for raw session %s: no api_server adapter to self-post through",
raw_sid,
)
- return None
+ return False
logger.warning(
"Dropping watch notification with no routing metadata for process %s",
evt.get("session_id", "unknown"),
)
return None
platform_name = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
- adapter = self._resolve_injection_adapter(platform_name)
+ adapter = self._resolve_injection_adapter(platform_name, source)
if not adapter:
- return None
+ return False
if not adapter_supports_push(adapter):
# Non-push adapter (api_server): its chat_id IS the raw session id, so handle_message would
# key the wake under a build_session_key() that never matches — self-post instead.
@@ -1049,7 +1067,7 @@ class GatewayNotificationsMixin:
source = await asyncio.to_thread(self._build_process_event_source, evt)
if source is not None:
platform = source.platform.value if hasattr(source.platform, "value") else str(source.platform)
- adapter = self._resolve_injection_adapter(platform)
+ adapter = self._resolve_injection_adapter(platform, source)
else:
session_key = str(evt.get("session_key") or "").strip()
raw_sid = str(evt.get("origin_session_id") or "").strip()
@@ -1390,16 +1408,18 @@ class GatewayNotificationsMixin:
return delivered
async def _async_delegation_watcher(self, interval: float = 2.0) -> None:
- """Drain async-delegation completions and inject them as new turns (IDLE case).
+ """Drain async completions and pattern notifications even while sessions are idle.
- Background subagents run on the daemon executor with no per-process watcher, so their
- completions would otherwise only be seen by the post-turn drain. Ignores non-async events.
+ Background subagents and process pattern events have no per-process notification
+ consumer; both must progress without a later foreground turn.
"""
await asyncio.sleep(3) # let platforms finish connecting
from tools.process_registry import process_registry as _pr
while self._running:
with _log_suppressed(logging.DEBUG, "Async delegation watcher error: %s"):
- # Take async-delegation events only; requeue watch/completion events for their own drains.
+ # Pattern events also need an idle consumer; foreground turns are optional.
+ await self._drain_watch_notifications(_pr.completion_queue)
+ # Process completions remain owned by their per-process watchers.
requeue = []
async_events = []
while not _pr.completion_queue.empty():
@@ -1444,9 +1464,10 @@ class GatewayNotificationsMixin:
new_output = _redact_gateway_user_facing_secrets(new_output)
return new_output
- async def _send_watcher_message(self, platform_name: str, chat_id, thread_id, message_text: str) -> None:
+ async def _send_watcher_message(self, platform_name: str, chat_id, thread_id, message_text: str, watcher: dict) -> None:
from gateway.run import _non_conversational_metadata
- adapter = self._adapter_by_platform_value(platform_name)
+ source = await asyncio.to_thread(self._build_process_event_source, watcher)
+ adapter = self._resolve_injection_adapter(platform_name, source)
if adapter and chat_id:
with _log_suppressed(logging.ERROR, "Watcher delivery error: %s"):
send_meta = {"thread_id": thread_id} if thread_id else None
@@ -1564,7 +1585,7 @@ class GatewayNotificationsMixin:
notify_mode == "error" and session.exit_code not in {0, None}
):
message_text = self._format_process_final_message(session_id, session, notify_mode)
- await self._send_watcher_message(platform_name, chat_id, thread_id, message_text)
+ await self._send_watcher_message(platform_name, chat_id, thread_id, message_text, watcher)
break
elif has_new_output and notify_mode == "all" and not agent_notify:
# New output — deliver a status update (only in "all" mode; agent_notify watchers
@@ -1572,6 +1593,6 @@ class GatewayNotificationsMixin:
new_output = self._redacted_output_tail(session, 500)
await self._send_watcher_message(
platform_name, chat_id, thread_id,
- f"[Background process {session_id} is still running~ New output:\n{new_output}]",
+ f"[Background process {session_id} is still running~ New output:\n{new_output}]", watcher,
)
logger.debug("Process watcher ended%s: %s", " (silent)" if silent else "", session_id)
diff --git a/tests/gateway/test_completion_delivery.py b/tests/gateway/test_completion_delivery.py
index 6b43f670193..107b3096042 100644
--- a/tests/gateway/test_completion_delivery.py
+++ b/tests/gateway/test_completion_delivery.py
@@ -936,3 +936,48 @@ def test_unavailable_delivery_preserves_budget_across_restarts(tmp_path, unavail
adapter.handle_message.assert_awaited_once()
finally:
db.close()
+
+
[email protected]("available", [False, True])
+def test_completion_profile_transport_never_falls_back(monkeypatch, isolated_registry, available):
+ primary = SimpleNamespace(handle_message=AsyncMock(), send=AsyncMock())
+ secondary = SimpleNamespace(handle_message=AsyncMock(), send=AsyncMock())
+ runner = _runner(primary)
+ runner._profile_adapters = {"research": {Platform.TELEGRAM: secondary}} if available else {}
+ evt = dict(_completion_event(started_at=1), session_key="agent:research:telegram:dm:12345")
+ result = asyncio.run(runner._inject_watch_notification("private result", evt))
+ assert result is available
+ asyncio.run(runner._send_watcher_message("telegram", "12345", None, "raw result", evt))
+ primary.send.assert_not_awaited()
+ assert secondary.send.await_count == int(available)
+ primary.handle_message.assert_not_awaited()
+ assert secondary.handle_message.await_count == int(available)
+ if available:
+ assert secondary.handle_message.await_args.args[0].source.profile == "research"
+
+
[email protected]("event_type", ["watch_match", "watch_disabled"])
[email protected]("mode", ["concise", "off"])
+def test_idle_watch_drain_respects_notify_mode(monkeypatch, isolated_registry, event_type, mode):
+ adapter = SimpleNamespace(handle_message=AsyncMock())
+ runner = _runner(adapter)
+ runner._load_background_notifications_mode = lambda: mode
+ evt = dict(_completion_event(started_at=1), type=event_type,
+ pattern="READY", output="READY", message="Watch patterns disabled")
+ isolated_registry.completion_queue.put(evt)
+ _stop_after_sleeps(monkeypatch, runner, count=2)
+ asyncio.run(runner._async_delegation_watcher(interval=0))
+ assert adapter.handle_message.await_count == (0 if mode == "off" else 1)
+ assert isolated_registry.completion_queue.empty()
+
+
+def test_watch_drain_retries_transport_failure(monkeypatch, isolated_registry):
+ adapter = SimpleNamespace(handle_message=AsyncMock(side_effect=[RuntimeError("offline"), None]))
+ runner = _runner(adapter)
+ runner._load_background_notifications_mode = lambda: "concise"
+ evt = dict(_completion_event(started_at=1), type="watch_match", pattern="READY", output="READY")
+ isolated_registry.completion_queue.put(evt)
+ _stop_after_sleeps(monkeypatch, runner, count=3)
+ asyncio.run(runner._async_delegation_watcher(interval=0))
+ assert adapter.handle_message.await_count == 2
+ assert isolated_registry.completion_queue.empty()
diff --git a/tests/gateway/test_relay_completion_injection_routing.py b/tests/gateway/test_relay_completion_injection_routing.py
index 226d0b48a4a..327e7377c12 100644
--- a/tests/gateway/test_relay_completion_injection_routing.py
+++ b/tests/gateway/test_relay_completion_injection_routing.py
@@ -81,10 +81,8 @@ async def test_injection_resolves_relay_adapter_for_fronted_platform():
@pytest.mark.asyncio
-async def test_injection_still_none_when_platform_not_fronted():
- """Control: a platform the relay does NOT front stays undeliverable
- (returns None) — the resolver must not let relay hijack unrelated
- targets."""
+async def test_injection_retries_when_platform_not_fronted():
+ """Unavailable transport stays retryable without letting relay hijack unrelated targets."""
adapter = _RelayAdapter() # fronts slack only
runner = _runner_with_relay(adapter)
evt = _slack_async_event()
@@ -92,5 +90,5 @@ async def test_injection_still_none_when_platform_not_fronted():
evt["platform"] = "discord"
result = await runner._inject_watch_notification("[x]", evt)
- assert result is None
+ assert result is False
assert adapter.handle_message.await_count == 0