The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): a settled choice closes the CLI picker; a described choice keeps its plain label
Teknium47895f8fe04c
diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.pyindex 499e3776bd9..c1201701aef 100644--- a/hermes_cli/gateway_plugin_commands.py+++ b/hermes_cli/gateway_plugin_commands.py@@ -222,7 +222,8 @@ def call_unbounded(cli, connection, name, command):from hermes_cli.gateway_connection import CallStoppedwake = cli._gateway_command_wait = threading.Event() # set by Ctrl+C (cli_tui_mixin)from agent.memory_provider import spawn_context_thread- spawn_context_thread(_answer_choices, args=(cli, connection, wake), name="hermes-command-choices").start()+ answering: list = [] # the clarify request id the panel is answering, while it is open+ spawn_context_thread(_answer_choices, args=(cli, connection, wake, answering), name="hermes-command-choices").start()try:return connection.call_until("slash.exec", wake, session_id=cli.session_id, command=command)except (CallStopped, KeyboardInterrupt) as exc:@@ -232,23 +233,41 @@ def call_unbounded(cli, connection, name, command):return STOPPEDfinally:cli._gateway_command_wait = None+ if answering: # the command is over: its picker must not keep the input+ cli._withdraw_gateway_modal("clarify")-def _answer_choices(cli, connection, wake):+def _answer_choices(cli, connection, wake, answering):"""While the command runs, answer the ``clarify`` server requests its handler sends to this session(``ctx.ask_choice``, ``gateway/plugin_command_choice.py``) with the CLI's clarify panel. No turnpump reads the session's frames between turns, so they are taken here; every other frame staysqueued, in order, for the turn that owns it."""from hermes_cli.gateway_agent import clarify_reply- events = connection.events- while not wake.wait(_CHOICE_POLL_S):- with events.mutex:- asks = [frame for frame in events.queue if isinstance(frame, dict) and frame.get("method") == "clarify"- and "id" in frame and (frame.get("params") or {}).get("session_id") == cli.session_id]+ events, state = connection.events, connection.state(cli.session_id)++ def withdrawn(payload):+ # ``request.cancel`` for the request the panel is answering (another viewer picked, or the gateway's+ # wait ended): close the panel, as GatewayAgent does for a turn's modal.+ if answering and payload.get("id") == answering[0]:+ cli._withdraw_gateway_modal("clarify")++ state.request_listeners.append(withdrawn)+ try:+ while not wake.wait(_CHOICE_POLL_S):+ with events.mutex:+ asks = [frame for frame in events.queue if isinstance(frame, dict) and frame.get("method") == "clarify"+ and "id" in frame and (frame.get("params") or {}).get("session_id") == cli.session_id]+ for frame in asks:+ events.queue.remove(frame)for frame in asks:- events.queue.remove(frame)- for frame in asks:- connection.reply(frame["id"], clarify_reply(cli._clarify_callback, frame["params"]))+ answering[:] = [frame["id"]]+ try:+ reply = clarify_reply(cli._clarify_callback, frame["params"])+ finally:+ answering.clear()+ connection.reply(frame["id"], reply)+ finally:+ state.request_listeners.remove(withdrawn)def run(cli, name, arg):diff --git a/hermes_cli/plugin_choices.py b/hermes_cli/plugin_choices.pyindex 7e6ca17cc31..ec20b49ddd1 100644--- a/hermes_cli/plugin_choices.py+++ b/hermes_cli/plugin_choices.py@@ -55,17 +55,18 @@ def clarify_asker(callback: Callable[[list], dict]) -> Asker:return ask-def _options(choices: list[Choice]) -> list[tuple[str, str]]:- """``[(value, label shown)]``: a string is both; a dict's description rides on its label."""+def _options(choices: list[Choice]) -> list[tuple[str, str, str]]:+ """``[(value, plain label, label shown)]``: a string is all three; a dict's description rides on the shown+ label only, so a typed plain label still picks it."""options = []for choice in choices:if isinstance(choice, str):- options.append((choice, choice))+ options.append((choice, choice, choice))continuevalue = str(choice["value"])label = str(choice.get("label") or value)description = str(choice.get("description") or "").strip()- options.append((value, f"{label} — {description}" if description else label))+ options.append((value, label, f"{label} — {description}" if description else label))return options@@ -89,7 +90,7 @@ def ask_choice(question: str, choices: list[Choice]) -> Optional[str]:logger.warning("ask_choice needs a sync slash-command handler: an async one would block the ""event loop that delivers the answer; returning None")return None- picked = asker(str(question), [label for _value, label in options])+ picked = asker(str(question), [shown for _value, _label, shown in options])typed = (picked or "").strip().casefold()- return next((value for value, label in options if typed and typed in (label.casefold(), value.casefold())),- None)+ return next((value for value, label, shown in options+ if typed and typed in (shown.casefold(), label.casefold(), value.casefold())), None)diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.pyindex b8f38458c82..0134017579a 100644--- a/tests/gateway/test_cli_plugin_command_in_gateway.py+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py@@ -11,6 +11,7 @@ from contextlib import asynccontextmanager, contextmanagerimport jsonimport osimport queue+import typesfrom http.server import ThreadingHTTPServerfrom pathlib import Pathimport signal@@ -120,6 +121,7 @@ class _Wire:self.thread.start()self.calls = []self.events = queue.Queue() # the session's frames (none reach this wire's ``call``)+ self.listeners = types.SimpleNamespace(request_listeners=[])async def _open():return await websocket(home, desc)@@ -128,6 +130,9 @@ class _Wire:def _run(self, coro):return asyncio.run_coroutine_threadsafe(coro, self.loop).result(60)+ def state(self, session_id):+ return self.listeners+def call(self, method, **params):from hermes_cli.gateway_client import GatewayRPCErrorself.calls.append(method)diff --git a/tests/hermes_cli/test_plugin_ask_choice.py b/tests/hermes_cli/test_plugin_ask_choice.pyindex 8df83fee56f..e7395ccb030 100644--- a/tests/hermes_cli/test_plugin_ask_choice.py+++ b/tests/hermes_cli/test_plugin_ask_choice.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport queueimport threading+import typesfrom pathlib import Pathimport pytest@@ -77,6 +78,11 @@ class _GatewayConnection:self.events: queue.Queue = queue.Queue()self.session_id = session_idself.answers: queue.Queue = queue.Queue()+ self.session = types.SimpleNamespace(request_listeners=[])++ def state(self, session_id):+ assert session_id == self.session_id+ return self.sessiondef call_until(self, method, wake, **params):assert (method, params["command"]) == ("slash.exec", "delegation")@@ -110,3 +116,44 @@ def test_a_gateway_plugin_command_choice_is_answered_while_the_cli_waits(monkeypassert shown and shown[0][0]["choices"] == _LABELS# The session's other frames stay queued, in order, for the turn pump that owns them.assert [f["params"]["type"] for f in list(connection.events.queue)] == ["message.delta"]+++def test_a_settled_choice_closes_the_cli_picker(monkeypatch, capsys):+ """Another viewer answers the command's picker (the gateway's ``request.cancel``): the CLI's panel closes+ instead of keeping the input for an already-settled request."""+ from cli import HermesCLI+ from hermes_cli import gateway_plugin_commands+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = "s1"+ opened, closed = threading.Event(), threading.Event()++ def panel(questions):+ opened.set()+ closed.wait(10) # a withdrawn panel returns nothing+ cli._clarify_callback = panel+ cli._withdraw_gateway_modal = lambda method: closed.set() if method == "clarify" else None+ connection = _GatewayConnection("s1")++ def other_viewer_answers(method, wake, **params):+ connection.events.put({"jsonrpc": "2.0", "id": "srq-1", "method": "clarify", "params": {+ "session_id": "s1", "questions": [{"qid": "q0", "question": "Delegation mode", "choices": _LABELS}]}})+ assert opened.wait(10)+ for listener in list(connection.session.request_listeners):+ listener({"id": "srq-1", "method": "clarify"})+ connection.answers.get(timeout=10) # the panel's late reply, dropped by the gateway+ return {"type": "exec", "output": "MODE=model_map"}+ connection.call_until = other_viewer_answers+ monkeypatch.setattr("hermes_cli.gateway_side.connection_for", lambda _cli: connection)+ result: list = []+ runner = threading.Thread(target=lambda: result.append(gateway_plugin_commands.run(cli, "delegation", "")))+ runner.start()+ runner.join(15)+ assert closed.is_set() and result == [True]+ assert "MODE=model_map" in capsys.readouterr().out+++def test_a_described_choice_still_accepts_its_plain_label():+ from hermes_cli.plugin_choices import ask_choice, bind_asker+ with bind_asker(lambda question, labels: "model routes"):+ assert ask_choice("Delegation mode", [+ {"value": "model_map", "label": "Model routes", "description": "a model per task"}]) == "model_map"