sessions_discard.py 4.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """``hermes sessions discard``: acknowledge a turn lost across a gateway crash, without a REPL.
  2. After an owner restart mid-turn, the session's ``started`` admission is fenced ``unknown`` and
  3. everything queued behind it waits. A finite ``hermes chat --resume <id> -q`` refuses (exit 3)
  4. rather than queue behind it. Interactively, ``/discard <admission>`` clears it. This is the same
  5. fenced control (``prompt.resolve_unknown`` with the generation the owner stamped) for scripts.
  6. The lost input is not replayed; it stays in the transcript to resend.
  7. """
  8. from __future__ import annotations
  9. import sys
  10. async def _resume(client, name):
  11. """Exact session id first, then title, as ``hermes chat --resume`` / ``-c`` resolve it."""
  12. from hermes_cli.gateway_client import GatewayClientError
  13. for key in ("session_id", "title"):
  14. try:
  15. return await client.rpc("session.resume", **{key: name})
  16. except GatewayClientError as exc:
  17. if str(exc) != "not_found":
  18. raise
  19. raise GatewayClientError(f"No session found matching '{name}'. Use 'hermes sessions list' to see available sessions.")
  20. def _confirm(session_id, rows):
  21. print(f"Discard {len(rows)} lost turn(s) on session {session_id}? They are acknowledged, not replayed.")
  22. for row in rows:
  23. print(f" {row['admission_id']}")
  24. try:
  25. return input("Proceed? [y/N] ").strip().lower() in {"y", "yes"}
  26. except EOFError:
  27. return False
  28. async def _discard(args):
  29. from hermes_cli.gateway_client import GatewayClientError, connect_gateway
  30. async with connect_gateway() as client:
  31. snapshot = await _resume(client, args.session)
  32. session_id = snapshot.get("session_id") or snapshot["stored_session_id"]
  33. unknown = [row for row in snapshot.get("pending", []) if row.get("status") == "unknown"]
  34. if args.admission:
  35. chosen = [row for row in unknown if row["admission_id"] in set(args.admission)]
  36. missing = sorted(set(args.admission) - {row["admission_id"] for row in chosen})
  37. if missing:
  38. raise GatewayClientError("Not an unknown (lost) admission of this session: " + ", ".join(missing))
  39. else:
  40. chosen = unknown
  41. if not chosen:
  42. print(f"Nothing to discard: session {session_id} has no unknown admission.")
  43. return 0
  44. if not args.yes:
  45. if not sys.stdin.isatty():
  46. print("Refusing to discard without confirmation on a non-interactive stdin; pass --yes.", file=sys.stderr)
  47. return 2
  48. if not _confirm(session_id, chosen):
  49. print("Cancelled; nothing was discarded.")
  50. return 1
  51. for row in chosen:
  52. await client.rpc("prompt.resolve_unknown", session_id=session_id, admission_id=row["admission_id"],
  53. execution_generation=row["execution_generation"])
  54. print(f"Discarded {row['admission_id']}")
  55. return 0
  56. def add_discard_parser(sessions_subparsers) -> None:
  57. from hermes_cli.subcommands._shared import add_yes_flag
  58. parser = sessions_subparsers.add_parser(
  59. "discard", help="Acknowledge turns lost in a gateway crash (unknown admissions) so the session runs again",
  60. description="After a gateway crash mid-turn, the lost turn is fenced 'unknown' and blocks the "
  61. "session: `hermes chat --resume <id> -q` exits 3 until it is acknowledged. This is the "
  62. "non-interactive form of `/discard <admission>`. The lost input is not replayed.")
  63. parser.add_argument("session", help="Session ID or title")
  64. parser.add_argument("--admission", action="append", metavar="ID",
  65. help="Discard only this unknown admission (repeatable; default: every unknown admission)")
  66. add_yes_flag(parser, "Do not ask for confirmation (required when stdin is not a TTY)")
  67. def cmd_discard(args) -> int:
  68. import asyncio
  69. from websockets.exceptions import WebSocketException
  70. from hermes_cli.gateway_client import GatewayClientError
  71. try:
  72. return asyncio.run(_discard(args))
  73. except (GatewayClientError, OSError, TimeoutError, WebSocketException) as exc:
  74. message = str(exc) if isinstance(exc, GatewayClientError) else "Gateway connection/read failed"
  75. print("Error: " + message, file=sys.stderr)
  76. return 1