session_clarify_batch.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """The clarify tool's whole question batch for a classic-CLI viewer's turn, in one request.
  2. Main's HermesCLI answered ``clarify_callback(questions)`` with its batch panel: every question shown
  3. at once, one active, answers revisitable until all are locked, ``{answers: {qid: raw | None},
  4. outcome}``. The messaging path asks one card per question. For a classic-CLI local viewer the owner
  5. sends the batch as the existing ``clarify`` server→client request (``ClarifyRequestParams`` →
  6. ``ClarifyResult``) through the same request/response machinery as the sudo prompt, so main's own panel
  7. answers it unchanged, and blocks until it answers, the turn is interrupted, or the clarify timeout
  8. (the same config both sides read) passes.
  9. """
  10. from __future__ import annotations
  11. _QUESTION_KEYS = ("qid", "question", "choices", "multi_select")
  12. def ask_clarify_batch(turn, questions) -> dict:
  13. from gateway.session_server_requests import ask_viewer_result
  14. from tools.clarify_gateway import get_clarify_timeout
  15. authority, session_id, _generation = turn._approval_owner
  16. live = authority.sessions.get(session_id)
  17. agent = (getattr(turn._ctx, "agent_holder", None) or [None])[0]
  18. interrupted = (lambda: bool(getattr(agent, "_interrupt_requested", False))) if agent is not None else (
  19. lambda: False)
  20. if live is None:
  21. return {"answers": {}, "outcome": "cancelled"}
  22. wire = [{key: entry.get(key) for key in _QUESTION_KEYS if entry.get(key) is not None} for entry in questions]
  23. timeout = get_clarify_timeout()
  24. # ``qids``: the viewer's batch panel locks each answer with ``clarify.lock`` (#140400).
  25. result = ask_viewer_result(live.event_stream, session_id, "clarify", {"questions": wire},
  26. cancelled=interrupted, timeout=timeout if timeout > 0 else None,
  27. qids=[entry["qid"] for entry in questions])
  28. if result is None:
  29. return {"answers": {}, "outcome": "cancelled" if interrupted() else "timed_out"}
  30. answers = result.get("answers")
  31. if not isinstance(answers, dict):
  32. return {"answers": {}, "outcome": "cancelled"}
  33. known = {entry["qid"] for entry in questions}
  34. clean = {qid: (value if isinstance(value, str) else None) for qid, value in answers.items() if qid in known}
  35. # ``session_server_requests`` settles a batch with its terminal outcome (an absent outcome on a frame
  36. # that carried answers is ``submitted``; a cancel-all or error is ``cancelled``).
  37. outcome = result.get("outcome") if result.get("outcome") in ("submitted", "timed_out", "cancelled") else "cancelled"
  38. return {"answers": clean, "outcome": outcome}