fix(gateway,cli): a classic-CLI clarify batch reaches main's batch panel as one request

Main's HermesCLI answered clarify_callback(questions) with its batch panel: every
question shown at once, one active, revisitable, then {answers: {qid: raw|None},
outcome}. Over the gateway the runner asked one clarify.request card per question,
so the CLI's panel said "1 question" and showed only the first.

- gateway/session_clarify_batch.py: for a classic-CLI local viewer turn
  (session_cli_turn.classic_cli_turn) the runner's clarify callback sends the whole
  batch as the existing `clarify` server→client request (ClarifyRequestParams ->
  ClarifyResult), through the sudo prompt's request/response machinery
  (session_sudo_prompt.ask_viewer_result, now shared by sudo/secret/clarify), and
  waits for the answer, an interrupt, or the clarify timeout both sides read from
  config. Unknown qids are dropped. TUI/Desktop/messaging turns are unchanged.
- ClarifyResult gains an optional `outcome` (submitted|timed_out|cancelled), so main's
  timed_out-with-locked-answers result survives; TS/OpenRPC regenerated.
- CLI: GatewayAgent answers a `clarify` request with main's own batch panel
  (clarify_callback) and replies {answers, outcome}; a list answer is JSON-encoded as
  the contract asks.

LEDGER: CB-017, IPS-133 (W4).
(cherry picked from commit 20e784431fe8876ec92e16728ac14cb9286e7a53)
This commit is contained in:
Teknium
2026-10-12 20:51:52 -07:00
parent 591deb0ae1
commit 4d73ffa0de
9 changed files with 211 additions and 18 deletions

View File

