Skip to content

The agent that grows with you

fix(cli): `hermes sessions discard` lets scripts recover a session after a gateway crash

Teknium23dcf14bdb32
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 2158a5aee5c..3f42ce4fb7c 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -350,7 +350,8 @@ class GatewayChatView:
# submitting so nothing is left queued for the next interactive resume to find.
lost = " ".join(self.unknown_admissions())
return self._detach("Unknown execution blocks this session; nothing was submitted. Resolve it "
- f"interactively with /discard {lost} (prompt.resolve_unknown), then retry.")
+ f"with `hermes sessions discard {self.session_id} --yes` (or /discard {lost} "
+ "interactively; both are prompt.resolve_unknown), then retry.")
renderer = asyncio.create_task(self.render())
try:
receipt = await self.submit(query) if query else None
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 1f4b5b12ee7..204b4977e26 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -1185,10 +1185,16 @@ def _cmd_set_journal_mode(args):
return cmd_set_journal_mode(args)
+def _cmd_discard(args):
+ from hermes_cli.sessions_discard import cmd_discard
+ return cmd_discard(args)
+
+
_PRE_DB_HANDLERS = {
"repair": _cmd_repair, "recover": _cmd_recover, "import": _cmd_import,
"repair-profiles": _cmd_repair_profiles, # opens every profile's store itself
"set-journal-mode": _cmd_set_journal_mode, # offline: must not open the store it converts
+ "discard": _cmd_discard, # a gateway control (prompt.resolve_unknown), never a direct store write
}
_OBSERVATIONAL_DB_ACTIONS = frozenset({"list", "stats", "pinned"})
_DB_HANDLERS = {
diff --git a/hermes_cli/sessions_discard.py b/hermes_cli/sessions_discard.py
new file mode 100644
index 00000000000..3dc3188562a
--- /dev/null
+++ b/hermes_cli/sessions_discard.py
@@ -0,0 +1,74 @@
+"""``hermes sessions discard``: acknowledge a turn lost across a gateway crash, without a REPL.
+
+After an owner restart mid-turn, the session's ``started`` admission is fenced ``unknown`` and
+everything queued behind it waits. A finite ``hermes chat --resume <id> -q`` refuses (exit 3)
+rather than queue behind it. Interactively, ``/discard <admission>`` clears it. This is the same
+fenced control (``prompt.resolve_unknown`` with the generation the owner stamped) for scripts.
+The lost input is not replayed; it stays in the transcript to resend.
+"""
+from __future__ import annotations
+
+import asyncio
+import sys
+
+from hermes_cli.gateway_client import GatewayClientError, connect_gateway
+
+
+async def _resume(client, name):
+ """Exact session id first, then title, as ``hermes chat --resume`` / ``-c`` resolve it."""
+ for key in ("session_id", "title"):
+ try:
+ return await client.rpc("session.resume", **{key: name})
+ except GatewayClientError as exc:
+ if str(exc) != "not_found":
+ raise
+ raise GatewayClientError(f"No session found matching '{name}'. Use 'hermes sessions list' to see available sessions.")
+
+
+def _confirm(session_id, rows):
+ print(f"Discard {len(rows)} lost turn(s) on session {session_id}? They are acknowledged, not replayed.")
+ for row in rows:
+ print(f" {row['admission_id']}")
+ try:
+ return input("Proceed? [y/N] ").strip().lower() in {"y", "yes"}
+ except EOFError:
+ return False
+
+
+async def _discard(args):
+ async with connect_gateway() as client:
+ snapshot = await _resume(client, args.session)
+ session_id = snapshot.get("session_id") or snapshot["stored_session_id"]
+ unknown = [row for row in snapshot.get("pending", []) if row.get("status") == "unknown"]
+ if args.admission:
+ chosen = [row for row in unknown if row["admission_id"] in set(args.admission)]
+ missing = sorted(set(args.admission) - {row["admission_id"] for row in chosen})
+ if missing:
+ raise GatewayClientError("Not an unknown (lost) admission of this session: " + ", ".join(missing))
+ else:
+ chosen = unknown
+ if not chosen:
+ print(f"Nothing to discard: session {session_id} has no unknown admission.")
+ return 0
+ if not args.yes:
+ if not sys.stdin.isatty():
+ print("Refusing to discard without confirmation on a non-interactive stdin; pass --yes.", file=sys.stderr)
+ return 2
+ if not _confirm(session_id, chosen):
+ print("Cancelled; nothing was discarded.")
+ return 1
+ for row in chosen:
+ await client.rpc("prompt.resolve_unknown", session_id=session_id, admission_id=row["admission_id"],
+ execution_generation=row["execution_generation"])
+ print(f"Discarded {row['admission_id']}")
+ return 0
+
+
+def cmd_discard(args) -> int:
+ from websockets.exceptions import WebSocketException
+ try:
+ return asyncio.run(_discard(args))
+ except (GatewayClientError, OSError, TimeoutError, WebSocketException) as exc:
+ message = str(exc) if isinstance(exc, GatewayClientError) else "Gateway connection/read failed"
+ print("Error: " + message, file=sys.stderr)
+ return 1
diff --git a/hermes_cli/subcommands/sessions.py b/hermes_cli/subcommands/sessions.py
index 0500ef1d413..34f94652f5c 100644
--- a/hermes_cli/subcommands/sessions.py
+++ b/hermes_cli/subcommands/sessions.py
@@ -264,6 +264,16 @@ def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:
sessions_subparsers.add_parser("stats", help="Show session store statistics")
+ sessions_discard = sessions_subparsers.add_parser(
+ "discard", help="Acknowledge turns lost in a gateway crash (unknown admissions) so the session runs again",
+ description="After a gateway crash mid-turn, the lost turn is fenced 'unknown' and blocks the "
+ "session: `hermes chat --resume <id> -q` exits 3 until it is acknowledged. This is the "
+ "non-interactive form of `/discard <admission>`. The lost input is not replayed.")
+ sessions_discard.add_argument("session", help="Session ID or title")
+ sessions_discard.add_argument("--admission", action="append", metavar="ID",
+ help="Discard only this unknown admission (repeatable; default: every unknown admission)")
+ add_yes_flag(sessions_discard, "Do not ask for confirmation (required when stdin is not a TTY)")
+
sessions_rename = sessions_subparsers.add_parser(
"rename", help="Set or change a session's title")
sessions_rename.add_argument("session_id", help="Session ID to rename")
diff --git a/tests/hermes_cli/test_sessions_discard.py b/tests/hermes_cli/test_sessions_discard.py
new file mode 100644
index 00000000000..1002b757806
--- /dev/null
+++ b/tests/hermes_cli/test_sessions_discard.py
@@ -0,0 +1,58 @@
+"""`hermes sessions discard`: a script can clear a turn lost in a gateway crash without a REPL."""
+import argparse
+import asyncio
+import json
+
+import pytest
+
+
+async def test_sessions_discard_yes_resolves_every_unknown_admission_with_its_fenced_generation(monkeypatch, capsys):
+ """The same fenced control as interactive /discard: resume by title, resolve each unknown row with the
+ generation the owner stamped on it, and never touch the queued input behind it. Without --yes on a
+ non-TTY stdin it refuses, and nothing is resolved."""
+ from websockets.asyncio.server import serve
+
+ from hermes_cli import sessions_cmd
+ from hermes_cli.subcommands.sessions import build_sessions_parser
+
+ lost = ["admission-lost-a", "admission-lost-b"]
+ snapshot = {"session_id": "local-abc", "stored_session_id": "local-abc", "pending": [
+ {"admission_id": lost[0], "status": "unknown", "execution_generation": 4},
+ {"admission_id": "admission-queued", "status": "queued", "execution_generation": None},
+ {"admission_id": lost[1], "status": "unknown", "execution_generation": 5}]}
+ calls = []
+
+ async def peer(ws):
+ async for raw in ws:
+ request = json.loads(raw)
+ calls.append((request["method"], request["params"]))
+ if request["method"] == "session.resume" and "session_id" in request["params"]:
+ reply = {"error": {"code": 4001, "message": "not_found", "data": {"reason": "not_found"}}}
+ else:
+ reply = {"result": snapshot if request["method"] == "session.resume" else {"status": "terminal"}}
+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": request["id"], **reply}))
+
+ parser = argparse.ArgumentParser()
+ build_sessions_parser(parser.add_subparsers(dest="command"), cmd_sessions=sessions_cmd.cmd_sessions)
+ monkeypatch.setattr("sys.stdin.isatty", lambda: False)
+ async with serve(peer, "127.0.0.1", 0) as server:
+ monkeypatch.setenv("HERMES_TUI_GATEWAY_URL", f"ws://127.0.0.1:{server.sockets[0].getsockname()[1]}")
+
+ def run(*argv):
+ args = parser.parse_args(["sessions", "discard", "my script session", *argv])
+ return args.func(args)
+
+ assert await asyncio.to_thread(run) == 2
+ assert "--yes" in capsys.readouterr().err
+ assert [m for m, _ in calls] == ["session.resume", "session.resume"]
+ calls.clear()
+ assert await asyncio.to_thread(run, "--yes") == 0
+
+ assert calls == [
+ ("session.resume", {"session_id": "my script session"}),
+ ("session.resume", {"title": "my script session"}),
+ ("prompt.resolve_unknown", {"session_id": "local-abc", "admission_id": lost[0], "execution_generation": 4}),
+ ("prompt.resolve_unknown", {"session_id": "local-abc", "admission_id": lost[1], "execution_generation": 5}),
+ ]
+ assert capsys.readouterr().out.split() == ["Discarded", lost[0], "Discarded", lost[1]]
diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.md
index 897fb33902d..eae45f70ec5 100644
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@ -132,8 +132,8 @@ API, ACP, cron, Bot Chat). What an existing install sees on its first update:
- **Work interrupted by the cutover restart is never replayed.** On the first gateway
start, an input that was mid-turn (`started`) and any managed worker that was running
become `unknown`; queued inputs behind it wait. Inspect the session, then acknowledge
- with `/discard <admission_id>` in `hermes chat` (or the Desktop/TUI equivalent) before
- later inputs run. A cron delivery a gateway had claimed but not finished is likewise
+ with `/discard <admission_id>` in `hermes chat` (or the Desktop/TUI equivalent), or from a
+ script with `hermes sessions discard <session> --yes`, before later inputs run. A cron delivery a gateway had claimed but not finished is likewise
fenced `unknown` and recorded `delivery_failed`.
- **Rolling back after the new gateway has written `state.db`:** the new runtime-ledger
tables reference `sessions` with `ON DELETE RESTRICT`, so an older release that deletes
diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.md
index c7d18881f82..0ea911a9ff5 100644
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@ -522,6 +522,26 @@ hermes sessions rename 20250305_091523_a1b2c3d4 debugging auth flow
If the title is already in use by another session, an error is shown.
+### Discard a Turn Lost in a Gateway Crash
+
+If the gateway stops in the middle of a turn, that turn's outcome is unknown and it is never replayed. It blocks
+the session until you acknowledge it. Interactive `hermes chat --resume <id>` lists it and accepts
+`/discard <admission_id>`. A scripted `hermes chat --resume <id> -q` refuses with exit code 3 and submits nothing.
+To clear it from a script:
+
+```bash
+# Acknowledge every unknown (lost) turn on the session, then continue it
+hermes sessions discard 20250305_091523_a1b2c3d4 --yes
+hermes chat --resume 20250305_091523_a1b2c3d4 -q "next question"
+
+# Only one specific admission (repeatable); the session may also be named by title
+hermes sessions discard "debugging auth flow" --admission a9b59ad3ee914d75967def2a33435c88 --yes
+```
+
+Without `--yes` the command asks for confirmation, and it refuses (exit code 2) when stdin is not a terminal.
+The lost input stays in the transcript. Some of its actions may already have run, so check their effects before
+you resend it. Inputs queued behind it run once it is discarded.
+
### Pin a Session
Pinning sets a durable "keep" flag: pinned sessions are exempt from the