plugin_choices.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """``PluginContext.ask_choice``: a plugin slash command asks its user to pick one option.
  2. The surface that dispatches the command binds an asker around the handler call (:func:`bind_asker`).
  3. Each asker is that surface's existing clarify prompt, so no surface grows a new kind of card:
  4. * a messaging chat: ``adapter.send_clarify`` (buttons on Telegram, Discord and Slack, the numbered
  5. list answered by a typed reply elsewhere): ``gateway/plugin_command_choice.py``;
  6. * a local session on the gateway (classic CLI, Ink TUI, Desktop): the ``clarify`` server request to
  7. its attached viewers (same module);
  8. * the in-process classic CLI and the legacy ``hermes serve`` backend: their own clarify picker.
  9. An asker takes ``(question, labels)`` and returns the label the user picked, or None; values are
  10. mapped back here, so a surface never sees them. With no asker bound (a hook, a cron job, a handler
  11. on an event loop, where blocking would stall the loop that must deliver the answer) the call
  12. returns None and the handler falls back to its own text usage.
  13. """
  14. from __future__ import annotations
  15. import asyncio
  16. import logging
  17. from contextlib import contextmanager
  18. from contextvars import ContextVar
  19. from typing import Callable, Iterator, Optional
  20. logger = logging.getLogger(__name__)
  21. Asker = Callable[[str, list], Optional[str]]
  22. Choice = str | dict
  23. _ASKER: ContextVar[Optional[Asker]] = ContextVar("plugin_choice_asker", default=None)
  24. @contextmanager
  25. def bind_asker(asker: Asker) -> Iterator[None]:
  26. """Make *asker* answer ``ask_choice`` for the calls in this context (and the executor thread a
  27. sync handler runs on: callers carry the context over)."""
  28. token = _ASKER.set(asker)
  29. try:
  30. yield
  31. finally:
  32. _ASKER.reset(token)
  33. def asker_bound() -> bool:
  34. return _ASKER.get() is not None
  35. def clarify_asker(callback: Callable[[list], dict]) -> Asker:
  36. """An asker over a clarify-tool callback (``questions -> {answers: {qid: raw}, outcome}``): the
  37. classic CLI's clarify panel, the legacy backend's ``clarify`` server request."""
  38. def ask(question: str, labels: list) -> Optional[str]:
  39. reply = callback([{"qid": "q0", "question": question, "choices": labels, "multi_select": False}])
  40. answer = ((reply or {}).get("answers") or {}).get("q0")
  41. return answer if isinstance(answer, str) else None
  42. return ask
  43. def _options(choices: list[Choice]) -> list[tuple[str, str, str]]:
  44. """``[(value, plain label, label shown)]``: a string is all three; a dict's description rides on the shown
  45. label only, so a typed plain label still picks it."""
  46. options = []
  47. for choice in choices:
  48. if isinstance(choice, str):
  49. options.append((choice, choice, choice))
  50. continue
  51. value = str(choice["value"])
  52. label = str(choice.get("label") or value)
  53. description = str(choice.get("description") or "").strip()
  54. options.append((value, label, f"{label} — {description}" if description else label))
  55. return options
  56. def _running_on_loop() -> bool:
  57. try:
  58. asyncio.get_running_loop()
  59. except RuntimeError:
  60. return False
  61. return True
  62. def ask_choice(question: str, choices: list[Choice]) -> Optional[str]:
  63. """Ask the user who ran the current slash command to pick one of *choices*; the picked choice's
  64. value, or None when nothing can ask here, the user cancels or types something else, or the
  65. clarify timeout passes. A typed value or label (any case) also counts as that choice."""
  66. asker = _ASKER.get()
  67. options = _options(choices)
  68. if asker is None or not options:
  69. return None
  70. if _running_on_loop():
  71. logger.warning("ask_choice needs a sync slash-command handler: an async one would block the "
  72. "event loop that delivers the answer; returning None")
  73. return None
  74. picked = asker(str(question), [shown for _value, _label, shown in options])
  75. typed = (picked or "").strip().casefold()
  76. return next((value for value, label, shown in options
  77. if typed and typed in (shown.casefold(), label.casefold(), value.casefold())), None)