@@ -5118,9 +5118,10 @@ export interface ClarifyQuestion {
choices?: string[] | null
multi_select?: boolean
}
/** ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response without ``answers`` is cancel-all. */
/** ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response without ``answers`` is cancel-all. ``outcome`` (optional): how the viewer's own panel ended, as main's classic CLI reports it (``timed_out`` keeps the answers locked before its deadline). */
export interface ClarifyResult {
answers?: Record<string, string | null> | null
outcome?: 'submitted' | 'timed_out' | 'cancelled' | null
}
export interface SetupChooseRequestParams {
session_id: string

View File

@@ -11362,7 +11362,7 @@
},
"ClarifyResult": {
"additionalProperties": false,
"description": "``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response\nwithout ``answers`` is cancel-all.",
"description": "``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response\nwithout ``answers`` is cancel-all. ``outcome`` (optional): how the viewer's own panel ended, as\nmain's classic CLI reports it (``timed_out`` keeps the answers locked before its deadline).",
"properties": {
"answers": {
"anyOf": [
@@ -11385,6 +11385,23 @@
],
"default": null,
"title": "Answers"
},
"outcome": {
"anyOf": [
{
"enum": [
"submitted",
"timed_out",
"cancelled"
],
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"title": "Outcome"
}
},
"title": "ClarifyResult",

View File

@@ -510,6 +510,11 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# Answer headless at once, as main's _single_query_clarify_callback did in process.
from gateway.session_finite import finite_clarify_reply
return finite_clarify_reply()
from gateway.session_cli_turn import classic_cli_turn
if classic_cli_turn(self):
# Main's classic CLI shows every question at once in its batch panel: one request.
from gateway.session_clarify_batch import ask_clarify_batch
return ask_clarify_batch(self, questions)
answers: dict[str, Any] = {}
reply: dict[str, Any] = {"answers": answers, "outcome": "submitted"}
last = len(questions) - 1

View File

@@ -0,0 +1,38 @@
"""The clarify tool's whole question batch for a classic-CLI viewer's turn, in one request.
Main's HermesCLI answered ``clarify_callback(questions)`` with its batch panel: every question shown
at once, one active, answers revisitable until all are locked, ``{answers: {qid: raw | None},
outcome}``. The messaging path asks one card per question. For a classic-CLI local viewer the owner
sends the batch as the existing ``clarify`` server→client request (``ClarifyRequestParams`` →
``ClarifyResult``) through the same request/response machinery as the sudo prompt, so main's own panel
answers it unchanged, and blocks until it answers, the turn is interrupted, or the clarify timeout
(the same config both sides read) passes.
"""
from __future__ import annotations
_QUESTION_KEYS = ("qid", "question", "choices", "multi_select")
def ask_clarify_batch(turn, questions) -> dict:
from gateway.session_sudo_prompt import ask_viewer_result
from tools.clarify_gateway import get_clarify_timeout
authority, session_id, _generation = turn._approval_owner
live = authority.sessions.get(session_id)
agent = (getattr(turn._ctx, "agent_holder", None) or [None])[0]
interrupted = (lambda: bool(getattr(agent, "_interrupt_requested", False))) if agent is not None else (
lambda: False)
if live is None:
return {"answers": {}, "outcome": "cancelled"}
wire = [{key: entry.get(key) for key in _QUESTION_KEYS if entry.get(key) is not None} for entry in questions]
timeout = get_clarify_timeout()
result = ask_viewer_result(live.event_stream, session_id, "clarify", {"questions": wire},
cancelled=interrupted, timeout=timeout if timeout > 0 else None)
if result is None:
return {"answers": {}, "outcome": "cancelled" if interrupted() else "timed_out"}
answers = result.get("answers")
if not isinstance(answers, dict):
return {"answers": {}, "outcome": "cancelled"}
known = {entry["qid"] for entry in questions}
clean = {qid: (value if isinstance(value, str) else None) for qid, value in answers.items() if qid in known}
outcome = result.get("outcome") if result.get("outcome") in ("submitted", "timed_out", "cancelled") else "submitted"
return {"answers": clean, "outcome": outcome}

View File

@@ -22,12 +22,13 @@ _POLL_S = 0.25
class _Pending:
__slots__ = ("event", "session_id", "value")
__slots__ = ("event", "result", "session_id", "value")
def __init__(self, session_id):
self.event = threading.Event()
self.session_id = session_id
self.value = ""
self.result = None
_lock = threading.Lock()
@@ -48,9 +49,10 @@ def resolve(frame, *, session_ok=lambda session_id: True) -> bool:
if pending is None or not session_ok(pending.session_id):
return False
_open.pop(frame["id"], None)
result = frame.get("result")
value = result.get("value") if isinstance(result, dict) and "error" not in frame else ""
result = frame.get("result") if "error" not in frame else None
value = result.get("value") if isinstance(result, dict) else ""
pending.value = value if isinstance(value, str) else ""
pending.result = result if isinstance(result, dict) else None
pending.event.set()
return True
@@ -64,8 +66,20 @@ def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SU
def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:
"""Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the
session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer."""
pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout)
return pending.value if pending is not None else ""
def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S):
"""The same round trip for a structured answer (``clarify``: ``ClarifyResult``): the viewer's
``result`` dict, or None on interrupt, timeout, an error response or no attached viewer."""
pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout)
return pending.result if pending is not None else None
def _ask(events, session_id, method, params, *, cancelled, timeout):
if not events.fanout.transports():
return ""
return None
request_id = f"srq-{uuid.uuid4().hex[:12]}"
pending = _Pending(session_id)
with _lock:
@@ -79,7 +93,7 @@ def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, t
if cancelled():
reason = "interrupted"
break
if waited >= timeout:
if timeout is not None and waited >= timeout:
break
with _lock:
still_open = _open.pop(request_id, None) is pending
@@ -89,8 +103,8 @@ def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, t
with contextlib.suppress(Exception):
events.publish(session_id, {"id": request_id, "method": method, "reason": reason},
event_type="request.cancel")
return ""
return pending.value
return None
return pending
@contextlib.contextmanager

View File

