Skip to content

The agent that grows with you

fix(cli): reconnect the classic CLI after a gateway restart

unsupportedpastels85b85f13677d
diff --git a/agent/error_surface.py b/agent/error_surface.py
index ff977fa8526..985c97411bf 100644
--- a/agent/error_surface.py
+++ b/agent/error_surface.py
@@ -37,6 +37,7 @@ LAYER_DISK = "disk"
_REASON_TO_LAYER = {
"auth": LAYER_AUTH, "auth_permanent": LAYER_AUTH, "billing": LAYER_BILLING, "billing_unverified": LAYER_BILLING,
"loop_error": LAYER_GATEWAY, "interpreter_shutdown": LAYER_GATEWAY, "session_busy": LAYER_GATEWAY,
+ "gateway_connection": LAYER_GATEWAY,
"truncated": LAYER_PROVIDER, "empty_response": LAYER_PROVIDER, "invalid_response": LAYER_PROVIDER,
"context_overflow": LAYER_PROVIDER, # a bigger-window model IS the fix, so Switch provider applies
}
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index 52c0ca59d95..655ea2772a0 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -18,7 +18,7 @@ from hermes_constants import display_hermes_home
# Failure codes minted by loop sites that are not provider verdicts (see module docstring).
SITE_FAILURE_CODES = frozenset({
"context_overflow", "truncated", "invalid_response", "empty_response", "loop_error",
- "interpreter_shutdown", "session_busy",
+ "interpreter_shutdown", "session_busy", "gateway_connection",
})
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 26b89ace1fe..8038b26715a 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -18,7 +18,7 @@ import time
import uuid
from hermes_cli.gateway_client import GatewayClientError
-from hermes_cli.gateway_connection import DISCONNECTED
+from hermes_cli.gateway_connection import DISCONNECTED, lost_before
logger = logging.getLogger(__name__)
@@ -146,6 +146,7 @@ class GatewayAgent:
self._todo_store = _TodoView()
self._generation = None
self._admission = None
+ self._epoch = None # the connection epoch this turn was submitted on
self._interrupt_sent_at = None
self._rate_limit_state = None
self._config_context_length = None
@@ -529,7 +530,8 @@ class GatewayAgent:
receipt = self.connection.call("prompt.submit", **self._submit_params(
user_message, persist_user_message, turn_author))
except GatewayClientError as exc:
- return self._failed(history, user_message, str(exc))
+ return self._failed(history, user_message, str(exc), failure_reason="gateway_connection")
+ self._epoch = getattr(self.connection, "epoch", None)
self._admission = (receipt or {}).get("admission_id")
if receipt and receipt.get("execution_generation") is not None:
self._generation = receipt["execution_generation"]
@@ -539,7 +541,8 @@ class GatewayAgent:
finally:
self._generation_done()
if isinstance(outcome, Exception):
- return self._failed(history, user_message, str(outcome) or DISCONNECTED)
+ return self._failed(history, user_message, str(outcome) or DISCONNECTED,
+ failure_reason="gateway_connection")
return self._result(history, user_message, outcome)
def _drain_stale(self):
@@ -550,6 +553,8 @@ class GatewayAgent:
except queue.Empty:
return
if isinstance(frame, Exception):
+ if lost_before(frame, getattr(self.connection, "epoch", None)):
+ continue # a connection a reconnect already replaced
self.connection.events.put(frame)
return
@@ -569,6 +574,8 @@ class GatewayAgent:
except queue.Empty:
continue
if isinstance(frame, Exception):
+ if lost_before(frame, self._epoch):
+ continue # the previous connection's loss, already reported; this turn is live
return frame
params = frame.get("params") if isinstance(frame, dict) else None
if not isinstance(params, dict) or params.get("session_id") != self.session_id:
@@ -808,9 +815,14 @@ class GatewayAgent:
return staged
return {"role": "user", "content": user_message}
- def _failed(self, history, user_message, error):
- return {**_RESULT_DEFAULTS, "final_response": "", "messages": history + [self._user_row(user_message)],
- "failed": True, "completed": False, "error": error, "session_id": self.session_id}
+ def _failed(self, history, user_message, error, *, failure_reason=None):
+ """``failure_reason="gateway_connection"``: the CLI shows ``error`` as written instead of
+ classifying a lost gateway as a model failure ("Run /model to switch...")."""
+ out = {**_RESULT_DEFAULTS, "final_response": "", "messages": history + [self._user_row(user_message)],
+ "failed": True, "completed": False, "error": error, "session_id": self.session_id}
+ if failure_reason:
+ out.update(failure_reason=failure_reason, failure_retryable=False)
+ return out
def _result(self, history, user_message, complete):
receipt = {}
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 1cc01cc7b46..9deb250f62a 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -388,6 +388,16 @@ class GatewayChatView:
if self.resume_footer:
print(resume_footer(self.session_id), flush=True)
+ @staticmethod
+ def _report_silent_interrupt(text, result):
+ """A restart or stop drain settles a finite turn interrupted with no reply: say so on stderr
+ instead of exiting 130 silently. It is never replayed."""
+ if text or not result.get("interrupted"):
+ return
+ reason = result.get("interrupt_message")
+ print(f"Turn interrupted{f' ({reason})' if isinstance(reason, str) and reason else ''}; "
+ "it was not retried. Resume this session to continue.", file=sys.stderr)
+
def _write_usage_file(self, result, outcome):
"""``-z --usage-file``: the same JSON ledger the in-process one-shot wrote."""
from hermes_cli.oneshot import _write_usage_file
@@ -448,6 +458,7 @@ class GatewayChatView:
if self.emitter is not None:
return self.emitter.emit_result({**result, "final_response": text},
session_id=self.session_id, exit_code=exit_code)
+ self._report_silent_interrupt(text, result)
print(text, flush=True)
# Same stderr exit contract as the legacy -Q path: automation wrappers read the
# durable id from this line, and it names the physical row (a compaction may have
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 372ec7fd95e..6dcb335cf5a 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -23,6 +23,13 @@ DISCONNECTED = ("Gateway disconnected; turn outcome is unknown. Resume the print
"whether it completed or was interrupted; do not resend the work.")
+def lost_before(frame, epoch) -> bool:
+ """``frame`` is a transport error from a connection older than ``epoch``: a reconnect replaced it,
+ so it is no outcome of anything submitted on ``epoch``."""
+ lost = getattr(frame, "connection_epoch", None)
+ return isinstance(frame, Exception) and lost is not None and epoch is not None and lost < epoch
+
+
class SessionState:
"""What the gateway last told this viewer about one session (plain attributes, GIL-atomic
reads from the prompt_toolkit render thread; never an RPC per paint)."""
@@ -87,6 +94,10 @@ class GatewayConnection:
self._stop = None
self._start_lock = threading.Lock()
self.closed = False
+ # close() ends the viewer; a gateway hang-up (restart, idle exit, crash) lets the next call
+ # dial again. Each connect bumps ``epoch``, and its loss is tagged with it (``lost_before``).
+ self._detached = False
+ self.epoch = 0
# /bg and /btw answers by task id (hermes_cli/gateway_side.py); created by whichever of the
# waiter or the frame comes first, so an answer faster than the verb's reply is kept.
self._side: dict[str, queue.Queue] = {}
@@ -109,9 +120,15 @@ class GatewayConnection:
def start(self, timeout=90):
with self._start_lock:
if self._thread is not None:
- if self._error is not None:
- raise self._error
- return
+ if self._thread.is_alive() or self._detached or (self._error is not None and not self.epoch):
+ if self._error is not None:
+ raise self._error
+ return
+ # The gateway hung up, or the last redial failed: dial again (``connect_gateway``
+ # starts a gateway when none is running) and resubscribe this viewer's sessions.
+ self._error = None
+ self._ready.clear()
+ self.closed = False
self._thread = threading.Thread(target=self._run, name="hermes-gateway-loop", daemon=True)
self._thread.start()
if not self._ready.wait(timeout):
@@ -139,6 +156,9 @@ class GatewayConnection:
connect = connect_gateway
try:
async with connect() as client:
+ if self.epoch:
+ await self._resubscribe(client)
+ self.epoch += 1
self.client = client
self._ready.set()
pump = asyncio.create_task(self._pump(client))
@@ -151,15 +171,30 @@ class GatewayConnection:
self._error = exc if isinstance(exc, GatewayClientError) else GatewayClientError(
f"Gateway connection failed; no local fallback ({type(exc).__name__})")
else:
- self.events.put(GatewayClientError(DISCONNECTED))
+ self._put_loss(GatewayClientError(DISCONNECTED))
finally:
self.client = None
+ def _put_loss(self, error):
+ error.connection_epoch = self.epoch
+ self.events.put(error)
+
+ async def _resubscribe(self, client):
+ """A new socket is a new viewer: the gateway streams a session's frames only to connections
+ that resumed it. Resume each session this viewer had open; one deleted meanwhile is skipped."""
+ for session_id, state in list(self.states.items()):
+ if state.subscription_id is None:
+ continue
+ try:
+ state.adopt_snapshot(await client.rpc("session.resume", session_id=session_id))
+ except (GatewayClientError, TimeoutError) as exc:
+ logger.debug("session.resume %s after reconnect failed: %s", session_id, exc)
+
async def _pump(self, client):
while True:
frame = await client.events.get()
if isinstance(frame, Exception):
- self.events.put(frame)
+ self._put_loss(frame)
return
params = frame.get("params") if isinstance(frame, dict) else None
if isinstance(params, dict) and self._take_side(params):
@@ -190,6 +225,7 @@ class GatewayConnection:
self._side.pop(task_id, None)
def close(self):
+ self._detached = True
loop, stop = self.loop, self._stop
if loop is not None and stop is not None and not self.closed:
try:
diff --git a/hermes_cli/gateway_tools_notify.py b/hermes_cli/gateway_tools_notify.py
index 35560441ea1..293c23fede6 100644
--- a/hermes_cli/gateway_tools_notify.py
+++ b/hermes_cli/gateway_tools_notify.py
@@ -49,6 +49,9 @@ def queue_admitted_turn(cli, store) -> None:
except queue.Empty:
return
if isinstance(frame, Exception):
+ from hermes_cli.gateway_connection import lost_before
+ if lost_before(frame, getattr(connection, "epoch", None)):
+ continue # a connection a reconnect already replaced
events.put(frame) # the disconnect belongs to the next turn
return
params = frame.get("params") if isinstance(frame, dict) else None
diff --git a/tests/hermes_cli/test_gateway_connection_reconnect.py b/tests/hermes_cli/test_gateway_connection_reconnect.py
new file mode 100644
index 00000000000..0607015636e
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_connection_reconnect.py
@@ -0,0 +1,183 @@
+"""The classic CLI dials the gateway again after it restarts (#134889).
+
+GatewayConnection kept its finished loop thread, so after a gateway restart every call raised
+"Gateway disconnected" and the CLI never re-attached, even once another client had started a new
+gateway. Each prompt then failed with copy that read as a model failure ("Run /model to switch").
+"""
+import asyncio
+from contextlib import asynccontextmanager
+
+import pytest
+
+from hermes_cli.cli_chat_error_copy import chat_error_response
+from hermes_cli.gateway_agent import GatewayAgent
+from hermes_cli.gateway_client import GatewayClientError
+from hermes_cli.gateway_connection import GatewayConnection, lost_before
+
+SID = "local-abc"
+
+
+def _frame(kind, payload):
+ return {"jsonrpc": "2.0", "method": "event", "params": {
+ "type": kind, "session_id": SID, "admission_id": "adm-1", "execution_generation": 7, "payload": payload}}
+
+
+class Life:
+ """One gateway process as one client sees it: from a dial until it hangs up."""
+
+ def __init__(self, number, *, drop_on_submit=False):
+ self.number = number
+ self.events = asyncio.Queue()
+ self.calls = []
+ self.drop_on_submit = drop_on_submit
+
+ async def rpc(self, method, *, _timeout=None, **params):
+ self.calls.append((method, params))
+ if method == "session.resume":
+ return {"stored_session_id": params["session_id"], "subscription_id": f"sub-{self.number}",
+ "revision": 1, "execution_generation": 7, "messages": []}
+ if method == "prompt.submit":
+ loop = asyncio.get_running_loop()
+ if self.drop_on_submit: # restarted mid-turn: the outcome is unknown to this client
+ loop.call_soon(self.events.put_nowait, GatewayClientError("Gateway disconnected"))
+ else:
+ loop.call_soon(self.events.put_nowait, _frame(
+ "message.complete", {"text": f"reply {self.number}", "outcome": "completed", "status": "complete"}))
+ return {"admission_id": "adm-1", "status": "queued", "execution_generation": 7}
+ if method == "prompt.receipt":
+ return {"result": {"final_response": f"reply {self.number}", "completed": True}, "usage": {}}
+ return {"status": "ok", "life": self.number}
+
+
+class Gateway:
+ """Each dial reaches a fresh gateway life; ``refusals`` makes the next dials fail first."""
+
+ def __init__(self):
+ self.lives = []
+ self.refusals = 0
+ self.drop_next_submit = False
+
+ @asynccontextmanager
+ async def dial(self):
+ if self.refusals:
+ self.refusals -= 1
+ raise GatewayClientError("Gateway starting: deadline. Your message was not sent.")
+ life = Life(len(self.lives) + 1, drop_on_submit=self.drop_next_submit)
+ self.drop_next_submit = False
+ self.lives.append(life)
+ yield life
+
+ def hang_up(self, conn):
+ """The current life goes away (``gateway restart``); the loop thread ends with it."""
+ thread = conn._thread
+ conn.loop.call_soon_threadsafe(self.lives[-1].events.put_nowait, GatewayClientError("Gateway disconnected"))
+ thread.join(5)
+ assert not thread.is_alive()
+
+
+def gateway():
+ return Gateway()
+
+
+def conn(gateway):
+ connection = GatewayConnection(connect=gateway.dial)
+ connection.start(5)
+ connection.state(SID).adopt_snapshot(connection.call("session.resume", session_id=SID))
+ yield connection
+ connection.close()
+
+
+def test_the_next_call_after_a_restart_reconnects_and_resubscribes(gateway, conn):
+ assert conn.epoch == 1
+ gateway.hang_up(conn)
+
+ assert conn.call("status") == {"status": "ok", "life": 2}
+ assert conn.epoch == 2
+ # Resubscribed before the reconnect counts as ready, so no frame of the new life is missed.
+ assert gateway.lives[1].calls[0] == ("session.resume", {"session_id": SID})
+ assert conn.state(SID).subscription_id == "sub-2"
+ lost = conn.events.get_nowait()
+ assert isinstance(lost, GatewayClientError) and lost_before(lost, conn.epoch)
+
+
+def test_close_ends_the_viewer_for_good(gateway, conn):
+ conn.close()
+ with pytest.raises(GatewayClientError, match="disconnected"):
+ conn.call("status")
+ assert len(gateway.lives) == 1
+
+
+def test_a_failed_redial_is_retried_on_the_next_call(gateway, conn):
+ gateway.hang_up(conn)
+ gateway.refusals = 1
+ with pytest.raises(GatewayClientError, match="Gateway starting"):
+ conn.call("status")
+ assert conn.call("status") == {"status": "ok", "life": 2}
+
+
+def test_a_first_connect_failure_is_still_final(gateway):
+ gateway.refusals = 2
+ connection = GatewayConnection(connect=gateway.dial)
+ for _ in range(2):
+ with pytest.raises(GatewayClientError, match="Gateway starting"):
+ connection.call("status")
+ assert gateway.refusals == 1 # never redialed: nothing to come back to
+
+
+def test_a_turn_lost_to_a_restart_is_reported_plainly_and_the_next_turn_runs(gateway, conn):
+ agent = GatewayAgent(connection=conn, session_id=SID)
+ gateway.lives[0].drop_on_submit = True
+
+ lost = agent.run_conversation("first")
+ assert lost["failed"] and lost["failure_reason"] == "gateway_connection"
+ assert "turn outcome is unknown" in lost["error"] or "Gateway disconnected" in lost["error"]
+ # The panel shows the transport error itself, not "The model request failed. Run /model ...".
+ assert chat_error_response(lost["error"], failure_reason=lost["failure_reason"]) == lost["error"]
+
+ conn._thread.join(5)
+ result = agent.run_conversation("second")
+ assert not result.get("failed") and result["final_response"] == "reply 2"
+ assert [method for method, _ in gateway.lives[1].calls][:2] == ["session.resume", "prompt.submit"]
+
+
+def test_the_previous_connections_loss_never_fails_a_live_turn(gateway, conn):
+ """Idle when the gateway restarted: the loss is queued, and the next prompt reconnects and
+ submits. Reading that loss as its own outcome would invite the user to resend accepted work."""
+ agent = GatewayAgent(connection=conn, session_id=SID)
+ gateway.hang_up(conn)
+ result = agent.run_conversation("hi")
+ assert not result.get("failed") and result["final_response"] == "reply 2"
+
+
+def test_lost_before():
+ error = GatewayClientError("Gateway disconnected")
+ assert not lost_before(error, 2) # untagged: a live loss
+ error.connection_epoch = 1
+ assert lost_before(error, 2) and not lost_before(error, 1) and not lost_before(error, None)
+ assert not lost_before({"connection_epoch": 1}, 2)
+
+
+def test_chat_q_says_why_a_turn_was_interrupted(capsys):
+ """A restart drain settles a running `chat -q` turn interrupted with no reply text: exit 130
+ as before, but no longer silently."""
+ from hermes_cli.gateway_chat_view import GatewayChatView
+
+ class Client:
+ def __init__(self):
+ self.events = asyncio.Queue()
+
+ async def rpc(self, method, **params):
+ if method == "prompt.submit":
+ asyncio.get_running_loop().call_soon(self.events.put_nowait, _frame(
+ "message.complete", {"text": "", "outcome": "cancelled", "status": "interrupted"}))
+ return {"admission_id": "adm-1", "status": "queued", "execution_generation": 7}
+ if method == "prompt.receipt":
+ return {"result": {"final_response": "", "interrupted": True,
+ "interrupt_message": "Gateway shutting down"}}
+ return {}
+
+ code = asyncio.run(GatewayChatView(Client(), {"stored_session_id": SID}).run("hi", oneshot=True))
+ assert code == 130
+ assert "Turn interrupted (Gateway shutting down); it was not retried." in capsys.readouterr().err