approval_mode.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Shared persistent approval-mode command logic.
  2. Approval mode is profile-scoped configuration, not conversation state. Changing it affects
  3. subsequent terminal guard checks immediately because approval.py loads config on each check; it must
  4. not rebuild a live agent or mutate its system prompt/tool schema, preserving the prompt-cache
  5. prefix.
  6. """
  7. from __future__ import annotations
  8. from contextlib import redirect_stderr, redirect_stdout
  9. from dataclasses import dataclass
  10. from io import StringIO
  11. from typing import Optional
  12. VALID_APPROVAL_MODES = ("manual", "smart", "off")
  13. @dataclass(frozen=True)
  14. class ApprovalModeResult:
  15. ok: bool
  16. mode: str
  17. changed: bool
  18. message: str
  19. def _effective_mode() -> str:
  20. """Return the exact mode enforced by the terminal approval guard."""
  21. from tools.approval_context import _get_approval_mode
  22. return _get_approval_mode()
  23. def run_approval_mode_command(requested_mode: Optional[str]) -> ApprovalModeResult:
  24. """Inspect or persist ``approvals.mode`` through canonical config APIs."""
  25. current = _effective_mode()
  26. requested = (requested_mode or "").strip().lower()
  27. if not requested:
  28. return ApprovalModeResult(True, current, False, f"Approval mode: {current} (persistent profile setting).")
  29. if requested not in VALID_APPROVAL_MODES:
  30. return ApprovalModeResult(False, current, False, "Usage: /approvals [manual|smart|off]")
  31. # set_config_value is the canonical managed-scope/write-safety chokepoint. It reports managed
  32. # policy through stderr + SystemExit, and the fail-closed write guard raises RuntimeError on an
  33. # unparseable config.yaml; capture both for slash-command output instead of terminating the
  34. # interactive worker.
  35. from hermes_cli.config import set_config_value
  36. output = StringIO()
  37. try:
  38. with redirect_stdout(output), redirect_stderr(output):
  39. set_config_value("approvals.mode", requested)
  40. except SystemExit:
  41. detail = output.getvalue().strip() or "Approval mode is managed and cannot be changed."
  42. return ApprovalModeResult(False, current, False, detail)
  43. except Exception as exc:
  44. return ApprovalModeResult(False, current, False, f"Failed to save approval mode: {exc}")
  45. effective = _effective_mode()
  46. if effective != requested:
  47. return ApprovalModeResult(
  48. False, effective, False,
  49. f"Approval mode remains {effective}; the requested value did not become effective.",
  50. )
  51. return ApprovalModeResult(
  52. True, effective, effective != current, f"Approval mode: {effective} (persistent profile setting).",
  53. )