gateway_rollback.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """``/rollback`` on the shared gateway session (``rollback.list`` / ``rollback.diff`` / ``rollback.restore``).
  2. The gateway's tools take the checkpoints (its ``CheckpointManager``, keyed by the session's launch
  3. cwd), so the CLI process has no manager of its own: it renders main's text over the owner's
  4. answers. A whole-tree restore also rewinds the newest user turn on the owner (``history_removed``);
  5. the CLI then re-reads the transcript so its warm history matches.
  6. """
  7. from __future__ import annotations
  8. import os
  9. from agent.i18n import t
  10. from hermes_cli.gateway_client import GatewayClientError
  11. def _t(key, **kw):
  12. return t(f"cli.commands.{key}", **kw)
  13. def _checkpoint_rows(result):
  14. """``rollback.list`` rows as ``format_checkpoint_list`` reads them."""
  15. return [{"hash": c.get("hash", ""), "short_hash": (c.get("hash") or "")[:7], "timestamp": c.get("timestamp", ""),
  16. "reason": c.get("message", "")} for c in result.get("checkpoints") or []]
  17. def rollback(cli, connection, command):
  18. from tools.checkpoint_manager import format_checkpoint_list
  19. words = command.split()[1:]
  20. args = [a for a in words if a.lower() not in ("--all", "--force")]
  21. restore_all = len(args) != len(words)
  22. cwd = os.getenv("TERMINAL_CWD", os.getcwd())
  23. sid = cli.session_id
  24. try:
  25. if not args:
  26. listed = connection.call("rollback.list", session_id=sid)
  27. if not listed.get("enabled"):
  28. return print("\n".join(f" {line}" if line else "" for line in _t("rollback.not_enabled").splitlines()))
  29. return print(format_checkpoint_list(_checkpoint_rows(listed), cwd))
  30. if args[0].lower() == "diff":
  31. if len(args) < 2:
  32. return print(f" {_t('rollback.usage_diff')}")
  33. return _diff(connection.call("rollback.diff", session_id=sid, hash=args[1]))
  34. params = {"session_id": sid, "hash": args[0]}
  35. if len(args) > 1:
  36. params["file_path"] = args[1]
  37. elif restore_all:
  38. params["all"] = True # main's --all/--force: also revert the user's hand-edits
  39. _restored(cli, connection, connection.call("rollback.restore", **params), params.get("file_path"))
  40. except GatewayClientError as exc:
  41. print(f" ❌ {exc}")
  42. def _diff(result):
  43. stat, diff = result.get("stat", ""), result.get("diff", "")
  44. if not stat and not diff:
  45. return print(f" {_t('rollback.no_changes_since')}")
  46. if stat:
  47. print(f"\n{stat}")
  48. if diff:
  49. lines = diff.splitlines()
  50. if len(lines) > 80: # main's terminal-flood limit
  51. print("\n".join(lines[:80]))
  52. print(f"\n {_t('rollback.more_lines', count=len(lines) - 80)}")
  53. else:
  54. print(f"\n{diff}")
  55. def _restored(cli, connection, result, file_path):
  56. if not result.get("success"):
  57. return print(f" ❌ {result.get('error')}")
  58. restored = {"hash": result.get("restored_to", ""), "reason": result.get("reason", "")}
  59. print(f" {_t('rollback.restored_file', file=file_path, **restored)}" if file_path
  60. else f" {_t('rollback.restored_all', **restored)}")
  61. from hermes_cli.cli_commands_session_tools import _rollback_kept
  62. _rollback_kept(result) # the in-process CLI's own lines
  63. print(f" {_t('rollback.snapshot_saved')}")
  64. if result.get("history_removed"):
  65. snapshot = connection.call("session.resume", session_id=cli.session_id)
  66. connection.state(cli.session_id).adopt_snapshot(snapshot)
  67. cli.conversation_history = [{k: v for k, v in m.items() if k != "row_id"}
  68. for m in snapshot.get("messages") or [] if not m.get("archived")]
  69. print(f" {_t('rollback.chat_turn_undone')}")