Skip to content

The agent that grows with you

fix(gateway): persist api_server async-delegation completions as deliveries, not user-turn wakes

Hermes Agent219cb714a1b8
diff --git a/gateway/run.py b/gateway/run.py
index 36d1fc6da0e..9b2e4b6f69d 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -27134,8 +27134,36 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
raw_sid = _sk
if raw_sid:
adapter = self.adapters.get(Platform.API_SERVER)
- from gateway.wake import adapter_supports_push, deliver_wake
+ from gateway.wake import (
+ adapter_supports_push,
+ deliver_wake,
+ persist_delegation_delivery,
+ )
if adapter is not None and not adapter_supports_push(adapter):
+ if evt.get("type") == "async_delegation":
+ # #85957: after the parent turn's event.complete the
+ # CLIENT owns the next turn on this stateless surface.
+ # Persist the completion as a durable delivery row —
+ # never self-post it as a new role=user prompt.
+ try:
+ logger.info(
+ "Async delegation completion — persisting "
+ "delivery row for api_server session %s "
+ "(no wake turn)",
+ raw_sid,
+ )
+ await persist_delegation_delivery(
+ adapter, text=synth_text,
+ session_id=raw_sid, evt=evt,
+ )
+ return True
+ except Exception as e:
+ logger.warning(
+ "Async delegation delivery persist failed "
+ "for session %s: %s",
+ raw_sid, e,
+ )
+ return False
try:
logger.info(
"Watch pattern notification — waking api_server "
@@ -27201,8 +27229,29 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# which binds chat_id = session_id). handle_message would run the
# wake under a build_session_key()-derived key that never matches
# the raw X-Hermes-Session-Id session — self-post instead.
- from gateway.wake import deliver_wake
+ from gateway.wake import deliver_wake, persist_delegation_delivery
raw_sid = str(evt.get("origin_session_id") or "").strip() or str(source.chat_id or "")
+ if evt.get("type") == "async_delegation":
+ # #85957: same client-owns-the-turn rule as the raw-key branch
+ # above — persist the completion as a delivery row, never
+ # self-post it as a new role=user prompt.
+ try:
+ logger.info(
+ "Async delegation completion — persisting delivery "
+ "row for api_server session %s (no wake turn)",
+ raw_sid,
+ )
+ await persist_delegation_delivery(
+ adapter, text=synth_text, session_id=raw_sid, evt=evt,
+ )
+ return True
+ except Exception as e:
+ logger.warning(
+ "Async delegation delivery persist failed for "
+ "session %s: %s",
+ raw_sid, e,
+ )
+ return False
try:
logger.info(
"Watch pattern notification — waking api_server session "
diff --git a/gateway/wake.py b/gateway/wake.py
index cee8d45e50c..deaaf28d3eb 100644
--- a/gateway/wake.py
+++ b/gateway/wake.py
@@ -19,6 +19,18 @@ Two delivery strategies, selected by the target adapter's
session, with full history, and its result is visible the next time the
client polls/reopens the conversation.
+Async-delegation completions are the exception on the stateless path
+(#85957): after the parent turn ends (``finish_reason=stop``, SSE
+``event.complete``) the CLIENT owns the next turn, so a completion must never
+be self-POSTed as a new ``role=user`` prompt — that starts an unauthorized
+agent turn that can blow through a pending human-confirmation gate. Instead
+``persist_delegation_delivery`` writes the completion into the session
+transcript as a durable DELIVERY row (``role=user`` +
+``display_kind="async_delegation_complete"`` — the same bookkeeping shape the
+TUI/desktop pollers use), so clients polling
+``GET /api/sessions/{id}/messages`` see the result immediately and the next
+REAL client turn carries it as context, without any model turn running.
+
Failures RAISE (after bounded retries on transient errors) so callers can
rewind cursors / retry instead of silently losing the event.
"""
@@ -94,6 +106,82 @@ async def deliver_wake(
await _self_post_chat_completion(adapter, text=text, session_id=session_id)
+def _delegation_display_metadata(evt: dict) -> dict:
+ """Display-only metadata for a persisted delegation delivery row.
+
+ Mirrors ``tui_gateway.server._async_delegation_display_metadata`` (the
+ same ``display_kind`` consumer contract) without importing the TUI stack
+ into the gateway.
+ """
+ raw_results = evt.get("results")
+ results = [r for r in raw_results if isinstance(r, dict)] if isinstance(
+ raw_results, list
+ ) else []
+ task_count = len(results) or 1
+ completed_count = sum(
+ 1 for r in results if r.get("status") in {"completed", "success"}
+ )
+ failed_count = sum(
+ 1 for r in results if r.get("status") in {"failed", "error"}
+ )
+ metadata = {
+ "delegation_id": str(evt.get("delegation_id") or ""),
+ "task_count": task_count,
+ "completed_count": completed_count or task_count - failed_count,
+ "failed_count": failed_count,
+ }
+ duration = evt.get("total_duration_seconds") or evt.get("duration_seconds")
+ if isinstance(duration, (int, float)):
+ metadata["duration_seconds"] = duration
+ return metadata
+
+
+async def persist_delegation_delivery(
+ adapter: Any, *, text: str, session_id: str, evt: Optional[dict] = None
+) -> None:
+ """Persist an async-delegation completion as a durable DELIVERY row.
+
+ #85957: on stateless api_server sessions the client owns the turn after
+ ``event.complete`` — a completion must never become a new ``role=user``
+ prompt via the self-post (that starts an unauthorized agent turn and can
+ cross a pending human-confirmation gate). Instead, append the completion
+ to the session transcript as a timeline bookkeeping row
+ (``display_kind="async_delegation_complete"`` + display metadata — the
+ exact shape the TUI/desktop delivery path persists), WITHOUT running any
+ agent turn. Clients polling ``GET /api/sessions/{id}/messages`` see it
+ immediately; the pre-request repair belt folds it into the next real
+ client turn as context.
+
+ Raises on failure so the caller can release the durable claim and retry
+ instead of losing the completion.
+ """
+ if not session_id:
+ raise ValueError(
+ "persist_delegation_delivery: raw session id required to persist "
+ "the completion on the api_server session transcript"
+ )
+ ensure = getattr(adapter, "_ensure_session_db", None)
+ db: Any = await asyncio.to_thread(ensure) if callable(ensure) else None
+ if db is None:
+ raise RuntimeError(
+ "persist_delegation_delivery: api_server SessionDB unavailable — "
+ f"cannot persist completion for session {session_id}"
+ )
+ await asyncio.to_thread(
+ db.append_message,
+ session_id,
+ "user",
+ content=text,
+ display_kind="async_delegation_complete",
+ display_metadata=_delegation_display_metadata(evt or {}),
+ )
+ logger.info(
+ "async delegation completion persisted as delivery row for "
+ "api_server session %s (no wake turn)",
+ session_id,
+ )
+
+
async def _self_post_chat_completion(
adapter: Any, *, text: str, session_id: str
) -> None:
diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.py
index 76941bb7106..de86b5ae851 100644
--- a/tests/gateway/test_background_process_notifications.py
+++ b/tests/gateway/test_background_process_notifications.py
@@ -580,6 +580,86 @@ async def test_inject_watch_notification_origin_session_id_wins(monkeypatch, tmp
assert posts == ["raw-origin-sid"]
+async def test_async_delegation_apiserver_persists_delivery_not_self_post(
+ monkeypatch, tmp_path,
+):
+ """#85957: an async_delegation completion targeting a stateless api_server
+ session must be persisted as a durable DELIVERY row — never self-POSTed
+ to /v1/chat/completions as a new role=user prompt (which starts an
+ unauthorized agent turn after the client-owned parent turn ended)."""
+ runner = _build_runner(monkeypatch, tmp_path, "all")
+ api_adapter = SimpleNamespace(
+ supports_async_delivery=False,
+ handle_message=AsyncMock(),
+ _host="127.0.0.1", _port=8642, _api_key="k", _model_name="m",
+ )
+ runner.adapters[Platform.API_SERVER] = api_adapter
+
+ import gateway.wake as wake_mod
+
+ posts = []
+
+ async def fake_self_post(adapter, *, text, session_id):
+ posts.append(session_id)
+
+ persisted = []
+
+ async def fake_persist(adapter, *, text, session_id, evt=None):
+ persisted.append({"text": text, "session_id": session_id, "evt": evt})
+
+ monkeypatch.setattr(wake_mod, "_self_post_chat_completion", fake_self_post)
+ monkeypatch.setattr(wake_mod, "persist_delegation_delivery", fake_persist)
+
+ evt = {
+ "type": "async_delegation",
+ "delegation_id": "deleg_85957",
+ "session_key": "raw-hq-session-id", # no agent:main:... structure
+ "origin_session_id": "raw-hq-session-id",
+ "status": "completed",
+ }
+ result = await runner._inject_watch_notification(
+ "[ASYNC DELEGATION BATCH COMPLETE — deleg_85957]", evt,
+ )
+
+ assert result is True
+ assert posts == [] # the self-POST user-turn wake must NOT fire
+ api_adapter.handle_message.assert_not_awaited()
+ assert len(persisted) == 1
+ assert persisted[0]["session_id"] == "raw-hq-session-id"
+ assert persisted[0]["evt"]["delegation_id"] == "deleg_85957"
+
+
+async def test_async_delegation_apiserver_persist_failure_is_retryable(
+ monkeypatch, tmp_path,
+):
+ """A failed delivery persist returns False so the durable claim is
+ released and the completion retried — never silently lost."""
+ runner = _build_runner(monkeypatch, tmp_path, "all")
+ api_adapter = SimpleNamespace(
+ supports_async_delivery=False,
+ handle_message=AsyncMock(),
+ _host="127.0.0.1", _port=8642, _api_key="k", _model_name="m",
+ )
+ runner.adapters[Platform.API_SERVER] = api_adapter
+
+ import gateway.wake as wake_mod
+
+ async def fail_persist(adapter, *, text, session_id, evt=None):
+ raise RuntimeError("state.db unavailable")
+
+ monkeypatch.setattr(wake_mod, "persist_delegation_delivery", fail_persist)
+
+ evt = {
+ "type": "async_delegation",
+ "delegation_id": "deleg_fail",
+ "session_key": "raw-sid",
+ }
+ result = await runner._inject_watch_notification("[BATCH COMPLETE]", evt)
+ assert result is False
+
+
def test_gateway_drain_retains_and_formats_overflow_events():
"""watch_overflow_* events must survive the gateway drain and render
their summary — previously they were discarded at the drain (only
diff --git a/tests/gateway/test_wake_delivery.py b/tests/gateway/test_wake_delivery.py
index 3d24e34f707..524ebd02456 100644
--- a/tests/gateway/test_wake_delivery.py
+++ b/tests/gateway/test_wake_delivery.py
@@ -125,3 +125,60 @@ def test_deliver_wake_retries_429_then_succeeds(monkeypatch):
assert calls["n"] == 2
+def test_persist_delegation_delivery_appends_delivery_row(tmp_path):
+ """#85957: the delegation completion lands in the session transcript as a
+ display_kind=async_delegation_complete delivery row (real SessionDB), and
+ NO self-post / agent turn is involved."""
+ from pathlib import Path
+
+ from gateway.wake import persist_delegation_delivery
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=Path(tmp_path) / "state.db")
+ sid = "raw-hq-sid"
+ db.create_session(sid, source="api_server")
+ db.append_message(sid, "user", content="please confirm before writing")
+ db.append_message(sid, "assistant", content="awaiting confirmation",
+ finish_reason="stop")
+
+ class DbAdapter(ApiServerLikeAdapter):
+ def _ensure_session_db(self):
+ return db
+
+ evt = {
+ "type": "async_delegation",
+ "delegation_id": "deleg_x",
+ "results": [{"status": "completed"}, {"status": "failed"}],
+ "total_duration_seconds": 12.5,
+ }
+ asyncio.run(persist_delegation_delivery(
+ DbAdapter(), text="[ASYNC DELEGATION BATCH COMPLETE — deleg_x]",
+ session_id=sid, evt=evt,
+ ))
+
+ rows = db.get_messages(sid)
+ assert len(rows) == 3
+ delivery = rows[-1]
+ assert delivery["role"] == "user"
+ assert delivery["display_kind"] == "async_delegation_complete"
+ meta = delivery["display_metadata"]
+ assert meta["delegation_id"] == "deleg_x"
+ assert meta["task_count"] == 2
+ assert meta["failed_count"] == 1
+ assert meta["duration_seconds"] == 12.5
+
+
+def test_persist_delegation_delivery_raises_without_db():
+ """DB unavailable must RAISE so the durable claim is released for retry."""
+ from gateway.wake import persist_delegation_delivery
+
+ class NoDbAdapter(ApiServerLikeAdapter):
+ def _ensure_session_db(self):
+ return None
+
+ with pytest.raises(RuntimeError, match="SessionDB unavailable"):
+ asyncio.run(persist_delegation_delivery(
+ NoDbAdapter(), text="x", session_id="sid",
+ ))
+
+