session_command_sink.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. """What a messaging command handler would have SENT, captured for a local ``slash.exec``.
  2. The messaging gateway's handlers deliver two things outside their return value: an ack line
  3. (``_send_command_ack``) and a next turn pushed onto the adapter FIFO (``/goal``'s kickoff,
  4. ``_enqueue_goal_turn``). A local session's adapter has no transport and no FIFO reader: its turns
  5. are client-submitted admissions with the client's own durable input id. So while ``slash.exec``
  6. runs a handler for a local session, both are captured here and returned to the client as one
  7. ``send`` directive (``notice`` + ``message``); the client submits it, the gateway never does.
  8. """
  9. from __future__ import annotations
  10. from contextlib import contextmanager
  11. from contextvars import ContextVar
  12. from dataclasses import dataclass, field
  13. _SINK: ContextVar = ContextVar('local_command_sink', default=None)
  14. @dataclass
  15. class CommandSink:
  16. notices: list[str] = field(default_factory=list)
  17. prompt: str | None = None
  18. display: str | None = None
  19. def active_sink() -> CommandSink | None:
  20. return _SINK.get()
  21. @contextmanager
  22. def capture():
  23. sink = CommandSink()
  24. token = _SINK.set(sink)
  25. try:
  26. yield sink
  27. finally:
  28. _SINK.reset(token)