slash_confirm.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """Generic slash-command confirmation primitive (gateway-side).
  2. Slash commands with an expensive side effect (currently only ``/reload-mcp``, which invalidates
  3. the provider prompt cache) route through here. Button-UI adapters render Approve Once / Always
  4. Approve / Cancel and call ``resolve()``; text-only adapters get a prompt and the gateway
  5. intercepts ``/approve``, ``/always``, ``/cancel``. State is module-level (like ``tools.approval``)
  6. so adapters can resolve without a ``GatewayRunner`` backreference. The CLI has its own
  7. synchronous variant (``_prompt_slash_confirm`` in ``cli.py``).
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import threading
  12. import time
  13. from typing import Any, Awaitable, Callable, Dict, Optional
  14. logger = logging.getLogger(__name__)
  15. # session_key -> {"confirm_id", "command", "handler", "created_at"}
  16. _pending: dict[str, dict[str, Any]] = {}
  17. _lock = threading.RLock()
  18. # Older pending confirms are discarded when the session's next message arrives (buttons live
  19. # as long as the adapter keeps callback_data).
  20. DEFAULT_TIMEOUT_SECONDS = 300
  21. def register(session_key: str, confirm_id: str, command: str,
  22. handler: Callable[[str], Awaitable[Optional[str]]]) -> None:
  23. """Register a pending confirm, superseding any prior one for the session."""
  24. with _lock:
  25. _pending[session_key] = {"confirm_id": confirm_id, "command": command,
  26. "handler": handler, "created_at": time.time()}
  27. def get_pending(session_key: str) -> Optional[dict[str, Any]]:
  28. """Return a copy of the pending confirm dict for a session, or None."""
  29. with _lock:
  30. entry = _pending.get(session_key)
  31. return dict(entry) if entry else None
  32. def clear(session_key: str) -> None:
  33. """Drop the pending confirm for ``session_key`` without running it."""
  34. with _lock:
  35. _pending.pop(session_key, None)
  36. def _is_stale(entry: dict[str, Any], timeout: float) -> bool:
  37. return time.time() - float(entry.get("created_at", 0) or 0) > timeout
  38. def clear_if_stale(session_key: str, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> bool:
  39. """Drop the pending confirm if older than ``timeout`` seconds; True if dropped."""
  40. with _lock:
  41. entry = _pending.get(session_key)
  42. stale = bool(entry and _is_stale(entry, timeout))
  43. if stale:
  44. _pending.pop(session_key, None)
  45. return stale
  46. async def resolve(session_key: str, confirm_id: str, choice: str,
  47. timeout: float = DEFAULT_TIMEOUT_SECONDS) -> Optional[str]:
  48. """Run the pending handler with ``choice`` ("once" / "always" / "cancel").
  49. Returns the handler's output string, or None if the confirm was stale, already resolved,
  50. or the confirm_id doesn't match (superseded prompt).
  51. """
  52. with _lock:
  53. entry = _pending.get(session_key)
  54. if not entry or entry.get("confirm_id") != confirm_id:
  55. return None
  56. # Pop before running so duplicate callbacks (button double-click) cannot run it twice.
  57. _pending.pop(session_key, None)
  58. if _is_stale(entry, timeout):
  59. return None
  60. handler = entry.get("handler")
  61. command = entry.get("command", "?")
  62. if not handler:
  63. return None
  64. try:
  65. result = await handler(choice)
  66. except Exception as exc:
  67. logger.error("Slash-confirm handler for /%s raised: %s", command, exc, exc_info=True)
  68. return f"❌ Error handling confirmation: {exc}"
  69. return result if isinstance(result, str) else None