Files
hermes-agent/hermes_cli/quiet_single_query.py
T
teknium1 d0a016db00 fix(bot-mode): the retried delivery adopts the DM behind the failed attempt's tool scaffolding too
adopt_unanswered_turn only adopted the DM when it was the transcript's literal
tail row. A turn that failed transiently mid-way (HTTP 503 on the API call after
a tool round) persists user + assistant(tool_calls) + tool rows before
agent.turn_recovery builds the failure text (_persist_session runs first), exits 1
with transient prose on stdout, so the policy-gated re-run fires — and found a
tool-row tail, adopted nothing, and appended a second copy of the DM: exactly the
duplicate this PR set out to remove, just one API call later.

The DM is unanswered as long as nothing after it is a plain assistant reply. The
re-run now walks back to the last user row, requires it to match the payload and
every later row to be tool scaffolding (assistant with tool_calls, or tool), adopts
that row and drops the scaffolding from the in-memory turn so the agent starts the
turn over from the DM. The scaffolding stays in the DB as the record of the failed
attempt; the re-run's answer lands after it as a valid continuation. An answered
tail (a real assistant reply) and a missing marker still adopt nothing.
2026-09-16 17:19:58 -07:00

135 lines
6.5 KiB
Python

"""Quiet ``hermes chat -Q`` helpers: bind this session's key and resume nested notifies.
Bot Mode delivers a local DM as ``hermes -p <bot> chat -Q --query-file``. Interactive
chat binds ``set_current_session_key(self.session_id)`` around the turn; the quiet
path did not, so a nested ``message_agent`` notify inherited the dispatcher's
``HERMES_SESSION_KEY`` and never woke the recipient. Quiet also printed and exited
after one turn, so a nested teammate reply that finished during the one-shot linger
was never injected as a follow-up.
"""
from __future__ import annotations
import contextlib
import os
import time
from typing import Any, Callable, MutableMapping
# Nested A→B→C is one extra turn; this caps a runaway message_agent chain.
_MAX_QUIET_NOTIFY_ROUNDS = 8
@contextlib.contextmanager
def bind_quiet_session_key(session_id: str):
"""Bind the approval/session key to *this* quiet session for the enclosing ``with`` block."""
from tools.approval_context import reset_current_session_key, set_current_session_key
token = set_current_session_key(session_id or "default")
try:
yield
finally:
reset_current_session_key(token)
def quiet_notify_linger_seconds() -> float:
"""Total linger budget for one quiet run: the shared ``terminal.oneshot_completion_wait_seconds``.
One budget covers the drain loop here AND the later ``_wait_for_oneshot_background_completions``
pass, so a stuck ``notify_on_complete`` child cannot stack round-after-round waits on top of the
finalize re-wait (pre-fix worst case: 8 rounds x 600s + 600s).
"""
from tools.process_registry import ProcessRegistry
return ProcessRegistry._oneshot_completion_wait_seconds()
def continue_quiet_notify_completions(
session_id: str,
run_turn: Callable[[str], Any],
*,
owns_event=None,
max_rounds: int = _MAX_QUIET_NOTIFY_ROUNDS,
linger_budget: float | None = None,
) -> Any:
"""Linger for ``notify_on_complete`` work, then run owned completion texts as follow-up turns.
Returns the last ``run_turn`` result, or ``None`` when nothing owned completed. The whole
loop shares ONE linger budget (default: ``terminal.oneshot_completion_wait_seconds``) — a
process that times out is waited on no further this run: after the current round's drained
texts run, the loop stops (the finalize linger still covers it once, bounded, via the
budget handshake below).
"""
from tools.process_registry import process_registry
from tools.async_delegation import claim_event_delivery, complete_event_delivery
last: Any = None
key = session_id or ""
if linger_budget is None:
linger_budget = quiet_notify_linger_seconds()
deadline = time.monotonic() + max(float(linger_budget), 0.0)
for _ in range(max_rounds):
wait = process_registry.wait_for_pending_completions(None, timeout=max(deadline - time.monotonic(), 0.0))
drained = []
for event, text in process_registry.drain_notifications(session_key=key, owns_event=owns_event):
# Durable async_delegation events carry a delivery ledger: without the
# claim/complete handshake the row stays delivery_state='pending' and
# restore_undelivered_completions re-queues it on the next process start,
# injecting the same result twice. Same contract as every other drain consumer.
claim = claim_event_delivery(event, "cli-quiet")
if claim is None:
continue
complete_event_delivery(event, claim)
drained.append((event, text))
# Every drained event type carries formatted text (completions, watch matches,
# async_delegation results): drain_notifications POPS owned events off the queue,
# so filtering by type here would consume-and-silently-drop owned
# async_delegation results. Keep everything that rendered.
texts = [text for _event, text in drained if text]
if texts:
last = run_turn("\n\n".join(texts))
if wait.get("timed_out"):
break
if not texts:
return last
return last
def adopt_unanswered_turn(cli: Any, query: Any, environ: MutableMapping[str, str] = os.environ) -> bool:
"""A dispatcher's re-run of a failed delivery turn resumes the DM its first attempt already
persisted instead of appending it again. Returns True when the tail row was adopted.
The failed attempt's turn-start persist left the DM as the transcript's unanswered tail row. A
fresh process cannot know that by itself (``_DB_PERSISTED_MARKER`` is in-process only), and
inferring it from an identical tail alone would swallow a person's deliberate re-send — so the
dispatcher must say so with ``tools.bot_relay.RESUME_UNANSWERED_TURN_ENV``, consumed (popped) here
before the turn so tool subprocesses never inherit it. The row is re-staged as the pending CLI
dict already stamped durable: ``_stage_turn_user_message`` reuses it as this turn's user message and
the flush writes no second row.
The DM is not always the literal tail: a turn that died mid-way (HTTP 503 on the call after a tool
round) persisted its tool scaffolding — assistant ``tool_calls`` rows and their ``tool`` results —
behind the DM before ``agent.turn_recovery`` built the failure text, and the dispatcher retries that
too. The DM is still unanswered while nothing after it is a plain assistant reply, so it is adopted
and the failed attempt's scaffolding leaves the in-memory transcript: the re-run starts the turn
over from the DM (the rows stay in the DB as the record of the failed attempt; the re-run's answer
lands after them as a valid continuation)."""
from tools.bot_relay import RESUME_UNANSWERED_TURN_ENV
if environ.pop(RESUME_UNANSWERED_TURN_ENV, None) != "1":
return False
history = getattr(cli, "conversation_history", None) or []
idx = next((i for i in range(len(history) - 1, -1, -1)
if isinstance(history[i], dict) and history[i].get("role") == "user"), None)
if idx is None or history[idx].get("content") != query:
return False
if not all(isinstance(row, dict) and (row.get("role") == "tool" or (row.get("role") == "assistant" and row.get("tool_calls")))
for row in history[idx + 1:]):
return False
from agent.context_compressor import _DB_PERSISTED_MARKER
tail = history[idx]
del history[idx:]
tail[_DB_PERSISTED_MARKER] = True
cli.agent._pending_cli_user_message = tail
return True