approval_yolo.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Session ``/yolo``: the one toggle / restore / carry contract every surface calls.
  2. The bypass itself is ``tools.approval``'s in-memory per-key set, so every process starts with it empty.
  3. Each surface persists it where its session identity lives: CLI, TUI and Desktop on the session row
  4. (``model_config.yolo_mode``), the messaging gateway on the routing entry, whose key outlives compression
  5. rotations; sessions the gateway owns for CLI/TUI/Desktop clients (``config.set key=yolo``) and their managed
  6. workers use that same routing entry. The surface hands its writer in as ``persist(enabled)``; everything else
  7. is decided here, so the CLI ``/yolo``, the TUI Shift+Tab, the Desktop zap and a Telegram ``/yolo`` behave the same.
  8. """
  9. import logging
  10. from typing import Any, Callable, Optional
  11. from tools import approval
  12. logger = logging.getLogger(__name__)
  13. Persist = Optional[Callable[[bool], Any]]
  14. def _persist(persist: Persist, enabled: bool, session_key: str) -> None:
  15. # Best-effort: the live flag is authoritative for this process; a failed write only costs the restore.
  16. if persist is None:
  17. return
  18. try:
  19. persist(enabled)
  20. except Exception:
  21. logger.warning("failed to persist session yolo=%s for %s", enabled, session_key, exc_info=True)
  22. def toggle_session_yolo(session_key: str, enabled: Optional[bool] = None, *, persisted: bool = False,
  23. persist: Persist = None) -> bool:
  24. """Flip (``enabled=None``) or set the bypass for *session_key*; returns the new state.
  25. *persisted* is the stored flag: after a restart only it is set and the user still sees ON, so a toggle
  26. turns it OFF. The write runs BEFORE the live flip, so a turn restoring in between never revives a
  27. bypass that is being switched off.
  28. """
  29. if enabled is None:
  30. enabled = not (persisted or approval.is_session_yolo_enabled(session_key))
  31. _persist(persist, enabled, session_key)
  32. (approval.enable_session_yolo if enabled else approval.disable_session_yolo)(session_key)
  33. return enabled
  34. def restore_session_yolo(session_key: str, persisted: bool) -> bool:
  35. """Re-arm a persisted bypass in a fresh process; True when this call turned it on.
  36. Key it on the id approvals are checked under (the stored session id / routing key), never a
  37. transport-local id. Skipped under the frozen process ``--yolo``, which already bypasses everything.
  38. """
  39. if (not session_key or not persisted or approval._YOLO_MODE_FROZEN
  40. or approval.is_session_yolo_enabled(session_key)):
  41. return False
  42. approval.enable_session_yolo(session_key)
  43. return True
  44. def apply_launch_yolo(session_key: str) -> None:
  45. """Seed a gateway-owned session's launch ``--yolo`` policy once per session boundary.
  46. Called every turn of such a route; only the first call (or the first after ``clear_session``) arms it,
  47. so a later ``/yolo`` off sticks instead of lasting one turn. Skipped under the frozen process ``--yolo``.
  48. """
  49. if not session_key or approval._YOLO_MODE_FROZEN:
  50. return
  51. with approval._lock:
  52. if session_key in approval._launch_yolo_applied:
  53. return
  54. approval._launch_yolo_applied.add(session_key)
  55. approval.enable_session_yolo(session_key)
  56. def restore_gateway_yolo(session_key: str, persisted: Optional[bool], *, launch: bool = False) -> None:
  57. """Restore the authoritative routing value, including OFF, before frozen launch seeding.
  58. ``persisted`` None means nobody toggled this route: the ``--yolo`` launch policy (*launch*) is seeded
  59. once per boundary instead, so an untouched entry never reads as a revocation.
  60. """
  61. if not session_key:
  62. return
  63. if persisted is None:
  64. if launch:
  65. apply_launch_yolo(session_key)
  66. return
  67. with approval._lock:
  68. if session_key in approval._launch_yolo_applied:
  69. return # after restoration, the live toggle remains authoritative in this process
  70. approval._launch_yolo_applied.add(session_key)
  71. (approval._session_yolo.add if persisted else approval._session_yolo.discard)(session_key)
  72. def transfer_session_yolo(old_key: str, new_key: str) -> None:
  73. """Move the live bypass when the conversation continues under a new id (compression rotation, /branch).
  74. The new row records it at creation (``with_session_yolo``), so nothing is written here. Every
  75. continuation site calls this, so it also moves the chat's MCP spend total: a rotation must not hand a
  76. chat that spent its limit a fresh budget."""
  77. from tools.mcp_tool_costs import transfer_session
  78. transfer_session(old_key, new_key)
  79. if not old_key or not new_key or old_key == new_key or not approval.is_session_yolo_enabled(old_key):
  80. return
  81. approval.enable_session_yolo(new_key)
  82. approval.disable_session_yolo(old_key)
  83. def with_session_yolo(model_config: Optional[dict], session_key: str) -> Optional[dict]:
  84. """``model_config`` for a session row being created, carrying a live bypass. Rows are created lazily on
  85. the first turn, so this is where a toggle made before the row existed gets recorded."""
  86. if not approval.is_session_yolo_enabled(session_key):
  87. return model_config
  88. return {**(model_config or {}), "yolo_mode": True}