Skip to content

The agent that grows with you

fix(peer): a connect-phase timeout is unreachable; only a response timeout means the turn was accepted

John Paul Soliva0497b9457077
diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.py
index 5962a7218ab..d858a04b9f7 100644
--- a/hermes_cli/subcommands/peer.py
+++ b/hermes_cli/subcommands/peer.py
@@ -343,6 +343,7 @@ def _peer_run(args, message: str, peer_name: str, profile: str | None, base: str
def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:
+ session_id = ""
try:
session_id = _ensure_bot_chat(base, key)
result = _request(
@@ -352,6 +353,17 @@ def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str,
print(f"Peer '{peer_name}': {exc}", file=sys.stderr)
return 1
except (urllib.error.URLError, TimeoutError, OSError) as exc:
+ # A timeout while awaiting the response, once the Bot Chat is known, means the peer took
+ # this turn: the message is already in its Bot Chat and the gateway runs the turn to
+ # completion regardless of this client, so reporting it unreachable makes the sender resend
+ # and deliver it twice. urllib raises that timeout bare; one it wraps in URLError hit while
+ # connecting or sending, so the request never arrived and "could not reach" is the truth.
+ if session_id and isinstance(exc, TimeoutError):
+ print(f"Peer '{peer_name}' accepted the message but its turn is still running after "
+ f"{DM_TIMEOUT_S}s: the message is already in its Bot Chat (session {session_id}) "
+ "and will be answered there. The reply cannot come back on this call. Do NOT resend.",
+ file=sys.stderr)
+ return 1
return _peer_failure(peer_name, exc)
msg = result.get("message")
reply = str(msg.get("content") or "") if isinstance(msg, dict) else ""
diff --git a/tests/hermes_cli/test_peer_dm_reporting.py b/tests/hermes_cli/test_peer_dm_reporting.py
new file mode 100644
index 00000000000..e5b84f58001
--- /dev/null
+++ b/tests/hermes_cli/test_peer_dm_reporting.py
@@ -0,0 +1,112 @@
+"""What ``hermes peer dm`` tells the sender when the turn does not come back.
+
+A peer DM is one synchronous ``POST /api/sessions/{id}/chat`` with a 600 s client timeout, and the
+receiving gateway runs the turn to completion whatever the client does. So a timeout while awaiting
+the response means the message IS in the peer's Bot Chat and is being answered — the opposite of
+unreachable. Reporting it as unreachable makes the sending bot resend, and the teammate runs the same
+turn twice. A timeout while connecting means the request never arrived, and must stay unreachable.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import socket
+import threading
+import urllib.error
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli.subcommands import peer as peer_mod
+
+SESSION = "20260916_bot_chat"
+
+
+def _run(monkeypatch, capsys, *, base="http://192.168.2.55:8642", raise_on_post=None, raise_on_session=None):
+ def _ensure(base, key):
+ if raise_on_session is not None:
+ raise raise_on_session
+ return SESSION
+
+ monkeypatch.setattr(peer_mod, "_ensure_bot_chat", _ensure)
+ if raise_on_post is not None:
+ def _request(url, key, **kwargs):
+ raise raise_on_post
+
+ monkeypatch.setattr(peer_mod, "_request", _request)
+ code = peer_mod._peer_dm(SimpleNamespace(json=False), "hello", "mini", None, base, "key")
+ return code, capsys.readouterr().err
+
+
+ ("raise_on_post", "raise_on_session", "expected", "forbidden"),
+ [
+ (TimeoutError("timed out"), None, "accepted the message but its turn is still running", "Could not reach"),
+ (urllib.error.URLError(TimeoutError("timed out")), None, "Could not reach peer", "still running"),
+ (urllib.error.URLError(ConnectionRefusedError(61, "Connection refused")), None, "Could not reach peer", "still running"),
+ (OSError(51, "Network is unreachable"), None, "Could not reach peer", "still running"),
+ (TimeoutError("timed out"), TimeoutError("timed out"), "Could not reach peer", "still running"),
+ (urllib.error.HTTPError("http://peer/chat", 503, "Service Unavailable", {}, None), None,
+ "rejected the request (HTTP 503)", "still running"),
+ ],
+ ids=["response-timeout", "connect-timeout", "connection-refused", "network-unreachable",
+ "timeout-before-the-session-is-known", "http-rejection"],
+)
+def test_only_a_timeout_on_an_accepted_turn_is_reported_as_delivered(
+ monkeypatch, capsys, raise_on_post, raise_on_session, expected, forbidden
+):
+ """Two things must both hold to call the message delivered: the Bot Chat was already resolved
+ (the peer answered a moment ago) and the timeout hit while awaiting the response (urllib raises
+ that one bare). A connect-phase timeout, a refusal, or a status code proves nothing arrived."""
+ code, err = _run(monkeypatch, capsys, raise_on_post=raise_on_post, raise_on_session=raise_on_session)
+
+ assert code == 1
+ assert expected in err
+ assert forbidden not in err
+ if "still running" in expected:
+ assert SESSION in err
+ assert "Do NOT resend" in err
+
+
[email protected]("phase", ["response", "connect"])
+def test_the_real_urllib_stack_raises_the_signatures_the_branch_relies_on(monkeypatch, capsys, phase):
+ """Through the real opener, not a hand-built exception: urllib wraps a connect/send failure in
+ ``URLError`` and lets a timeout on the response through bare. Getting that backwards reports a
+ message that never arrived as delivered, and the sender is told not to resend it."""
+ for var in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setattr(peer_mod, "DM_TIMEOUT_S", 0.5)
+
+ server = socket.socket()
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ held = []
+ done = threading.Event()
+
+ def _accept_and_never_answer():
+ with contextlib.suppress(OSError): # the connect phase never dials, so close() ends accept()
+ conn, _ = server.accept()
+ held.append(conn)
+ conn.recv(65536)
+ done.wait(10)
+
+ thread = threading.Thread(target=_accept_and_never_answer, daemon=True)
+ thread.start()
+ if phase == "connect":
+ def _connect_times_out(*args, **kwargs):
+ raise TimeoutError("timed out")
+
+ monkeypatch.setattr(socket, "create_connection", _connect_times_out)
+ try:
+ code, err = _run(monkeypatch, capsys, base=f"http://127.0.0.1:{server.getsockname()[1]}")
+ finally:
+ done.set()
+ server.close()
+ for conn in held:
+ conn.close()
+
+ assert code == 1
+ if phase == "response":
+ assert "accepted the message but its turn is still running" in err and "Do NOT resend" in err
+ else:
+ assert "Could not reach peer" in err and "still running" not in err
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index e188bc5d0c8..58c0630d86c 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -236,7 +236,10 @@ hermes peer stop spark run_abc123
`hermes peer dm` delivers into the remote agent's canonical Bot Chat over the peer's existing API server, runs one agent turn there, and prints the reply on stdout — the exact cross-machine twin of the local `hermes -p <bot> chat` command.
Use `peer dm` only for short queries and receipts because it holds one HTTP
-connection until the turn finishes. For a long turn, `peer run` returns a
+connection until the turn finishes. If the peer takes the message but the turn outlasts that
+connection, the message is already in the peer's Bot Chat and the turn keeps running there, so the
+command says exactly that instead of reporting the peer unreachable — resending would run the turn
+twice. A timeout while connecting still reports the peer unreachable. For a long turn, `peer run` returns a
`run_id` immediately; poll it with `peer status`. The run inherits the
canonical Bot Chat transcript, and a stable `--idempotency-key` makes a retry
return the original run instead of starting duplicate work. Use `peer stop`