gateway_side.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """``/bg`` and ``/btw`` on the shared gateway session (``prompt.background`` / ``prompt.btw``).
  2. On main the classic CLI built a second ``AIAgent`` (``/bg``) or made a one-shot auxiliary call
  3. (``/btw``) in its own process. Rewired, the side work runs in the gateway, like Ink's: the verb
  4. replies ``{task_id}`` at once and the answer arrives later on the session's event stream as
  5. ``background.complete`` / ``btw.complete`` ``{task_id, text}`` (``error: <exc>`` on failure,
  6. ``gateway/session_tui_side.py``). The connection's pump hands those frames to the waiter
  7. registered here, so neither the turn pump nor the idle notification tick can drop them.
  8. """
  9. from __future__ import annotations
  10. import queue
  11. SIDE_EVENTS = frozenset({"background.complete", "btw.complete"})
  12. _POLL_SECONDS = 1.0
  13. def connection_for(cli):
  14. """The CLI's gateway connection when its session is open, else None (not rewired). A hung-up
  15. connection is returned (its next call redials); only a final one is None."""
  16. from hermes_cli.gateway_tools_notify import gateway_store
  17. store = gateway_store(cli)
  18. if store is None or not getattr(cli, "_gateway_session_open", False) or store.connection.final:
  19. return None
  20. return store.connection
  21. def start(connection, session_id, verb, text):
  22. """Admit the side task on the owner: ``(task_id, wait)``; ``wait()`` -> the answer (raises on failure)."""
  23. # The epoch of the socket that admitted it: a redial before the waiter exists must still end it.
  24. result, epoch = connection.call_tagged(f"prompt.{verb}", session_id=session_id, text=text)
  25. task_id = (result or {}).get("task_id")
  26. if not task_id:
  27. raise RuntimeError(f"prompt.{verb} returned no task id")
  28. inbox = connection.side_waiter(task_id)
  29. def wait():
  30. try:
  31. while True:
  32. try:
  33. payload = inbox.get(timeout=_POLL_SECONDS)
  34. except queue.Empty:
  35. # The task lived on the socket that admitted it: hung up, or already redialed.
  36. if connection.closed or connection.epoch != epoch:
  37. from hermes_cli.gateway_connection import DISCONNECTED
  38. raise RuntimeError(DISCONNECTED) from None
  39. continue
  40. answer = str((payload or {}).get("text") or "")
  41. if answer.startswith("error: "):
  42. raise RuntimeError(answer[len("error: "):])
  43. return answer
  44. finally:
  45. connection.drop_side_waiter(task_id)
  46. return task_id, wait