The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-relay): a relayed turn is booked from its turn report at the cap, not killed with its handoff
John Paul Soliva76a486a1eb6a
diff --git a/cli.py b/cli.pyindex 7db145d0a4f..e63e1bd8650 100644--- a/cli.py+++ b/cli.py@@ -4205,11 +4205,17 @@ def _run_quiet_single_query(cli, effective_query, emitter=None):# without this sync it would point at the ended parent after compression._sync_cli_session_id_from_agent(cli)# The turn is over and persisted: the one-shot exit linger that follows protects nested- # notify_on_complete replies and is NOT part of the spawner's delivery (#113608).- write_turn_report(- turn_report_path, exit_code=_single_query_exit_code(result),- error=str(result.get("error") or "") if isinstance(result, dict) else "agent turn did not run",- )+ # notify_on_complete replies and is NOT part of the spawner's delivery (#113608). The+ # report carries what this run will print, so a spawner booking a child still lingering+ # at its cap relays the answer instead of a timeout (#114980).+ def _report_turn(res) -> None:+ write_turn_report(+ turn_report_path, exit_code=_single_query_exit_code(res),+ error=str(res.get("error") or "") if isinstance(res, dict) else "agent turn did not run",+ reply=res.get("final_response", "") if isinstance(res, dict) else str(res),+ )++ _report_turn(result)if isinstance(result, dict) and not result.get("failed"):history = result.get("messages") or cli.conversation_history@@ -4242,6 +4248,8 @@ def _run_quiet_single_query(cli, effective_query, emitter=None):cli._quiet_notify_linger_done = Trueif isinstance(continued, dict):result = continued+ # A teammate's reply displaced the answer this run prints; tell the spawner.+ _report_turn(result)response = result.get("final_response", "") if isinstance(result, dict) else str(result)# Surface backend errors that produced no visible output (e.g. invalid model slug# -> provider 4xx) on stderr so piped stdout stays clean.diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 2a7dc5dafe4..8a26e3641c1 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -17,12 +17,9 @@ import osimport shutilimport subprocessimport sys-import threading-import timefrom dataclasses import dataclassfrom typing import Any, List, Optional-from hermes_cli._subprocess_compat import windows_hide_flags# Log-record parity with the origin module.logger = logging.getLogger("cron.scheduler")@@ -724,75 +721,24 @@ _BOT_CHAT_STDERR_TAIL = 500# stdout is the model's answer; only a short tail is persisted (jobs.json / ledger)._BOT_CHAT_STDOUT_TAIL = 200_BOT_CHAT_BANNER_PREFIXES = ("Resumed session", "session_id:")-# After the child reports its turn, a child with nothing to linger for exits at once; give it-# that long so its real exit code and stream tails are booked instead of the report's summary.-_BOT_CHAT_EXIT_GRACE_SECONDS = 2.0def _run_bot_chat_turn(argv: list, env: dict, report_path: str, timeout: float) -> subprocess.CompletedProcess:- """Run one ``hermes chat -Q`` delivery child; the cap bounds the TURN, not the process.-- The child records its turn outcome at *report_path* (``hermes_cli.quiet_single_query``)- the moment the turn ends, then runs the one-shot exit linger for nested- ``notify_on_complete`` replies — bounded by ``terminal.oneshot_completion_wait_seconds``,- whose default equals this lane's cap, so waiting for process exit booked every delivered- turn that left a reply pending as a timeout and killed the linger (#113608). Once the- report exists the delivery is booked from it and the still-lingering child is left- running (a daemon thread drains and reaps it); only a turn that never ends is killed.+ """Run one ``hermes chat -Q`` delivery child; the cap bounds the TURN, not the process (#113608).++ The booking policy lives with the report contract (``quiet_single_query.run_reported_turn``):+ this lane needs only the outcome, so a child that reported its turn gets the exit grace and is+ then left to its linger; only a turn that never ends is killed."""- from hermes_cli.quiet_single_query import read_turn_report+ from hermes_cli.quiet_single_query import run_reported_turn# The scheduler may sit in a directory that no longer exists (a kanban worker whose# scratch workspace was reaped): a child inheriting that cwd dies at CLI startup# (#102941). The target home is the one directory this lane has already verified.- # Lossy decode everywhere; on Windows also decode as the UTF-8 the child writes.- # A stray non-UTF-8 byte (e.g. a grandchild sharing the pipe interleaving a- # partial multi-byte write) must not raise UnicodeDecodeError in the drain- # thread and take both the reply and the failure tail with it (#105582; same- # errors= hardening as _run_job_script). On win32 the child is guaranteed- # UTF-8 — hermes_cli reconfigures its own streams via hermes_bootstrap even- # under PYTHONIOENCODING=cp1252 — while the gateway parent is NOT started in- # UTF-8 mode (its env overlay sets only PYTHONIOENCODING), so text=True alone- # decodes the pipes with the ANSI code page: accented replies come back- # mojibake'd, or the reader thread dies on bytes undefined in cp1252 and the- # captured reply is silently lost while the delivery still books as delivered- # (#115894). On POSIX the child keeps the locale codec, so the locale default- # stays correct there (#66566).- popen_kwargs: dict = {"errors": "replace"}- if sys.platform == "win32":- popen_kwargs["encoding"] = "utf-8"- proc = subprocess.Popen(- argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,- env=env, cwd=env.get("HERMES_HOME") or None, creationflags=windows_hide_flags(), **popen_kwargs)- streams: dict = {}-- def _drain() -> None:- streams["out"], streams["err"] = proc.communicate()-- drain = threading.Thread(target=_drain, name=f"bot-chat-delivery-{proc.pid}", daemon=True)- drain.start()- deadline = time.monotonic() + timeout- report = None- while True:- drain.join(timeout=0.25 if report is None else _BOT_CHAT_EXIT_GRACE_SECONDS)- if not drain.is_alive():- return subprocess.CompletedProcess(argv, proc.returncode, streams.get("out", ""), streams.get("err", ""))- if report is not None:- # Turn over, child still lingering for a nested reply: not this lane's wait.- return subprocess.CompletedProcess(argv, int(report["exit_code"]), "", report.get("error") or "")- report = read_turn_report(report_path, proc.pid)- if report is None and time.monotonic() >= deadline:- proc.kill()- drain.join(timeout=5.0)- # A killed child cannot run further, but the turn may have ENDED (and delivered)- # in the window between the last report check and the kill landing. Re-read once:- # a report that appeared means the turn completed — book it as delivered instead- # of misreporting a delivered turn as a timeout (and never re-notifying).- late = read_turn_report(report_path, proc.pid)- if late is not None:- return subprocess.CompletedProcess(- argv, int(late["exit_code"]), "", late.get("error") or "")- raise subprocess.TimeoutExpired(argv, timeout)+ # Decoding is the runner's platform policy: lossy everywhere (#105582), UTF-8 only on+ # win32 (#115894), the locale codec on POSIX (#66566).+ return run_reported_turn(argv, env=env, report_path=report_path, timeout=timeout,+ cwd=env.get("HERMES_HOME") or None)def _format_failure_streams(result) -> str:diff --git a/hermes_cli/quiet_single_query.py b/hermes_cli/quiet_single_query.pyindex ad6e5750213..70c41833f94 100644--- a/hermes_cli/quiet_single_query.py+++ b/hermes_cli/quiet_single_query.py@@ -13,7 +13,9 @@ from __future__ import annotationsimport contextlibimport jsonimport os+import subprocessimport sys+import threadingimport timefrom typing import Any, Callable, MutableMapping@@ -52,17 +54,18 @@ def take_turn_report_path(environ: MutableMapping[str, str] = os.environ) -> strreturn environ.pop(TURN_REPORT_FILE_ENV, None) or None-def write_turn_report(path: str | None, *, exit_code: int, error: str = "") -> None:- """Atomically record ``{pid, exit_code, error}`` at *path*; a no-op without a path. Never raises:- the report is the spawner's convenience, the turn itself is already persisted."""+def write_turn_report(path: str | None, *, exit_code: int, error: str = "", reply: str = "") -> None:+ """Atomically record ``{pid, exit_code, error, reply}`` at *path*; a no-op without a path. Never+ raises: the report is the spawner's convenience, the turn itself is already persisted. ``reply``+ is what the run will print — a spawner booking a lingering child from its report relays it."""if not path:return- record = {"pid": os.getpid(), "exit_code": int(exit_code), "error": str(error or "")}+ from utils import atomic_json_write++ record = {"pid": os.getpid(), "exit_code": int(exit_code), "error": str(error or ""), "reply": str(reply or "")}+ # 0600 from creation: the record now carries the turn's answer, like the 0600 query file beside it.with contextlib.suppress(Exception):- tmp = f"{path}.{os.getpid()}.tmp"- with open(tmp, "w", encoding="utf-8") as fh:- json.dump(record, fh)- os.replace(tmp, path)+ atomic_json_write(path, record, indent=None, mode=0o600)def read_turn_report(path: str, pid: int) -> dict | None:@@ -77,6 +80,81 @@ def read_turn_report(path: str, pid: int) -> dict | None:return record+# After the child reports its turn, a child with nothing to linger for exits at once; a spawner+# that needs only the outcome gives it that long so its real exit code and stream tails are+# booked instead of the report's summary.+REPORTED_TURN_EXIT_GRACE_SECONDS = 2.0+++def run_reported_turn(argv: list, *, env: MutableMapping[str, str], report_path: str, timeout: float,+ exit_grace: float | None = REPORTED_TURN_EXIT_GRACE_SECONDS, cwd: str | None = None,+ encoding: str | None = None) -> subprocess.CompletedProcess:+ """Run one ``hermes chat -Q`` delivery child; *timeout* bounds the TURN, not the process.++ The child records its turn at *report_path* (``write_turn_report``) the moment the turn ends,+ then runs the one-shot exit linger for nested ``notify_on_complete`` replies — bounded by+ ``terminal.oneshot_completion_wait_seconds``, whose default equals the delivery caps, so+ waiting for process exit booked every delivered turn that left a reply pending as a timeout+ and killed the linger (#113608, #114980). A child that exits is booked from its real exit+ code and streams. A child still lingering once its report exists is booked from the report+ and left running (a daemon thread drains and reaps it): after *exit_grace* seconds for a+ spawner that needs only the outcome, or at the cap when *exit_grace* is None, for a spawner+ that relays the printed answer — a teammate's reply during the linger may still become it.+ Only a turn that never ends is killed, as ``subprocess.TimeoutExpired``.++ *cwd* pins the child's directory (a spawner sitting in a reaped scratch workspace must not+ hand its dead cwd on — the child dies at CLI startup, #102941). The pipes decode lossily+ everywhere: a stray non-UTF-8 byte (a grandchild sharing the pipe interleaving a partial+ multi-byte write) must not raise in the drain thread and take the reply and the failure tail+ with it (#105582). Without an explicit *encoding* they decode as UTF-8 only on win32, where+ the child is guaranteed UTF-8 (hermes_bootstrap reconfigures its streams even under+ PYTHONIOENCODING=cp1252) while the gateway parent is not started in UTF-8 mode, so the+ locale default mangled or lost accented replies (#115894); on POSIX the child keeps the+ locale codec, so the locale default stays correct there (#66566).+ """+ from hermes_cli._subprocess_compat import windows_hide_flags++ if encoding is None and sys.platform == "win32":+ encoding = "utf-8"+ proc = subprocess.Popen(+ argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,+ encoding=encoding, errors="replace", env={**env, TURN_REPORT_FILE_ENV: report_path},+ cwd=cwd, creationflags=windows_hide_flags())+ streams: dict = {}++ def _drain() -> None:+ streams["out"], streams["err"] = proc.communicate()++ drain = threading.Thread(target=_drain, name=f"quiet-turn-drain-{proc.pid}", daemon=True)+ drain.start()+ deadline = time.monotonic() + timeout+ report = None+ while True:+ drain.join(timeout=exit_grace if report is not None and exit_grace is not None else 0.25)+ if not drain.is_alive():+ return subprocess.CompletedProcess(argv, proc.returncode, streams.get("out", ""), streams.get("err", ""))+ if report is not None and exit_grace is not None:+ break+ # Re-read while waiting for the cap: a follow-up turn rewrites the report with its answer.+ report = read_turn_report(report_path, proc.pid) or report+ if time.monotonic() >= deadline:+ if report is not None:+ break+ proc.kill()+ drain.join(timeout=5.0)+ # A killed child cannot run further, but the turn may have ENDED (and delivered)+ # in the window between the last report check and the kill landing. Re-read once:+ # a report that appeared means the turn completed — book it instead of+ # misreporting a delivered turn as a timeout (and never re-notifying).+ report = read_turn_report(report_path, proc.pid)+ if report is not None:+ break+ raise subprocess.TimeoutExpired(argv, timeout)+ # Turn over, child still lingering for a nested reply: not this spawner's wait.+ return subprocess.CompletedProcess(+ argv, int(report["exit_code"]), report.get("reply") or "", report.get("error") or "")++@contextlib.contextmanagerdef bind_quiet_session_key(session_id: str):"""Bind the approval/session key to *this* quiet session for the enclosing ``with`` block."""diff --git a/tests/hermes_cli/test_quiet_single_query.py b/tests/hermes_cli/test_quiet_single_query.pyindex a4b838ee787..14e08711169 100644--- a/tests/hermes_cli/test_quiet_single_query.py+++ b/tests/hermes_cli/test_quiet_single_query.py@@ -106,6 +106,42 @@ def test_turn_report_is_written_before_the_exit_linger_and_the_path_is_not_inherexcept SystemExit as exc:assert exc.code == 0assert seen["env_during_turn"] is None and seen["report_during_turn"] is False- assert seen["report_at_linger"] == {"pid": os.getpid(), "exit_code": 0, "error": ""}+ assert seen["report_at_linger"] == {"pid": os.getpid(), "exit_code": 0, "error": "", "reply": "ok"}# Another process's record is not this child's report.assert qsq.read_turn_report(str(report), os.getpid() + 1) is None+++def test_a_follow_up_turn_rewrites_the_report_with_the_answer_it_displaces(monkeypatch, tmp_path):+ """The report says what this run will print. When a teammate's reply during the linger runs a+ follow-up turn whose answer displaces the first (the quiet run's final-answer contract), the+ report is rewritten with it, so a relay booking the child at its cap relays that answer (#114980)."""+ from hermes_cli import quiet_single_query as qsq++ monkeypatch.delenv("HERMES_KANBAN_GOAL_MODE", raising=False)+ monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)+ report = tmp_path / "turn.json"+ monkeypatch.setenv(qsq.TURN_REPORT_FILE_ENV, str(report))+ answers = iter(["asking the teammate", "teammate says: done"])+ seen = {}++ def run_conversation(**kwargs):+ return {"final_response": next(answers), "messages": []}++ def linger_then_follow_up(session_id, run_turn, **kwargs):+ seen["report_before_follow_up"] = qsq.read_turn_report(str(report), os.getpid())["reply"]+ return run_turn("teammate: done")++ monkeypatch.setattr(qsq, "continue_quiet_notify_completions", linger_then_follow_up)+ monkeypatch.setattr("tools.process_registry.process_registry.wait_for_pending_completions",+ lambda *a, **k: {"waited": [], "completed": [], "timed_out": []})+ agent = SimpleNamespace(run_conversation=run_conversation, session_id="s-1")+ printed = []+ monkeypatch.setattr("builtins.print", lambda *a, **k: printed.append(a))+ try:+ cli._run_quiet_single_query(SimpleNamespace(agent=agent, conversation_history=[], session_id="s-1"), "hello")+ except SystemExit as exc:+ assert exc.code == 0+ assert seen["report_before_follow_up"] == "asking the teammate"+ assert qsq.read_turn_report(str(report), os.getpid())["reply"] == "teammate says: done"+ assert ("teammate says: done",) in printed, "the report and stdout name the same answer"+diff --git a/tests/tools/test_bot_retry_policy.py b/tests/tools/test_bot_retry_policy.pyindex 307924ecbae..5d811bddbb3 100644--- a/tests/tools/test_bot_retry_policy.py+++ b/tests/tools/test_bot_retry_policy.py@@ -111,7 +111,7 @@ def test_deliver_retries_same_argv_on_transient_failure(home, monkeypatch):return _Proc(1, stderr="Error code: 429 - rate limit exceeded")return _Proc(0, stdout="recovered reply")- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)out = _deliver({"profile": "ops", "message": "ping"})assert out["result"]["reply"] == "recovered reply"turns = _transport_calls(calls)@@ -133,7 +133,7 @@ def test_deliver_retries_once_on_context_overflow(home, monkeypatch):return _Proc(1, stderr="This model's maximum context length is 200000 tokens")return _Proc(0, stdout="fits after compaction")- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)out = _deliver({"profile": "ops", "message": "ping"})assert out["result"]["reply"] == "fits after compaction"turns = _transport_calls(calls)@@ -151,7 +151,7 @@ def test_deliver_never_retries_auth_failure(home, monkeypatch):return _Proc(0)return _Proc(1, stderr="Error code: 401 - Your API key is invalid")- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)out = _deliver({"profile": "ops", "message": "ping"})assert "error" in outassert len(_transport_calls(calls)) == 1, "auth failures must not auto-retry"@@ -162,7 +162,7 @@ def test_deliver_never_retries_auth_failure(home, monkeypatch):def test_deliver_failure_carries_typed_reason(home, monkeypatch):"""A still-failing retryable error surfaces its classified reason."""monkeypatch.setattr(- "subprocess.run",+ "hermes_cli.quiet_single_query.run_reported_turn",lambda argv, **k: _Proc(1, stderr="502 server error - overloaded")if _is_hermes_cli(list(argv))else _Proc(0),@@ -246,14 +246,14 @@ def test_deliver_retry_reads_the_stream_the_cli_writes_and_resumes_the_persistedreturn _Proc(1, stdout=_REAL_FAILED_STDOUT, stderr=_REAL_FAILED_STDERR)return _Proc(0, stdout="recovered reply")- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)out = _deliver({"profile": "ops", "message": "ping"})assert out["result"]["reply"] == "recovered reply"assert [RESUME_UNANSWERED_TURN_ENV in env for env in envs] == [False, True]assert envs[1][RESUME_UNANSWERED_TURN_ENV] == "1"monkeypatch.setattr(- "subprocess.run",+ "hermes_cli.quiet_single_query.run_reported_turn",lambda argv, **k: _Proc(1, stdout=_REAL_FAILED_STDOUT, stderr=_REAL_FAILED_STDERR)if _is_hermes_cli(list(argv)) else _Proc(0),)diff --git a/tests/tools/test_bot_turn_lock.py b/tests/tools/test_bot_turn_lock.pyindex 797480c9854..69cb765d5de 100644--- a/tests/tools/test_bot_turn_lock.py+++ b/tests/tools/test_bot_turn_lock.py@@ -305,7 +305,7 @@ def test_relay_deliver_returns_target_busy_error(tmp_path, monkeypatch):return _Done()- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)held = threading.Event()release = threading.Event()@@ -340,7 +340,7 @@ def test_relay_deliver_serializes_then_succeeds(tmp_path, monkeypatch):stdout = "pong"stderr = ""- monkeypatch.setattr("subprocess.run", lambda *a, **k: _Proc())+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", lambda *a, **k: _Proc())held = threading.Event()release = threading.Event()@@ -398,7 +398,7 @@ def test_every_relay_refusal_carries_its_typed_reason(tmp_path, monkeypatch, faidef _raise(argv, **kwargs):raise failure- monkeypatch.setattr("subprocess.run", _raise)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _raise)out = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "x"})diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.pyindex 86aa01fcd06..dbea64bfba6 100644--- a/tests/tui_gateway/test_bot_relay_methods.py+++ b/tests/tui_gateway/test_bot_relay_methods.py@@ -4,21 +4,29 @@ The Desktop's relay door on each connected gateway. Contracts:- roster.sync persists validated rows and reports the accepted count;- outbox.drain returns queued envelopes exactly once;- deliver validates the target profile against THIS install and runs the- one-turn Bot Chat transport (subprocess is faked here — the argv contract- is what's pinned);+ one-turn Bot Chat transport (the turn runner is faked here — the argv+ contract is what's pinned; the runner itself is pinned below with real+ children: its cap bounds the turn, not the exit linger, #114980);- reply writes the waiter's file and rejects malformed envelope ids."""from __future__ import annotationsimport json+import os+import subprocess+import sys+import textwrap+import timefrom pathlib import Path+from unittest import mockimport pytestimport tui_gateway.server as srvfrom hermes_cli.dashboard_auth.ws_tickets import INTERNAL_PROVIDER, INTERNAL_USER_IDfrom tools import bot_relay+from tui_gateway import methods_bot_relay@pytest.fixture@@ -115,17 +123,16 @@ def test_deliver_validates_profile_and_runs_transport(home, monkeypatch):calls["kwargs"] = kwargsreturn _Proc()- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)out = _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"}))assert out["reply"] == "pong from ops"- # Decoding is pinned (#93590 sibling defect): without encoding= the- # child's UTF-8 output is decoded with the locale codec — cp1252/GBK on- # Windows — mangling non-ASCII replies; errors="replace" keeps a bad- # byte from raising instead of delivering.- assert calls["kwargs"]["encoding"] == "utf-8"- assert calls["kwargs"]["errors"] == "replace"+ # The cap bounds the turn; the relay wants the printed answer, so a reported child is+ # booked only at the cap (exit_grace=None), never early like the cron lane (#114980).+ assert calls["kwargs"]["timeout"] == bot_relay.TURN_ATTEMPT_TIMEOUT_SECONDS+ assert calls["kwargs"]["exit_grace"] is None+ assert calls["kwargs"]["report_path"].endswith(".turn.json")argv = calls["argv"]# argv[0] may be a resolved venv path (#93590) — match by basename.assert argv[1:3] == ["-p", "ops"]@@ -189,7 +196,7 @@ def test_deliver_relays_empty_reply_for_a_bare_silence_marker(home, monkeypatch)returncode, stderr = 0, ""stdout = " *NO_REPLY* "- monkeypatch.setattr("subprocess.run", lambda *_a, **_k: _Proc())+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", lambda *_a, **_k: _Proc())assert _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"}))["reply"] == ""_Proc.stdout = "The NO_REPLY marker means do not answer."@@ -218,7 +225,7 @@ def test_deliver_lands_in_live_bot_chat_instead_of_subprocess(home, monkeypatch)spawned.append(argv)return _Proc()- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)monkeypatch.setitem(srv._methods, "prompt.submit", lambda rid, p: submitted.append(p) or srv._ok(rid, {"status": "streaming"}))@@ -271,7 +278,7 @@ def test_deliver_hands_off_to_a_bot_chat_owned_by_another_process(home, monkeypaspawned.append(argv)raise AssertionError("the CLI transport collides with the live owner")- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)monkeypatch.setattr(srv, "_profile_home", lambda name: ops_home)monkeypatch.setattr(srv, "_sessions", {}) # THIS process hosts nothing for opstry:@@ -346,7 +353,7 @@ def fake_runs(monkeypatch):return _Proc()- monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)return calls, outcomes@@ -478,3 +485,90 @@ def test_gateway_drains_the_mailbox_the_tools_write_to(tmp_path, monkeypatch, suassert methods_bot_relay._relay_root() == writer_rootdrained = _result(srv._methods["bot_relay.outbox.drain"](1, {}))assert [e["id"] for e in drained["envelopes"]] == [env["id"]]+++_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+++def _child_argv(monkeypatch, body: str) -> dict:+ """Stand in a Python child for the ``hermes`` transport; it imports ``hermes_cli`` from this checkout."""+ argv = [sys.executable, "-c", textwrap.dedent(body)]+ monkeypatch.setattr(bot_relay, "local_delivery_command", lambda prof, tmp: argv)+ return {**os.environ, "PYTHONPATH": os.pathsep.join(p for p in (_REPO_ROOT, os.environ.get("PYTHONPATH")) if p)}+++def _spy_popen():+ procs, real_popen = [], subprocess.Popen++ def spy(*args, **kwargs):+ procs.append(real_popen(*args, **kwargs))+ return procs[-1]++ return procs, spy+++def test_reported_turn_still_lingering_at_the_cap_is_booked_from_its_latest_report_not_killed(tmp_path, monkeypatch):+ """#114980: the cap bounds the TURN. A child that reported its turn and then lingers for a+ nested notify_on_complete reply (bounded by oneshot_completion_wait_seconds, default == the+ cap) is booked at the cap from its report — the answer a follow-up turn last wrote there,+ exit code 0, never delivery_timeout — and is NOT killed, so its own handoff survives."""+ env = _child_argv(monkeypatch, """+ import os, time+ from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report+ path = os.environ.pop(TURN_REPORT_FILE_ENV)+ write_turn_report(path, exit_code=0, reply="asking the teammate")+ time.sleep(0.5)+ write_turn_report(path, exit_code=0, reply="teammate says: done")+ time.sleep(30)+ """)+ procs, spy = _spy_popen()+ tmp = tmp_path / "dm.txt"+ tmp.write_text("hi", encoding="utf-8")+ started = time.monotonic()+ try:+ with mock.patch.object(subprocess, "Popen", side_effect=spy):+ result = methods_bot_relay._run_delivery("ops", str(tmp), env, timeout=2)+ elapsed = time.monotonic() - started+ assert (result.returncode, result.stdout, result.stderr) == (0, "teammate says: done", "")+ assert 2 <= elapsed < 8, elapsed+ assert procs[0].poll() is None, "the lingering child must survive the booking"+ assert not (tmp_path / "dm.txt.turn.json").exists(), "the report is the runner's to clean up"+ finally:+ for proc in procs:+ proc.kill()+ proc.wait(timeout=10)+++def test_child_that_exits_under_the_cap_is_booked_from_its_streams(tmp_path, monkeypatch):+ """Today's contract when the whole run fits: ``-Q`` prints after the linger, and a teammate's+ reply may have become that answer — so the printed streams and real exit code win over the+ report. Decoding is pinned (#93590 sibling defect): without encoding= the child's UTF-8 output+ is decoded with the locale codec — cp1252/GBK on Windows — mangling non-ASCII replies."""+ env = _child_argv(monkeypatch, """+ import os, sys+ from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report+ write_turn_report(os.environ.pop(TURN_REPORT_FILE_ENV), exit_code=0, reply="interim")+ print("final: ünïcode")+ print("session_id: s-1", file=sys.stderr)+ sys.exit(3)+ """)+ procs, spy = _spy_popen()+ tmp = tmp_path / "dm.txt"+ tmp.write_text("hi", encoding="utf-8")+ env["PYTHONIOENCODING"] = "utf-8" # the real child writes UTF-8 whatever the console codec+ with mock.patch.object(subprocess, "Popen", side_effect=spy) as popen:+ result = methods_bot_relay._run_delivery("ops", str(tmp), env, timeout=10)+ assert (result.returncode, result.stdout, result.stderr) == (3, "final: ünïcode\n", "session_id: s-1\n")+ assert popen.call_args.kwargs["encoding"] == "utf-8" and popen.call_args.kwargs["errors"] == "replace"+++def test_turn_that_never_ends_is_still_a_delivery_timeout(tmp_path, monkeypatch):+ """Control: with no turn report the cap stays the guard it always was."""+ env = _child_argv(monkeypatch, "import time; time.sleep(30)")+ tmp = tmp_path / "dm.txt"+ tmp.write_text("hi", encoding="utf-8")+ started = time.monotonic()+ with pytest.raises(subprocess.TimeoutExpired):+ methods_bot_relay._run_delivery("ops", str(tmp), env, timeout=1)+ assert time.monotonic() - started < 8+diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.pyindex 9aea6360a46..a25983aae32 100644--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@ -6,6 +6,7 @@ Chat delivery on the TARGET gateway, returns the reply), ``reply`` (write the rethe SENDER gateway for its waiter). Plumbing: ``tools/bot_relay.py``; handlers are rebound ontoserver.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""+import contextlibimport osimport subprocessfrom pathlib import Path@@ -28,11 +29,25 @@ def _relay_root() -> Path:return _hermes_root(Path(_default_home()))-def _run_delivery(profile: str, tmp: str, env: dict | None = None) -> subprocess.CompletedProcess:+def _run_delivery(profile: str, tmp: str, env: dict | None = None, *,+ timeout: float = TURN_ATTEMPT_TIMEOUT_SECONDS) -> subprocess.CompletedProcess:+ """One relayed turn; the cap bounds the TURN, not the child (#114980). ``-Q`` prints its answer+ only after the one-shot exit linger (a teammate's reply during it may become that answer), so a+ child that exits under the cap is booked from its streams as before; one still lingering at the+ cap is booked from its turn report — its answer and outcome, never a timeout — and left to finish+ the linger that protects its own handoff. Only a turn that never ends is a timeout."""+ from hermes_cli.quiet_single_query import run_reported_turnfrom tools.bot_relay import local_delivery_command- return subprocess.run(- local_delivery_command(profile, tmp), capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=TURN_ATTEMPT_TIMEOUT_SECONDS, env=env)+ report = f"{tmp}.turn.json"+ try:+ # The relay pins UTF-8 on every platform (#93590): its child is the bootstrapped hermes_cli+ # and its answer is relayed verbatim, unlike the cron lane's locale-decoded tails.+ return run_reported_turn(+ local_delivery_command(profile, tmp), env=os.environ if env is None else env,+ report_path=report, timeout=timeout, exit_grace=None, encoding="utf-8")+ finally:+ with contextlib.suppress(OSError):+ os.unlink(report)@method("bot_relay.roster.sync")diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex 3c91927d931..62ecc75cbf9 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -226,6 +226,7 @@ Every gateway you register in **Settings → Connections** — local, remote URL- **`message_agent` reaches them directly.** A Bot on your laptop messages the cloud agent with `message_agent(target="moxie", …)` exactly like a local teammate. If the same handle exists on several machines, disambiguate with `target="moxie@<connection>"` (the tool's error tells the Bot the exact forms). Delivery rides the Desktop: the sending gateway queues the message, the Desktop relays it to the target connection's own gateway, the target Bot runs a turn in its canonical Bot Chat, and the reply comes back to the sender as the same background completion notification local DMs use (the process that waits for it is a Hermes entrypoint, so it starts under `approvals.single_query_mode: deny` — the default for a Bot's one-shot reply turn — too). Messages to different Bots are delivered side by side, so one Bot's long turn never delays another Bot's mail (or ages it past `bot_mode.envelope_ttl_seconds`); messages to the *same* Bot are delivered in order, one turn at a time.- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging; a message the Desktop picked up but never handed to the target (it disconnected in between) is offered to the next drain again — once, and only after the Desktop's own delivery deadline (~26 minutes) has passed with no reply, so a slow-but-live turn is never delivered twice. The sender keeps waiting long enough for that second delivery to finish (~52 minutes in all); if it still gets no reply, the sender is told so with reason `delivery_timeout`. While a re-offered message waits for a drain, `bot_mode.envelope_ttl_seconds` applies to it exactly as to a freshly queued one, and the first reply recorded for a message is the one that stands. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.- **A remote `default` goes by its title.** Every machine's `default` is `@hermes`, so a remote one is offered — and reachable — under its Bot Mode title instead (a remote `default` titled *CoS Bot* is `@cos-bot`; with no title, `hermes@<connection>`), and a DM it sends arrives signed with that same reply-safe form rather than a bare `@hermes` that would point back at your own default.+- **The 10-minute cap bounds the target's turn, not its handoffs.** A relayed message gives the target Bot 10 minutes to finish its turn. When that turn messages a teammate itself, the delivery process stays alive afterwards — bounded by `terminal.oneshot_completion_wait_seconds` — so the teammate's reply can land in its Bot Chat (and, when it arrives in time, becomes the answer relayed back). That wait is never counted against the cap: a turn that finished is reported to the sender with its answer, not as `delivery_timeout`, and its handoff is left to complete.### Bot-initiated DMs across machines (`hermes peer`)