@@ -10,6 +10,7 @@ Event contract: wave_a.md (frozen). Every frame is a gateway ``event`` with para
"""
from __future__ import annotations
import json
import logging
import queue
import threading
@@ -501,7 +502,6 @@ class GatewayAgent:
self.tool_complete_callback(call_id, name, args, result)
def _todo_from_result(self, result):
import json
try:
data = json.loads(result) if isinstance(result, str) else result
except ValueError:
@@ -584,15 +584,36 @@ class GatewayAgent:
prompt_id=payload.get("prompt_id"), answer=str(answer))
def _answer_request(self, frame):
"""A gateway server→client request (``sudo``): main's own modal answers it on this (agent)
thread, through the callback HermesCLI registered for the turn; the value travels only in the
JSON-RPC response frame."""
"""A gateway server→client request (``sudo``, ``secret``, ``clarify``): main's own modal
answers it on this (agent) thread, through the callback HermesCLI registered for the turn; the
answer travels only in the JSON-RPC response frame."""
method = frame["method"]
try:
value = _SERVER_REQUESTS[frame["method"]](self, frame.get("params") or {})
answer = _SERVER_REQUESTS[method](self, frame.get("params") or {})
except Exception: # health: allow BLE001 -- a broken modal is a skip, never a hung tool
logger.debug("server request %s failed", frame.get("method"), exc_info=True)
value = ""
self.connection.reply(frame["id"], {"value": value if isinstance(value, str) else ""})
logger.debug("server request %s failed", method, exc_info=True)
answer = {"outcome": "cancelled"} if method == "clarify" else ""
if method == "clarify":
self.connection.reply(frame["id"], answer)
else:
self.connection.reply(frame["id"], {"value": answer if isinstance(answer, str) else ""})
def _ask_clarify(self, params):
"""Main's batch clarify panel (``clarify_callback(questions)``) for the whole question set."""
questions = [{"qid": q.get("qid"), "question": q.get("question") or "",
"choices": list(q.get("choices") or []), "multi_select": bool(q.get("multi_select"))}
for q in params.get("questions") or [] if isinstance(q, dict) and q.get("qid")]
if self.clarify_callback is None or not questions:
return {"outcome": "cancelled"}
reply = self.clarify_callback(questions)
if not isinstance(reply, dict):
return {"outcome": "cancelled"}
answers = {qid: (value if isinstance(value, str) or value is None else json.dumps(value))
for qid, value in (reply.get("answers") or {}).items()}
out = {"answers": answers}
if reply.get("outcome") in ("submitted", "timed_out", "cancelled"):
out["outcome"] = reply["outcome"]
return out
def _ask_sudo(self, params):
from tools.terminal_tool import _get_sudo_password_callback
@@ -759,6 +780,7 @@ _SECRET_LOCK = threading.Lock()
_SERVER_REQUESTS = {
"sudo": GatewayAgent._ask_sudo,
"secret": GatewayAgent._ask_secret,
"clarify": GatewayAgent._ask_clarify,
}
_HANDLERS = {

View File

@@ -0,0 +1,73 @@
"""A classic-CLI viewer's clarify batch goes out as ONE ``clarify`` request (main's batch panel shows
every question at once); the messaging path still asks one card per question."""
import threading
import time
from types import SimpleNamespace
from gateway.config import Platform
class _Peer:
def __init__(self):
self.frames = []
def write(self, frame):
self.frames.append(frame)
return True
def close(self):
pass
def _turn():
from gateway.session_events import SessionEvents
events, peer = SessionEvents(), _Peer()
events.fanout.attach(peer)
authority = SimpleNamespace(sessions={'s1': SimpleNamespace(event_stream=events)})
turn = SimpleNamespace(_approval_owner=(authority, 's1', 1), _ctx=SimpleNamespace(
source=SimpleNamespace(platform=Platform.LOCAL), agent_holder=[SimpleNamespace(_interrupt_requested=False)]))
return turn, peer
def _wait_for(predicate, timeout=5.0):
deadline = time.monotonic() + timeout
while not predicate():
assert time.monotonic() < deadline
time.sleep(0.01)
QUESTIONS = [{'qid': 'q0', 'question': 'colour?', 'choices': ['red', 'blue'], 'multi_select': False},
{'qid': 'q1', 'question': 'size?', 'choices': None, 'multi_select': False}]
def test_batch_is_one_request_and_the_panels_answers_return(monkeypatch):
from gateway.session_clarify_batch import ask_clarify_batch
from gateway.session_sudo_prompt import resolve
turn, peer = _turn()
out = {}
worker = threading.Thread(target=lambda: out.update(ask_clarify_batch(turn, QUESTIONS)))
worker.start()
_wait_for(lambda: any(f.get('method') == 'clarify' for f in peer.frames))
requests = [f for f in peer.frames if f.get('method') == 'clarify']
assert len(requests) == 1
params = requests[0]['params']
assert params == {'session_id': 's1', 'questions': [
{'qid': 'q0', 'question': 'colour?', 'choices': ['red', 'blue'], 'multi_select': False},
{'qid': 'q1', 'question': 'size?', 'multi_select': False}]}
from tui_gateway.contracts.registry import SERVER_REQUESTS, validate_params
assert validate_params(SERVER_REQUESTS['clarify'], params)[1] is None
resolve({'jsonrpc': '2.0', 'id': requests[0]['id'],
'result': {'answers': {'q0': 'red', 'q1': None, 'zz': 'x'}, 'outcome': 'submitted'}})
worker.join(5)
assert out == {'answers': {'q0': 'red', 'q1': None}, 'outcome': 'submitted'}
def test_runner_routes_a_classic_cli_turn_to_the_batch(monkeypatch):
from gateway import run_turn_runner, session_cli_turn
import gateway.session_clarify_batch as batch
monkeypatch.setattr(session_cli_turn, 'classic_cli_turn', lambda turn: True)
monkeypatch.setattr(run_turn_runner, '_finite_viewer_turn', lambda: False)
monkeypatch.setattr(batch, 'ask_clarify_batch', lambda turn, qs: {'answers': {'q0': 'blue'}, 'outcome': 'submitted'})
runner = run_turn_runner.TurnRunner.__new__(run_turn_runner.TurnRunner)
runner._ask_clarify_question = lambda *a, **k: (_ for _ in ()).throw(AssertionError('per-card path used'))
assert runner._clarify_callback_sync(QUESTIONS) == {'answers': {'q0': 'blue'}, 'outcome': 'submitted'}

View File

@@ -427,3 +427,22 @@ def test_gateway_secret_request_opens_mains_secret_panel_and_the_gateway_saves(m
assert seen and seen[0].startswith("Enter it")
assert replies == [("srq-sec", {"value": "sekrit"})]
assert local_writes == [] # the gateway saves; this process never writes .env
def test_gateway_clarify_batch_request_opens_mains_batch_panel(make_agent):
"""All questions arrive in one ``clarify`` request; main's batch panel answers the set."""
request = {"jsonrpc": "2.0", "id": "srq-clr", "method": "clarify", "params": {"session_id": SID, "questions": [
{"qid": "q0", "question": "colour?", "choices": ["red", "blue"]},
{"qid": "q1", "question": "size?", "choices": ["s", "l"], "multi_select": True}]}}
shown = []
def panel(questions):
shown.append(questions)
return {"answers": {"q0": "red", "q1": ["s", "l"]}, "outcome": "submitted"}
agent, _ = make_agent([request, frame("message.complete", {"text": "ok", "outcome": "completed"})],
clarify_callback=panel)
replies = []
agent.connection.reply = lambda rid, result: replies.append((rid, result)) or True
agent.run_conversation("ask")
assert [q["qid"] for q in shown[0]] == ["q0", "q1"] and shown[0][1]["multi_select"] is True
assert replies == [("srq-clr", {"answers": {"q0": "red", "q1": '["s", "l"]'}, "outcome": "submitted"})]

View File

@@ -7,6 +7,8 @@ the transport and declared on the shared base) and the ``result`` the client ans
from __future__ import annotations
from typing import Literal
from pydantic import Field
from tools.tour_presets import TourPreset
@@ -47,9 +49,11 @@ class ClarifyRequestParams(ServerRequestParams):
class ClarifyResult(Result):
"""``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response
without ``answers`` is cancel-all."""
without ``answers`` is cancel-all. ``outcome`` (optional): how the viewer's own panel ended, as
main's classic CLI reports it (``timed_out`` keeps the answers locked before its deadline)."""
answers: dict[str, str | None] | None = None
outcome: Literal["submitted", "timed_out", "cancelled"] | None = None
server_request("clarify", params=ClarifyRequestParams, result=ClarifyResult,