The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): plugin slash commands can ask the user to pick an option
Teknium49520132f4a3
diff --git a/cli.py b/cli.pyindex dbb48dad3a7..23c7c5a40e5 100644--- a/cli.py+++ b/cli.py@@ -1290,10 +1290,12 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,if not plugin_handler:returnsession_id = getattr(self, "session_id", None) or ""+ from hermes_cli.plugin_choices import bind_asker, clarify_askertry:- result = resolve_plugin_command_result(invoke_plugin_command(- plugin_handler, user_args, source=None, session_id=session_id, session_key=session_id,- platform="cli"))+ with bind_asker(clarify_asker(self._clarify_callback)): # ctx.ask_choice: the clarify panel+ result = resolve_plugin_command_result(invoke_plugin_command(+ plugin_handler, user_args, source=None, session_id=session_id, session_key=session_id,+ platform="cli"))if result:_cprint(str(result))except Exception as e:diff --git a/gateway/plugin_command_choice.py b/gateway/plugin_command_choice.pynew file mode 100644index 00000000000..cc8711d9d5c--- /dev/null+++ b/gateway/plugin_command_choice.py@@ -0,0 +1,78 @@+"""The gateway's askers for ``PluginContext.ask_choice`` (``hermes_cli/plugin_choices.py``).++Both reuse the clarify tool's own prompt, so every surface renders a plugin command's choice the+way it renders the agent's questions:++* a messaging chat gets ``adapter.send_clarify``: buttons where the adapter has them (Telegram,+ Discord, Slack), the base numbered list elsewhere. A tap resolves it through+ ``resolve_gateway_clarify``; a typed reply reaches the clarify text-intercept even though the+ command still holds the chat (the adapter's clarify bypass), and an undeliverable card falls back+ to the numbered text, as for the clarify tool;+* a local session (classic CLI, Ink TUI, Desktop) gets the ``clarify`` server request on its+ viewers' sockets, answered by their clarify panel.++The handler runs on an executor thread (``_hm_run_plugin_handler``), so blocking here is safe; the+wait follows the clarify timeout.+"""+from __future__ import annotations++import asyncio+import uuid+from contextlib import nullcontext+from typing import Optional++from gateway.config import Platform+++def chat_choices(runner, source, session_key: str):+ """Bind the messaging asker for a command *source* sent, unless the caller bound one already (a+ local viewer's ``slash.exec``) or the source is a local session (it has no chat to post in)."""+ from hermes_cli.plugin_choices import asker_bound, bind_asker+ if asker_bound() or source.platform == Platform.LOCAL:+ return nullcontext()+ loop = asyncio.get_running_loop()+ return bind_asker(lambda question, labels: _ask_chat(runner, source, session_key, loop, question, labels))+++def _ask_chat(runner, source, session_key, loop, question, labels) -> Optional[str]:+ from gateway.run_turn_runner_clarify_delivery import _clarify_send_then_wait, text_fallback_coro+ from tools import clarify_gateway+ adapter = runner._delivery_adapter_for(source)+ if adapter is None:+ return None+ clarify_id = uuid.uuid4().hex[:10]+ send = dict(chat_id=source.chat_id, question=question, choices=labels, clarify_id=clarify_id,+ session_key=session_key, metadata=runner._thread_metadata_for_source(source))+ clarify_gateway.register(clarify_id, session_key, question, labels)++ def fallback():+ coro = text_fallback_coro(adapter, **send)+ return None if coro is None else asyncio.run_coroutine_threadsafe(coro, loop)+ card = asyncio.run_coroutine_threadsafe(adapter.send_clarify(**send), loop)+ response, answered = _clarify_send_then_wait(card, clarify_id=clarify_id, session_key=session_key,+ clarify_mod=clarify_gateway, fallback=fallback)+ if answered:+ return response+ retire = getattr(type(adapter), "retire_clarify_card", None)+ if callable(retire): # a persistent card must stop looking answerable+ from gateway.run_turn_runner import _clarify_expired_notice+ asyncio.run_coroutine_threadsafe(retire(adapter, clarify_id, _clarify_expired_notice()), loop)+ return None+++def viewer_choices(live, session_id: str):+ """Bind the local-session asker: the ``clarify`` server request to *live*'s attached viewers."""+ from hermes_cli.plugin_choices import bind_asker+ return bind_asker(lambda question, labels: _ask_viewers(live, session_id, question, labels))+++def _ask_viewers(live, session_id, question, labels) -> Optional[str]:+ from gateway.session_server_requests import ask_viewer_result+ from tools.clarify_gateway import get_clarify_timeout+ timeout = get_clarify_timeout()+ result = ask_viewer_result(live.event_stream, session_id, "clarify",+ {"questions": [{"qid": "q0", "question": question, "choices": labels,+ "multi_select": False}]},+ timeout=timeout if timeout > 0 else None, qids=["q0"])+ answer = ((result or {}).get("answers") or {}).get("q0")+ return answer if isinstance(answer, str) else Nonediff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.pyindex 19b54696c29..964cd969c0d 100644--- a/gateway/run_inbound_hooks.py+++ b/gateway/run_inbound_hooks.py@@ -284,12 +284,15 @@ class GatewayInboundHooksMixin:user_args = event.get_command_args().strip() if args is None else argsfrom hermes_cli.plugin_command_dispatch import invoke_plugin_commandfrom gateway.plugin_messages import bind_live_source+ from gateway.plugin_command_choice import chat_choicescall = functools.partial(invoke_plugin_command, plugin_handler, user_args, source=source,session_id=_plugin_context.session_id or "", session_key=_plugin_context.session_key or "",platform=source.platform.value)- # ctx.post_message from the handler reaches this chat even before its session is stored.- with self._session_env_scope(_plugin_context), bind_live_source(source):+ # ctx.post_message from the handler reaches this chat even before its session is stored;+ # ctx.ask_choice asks it with the clarify prompt.+ with (self._session_env_scope(_plugin_context), bind_live_source(source),+ chat_choices(self, source, self._session_key_for_source(source))):if inspect.iscoroutinefunction(plugin_handler):result = await call()else:diff --git a/gateway/session_commands.py b/gateway/session_commands.pyindex 2f3487ca781..4ba869222e7 100644--- a/gateway/session_commands.py+++ b/gateway/session_commands.py@@ -465,7 +465,9 @@ async def execute_command(connection, ref, params, *, dispatch=False):or authority._handle(ref).execution_state == 'idle'):await before() # mid-run the busy dispatcher fires it once it accepts the command (``BUSY_ACCEPTED``)if runner_command is not None:- with _profile_runtime_scope(home), _session_workspace(authority.runner, live.source):+ from gateway.plugin_command_choice import viewer_choices+ with (_profile_runtime_scope(home), _session_workspace(authority.runner, live.source),+ viewer_choices(live, ref.session_id)):output = await _run_runner_command(authority.runner, live, name, arg, *runner_command)return {'type': 'exec', 'output': _text(output)}if definition is None:diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 61aa0457283..26747702305 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -1167,21 +1167,7 @@ class GatewayAgent:logger.debug("modal withdraw for %s failed", current[1], exc_info=True)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+ return clarify_reply(self.clarify_callback, params)def _ask_sudo(self, params):from tools.terminal_tool import _get_sudo_password_callback@@ -1413,6 +1399,25 @@ def _moa_handler(kind):return handler+def clarify_reply(callback, params) -> dict:+ """Main's batch clarify panel (``callback(questions)``, ``HermesCLI._clarify_callback``) answering a+ ``clarify`` server request's whole question set: its ``ClarifyResult``."""+ 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 callback is None or not questions:+ return {"outcome": "cancelled"}+ reply = 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++_SECRET_LOCK = threading.Lock()_SERVER_REQUESTS = {"sudo": GatewayAgent._ask_sudo,diff --git a/hermes_cli/gateway_plugin_commands.py b/hermes_cli/gateway_plugin_commands.pyindex 17c0057f85b..499e3776bd9 100644--- a/hermes_cli/gateway_plugin_commands.py+++ b/hermes_cli/gateway_plugin_commands.py@@ -24,6 +24,7 @@ _CATEGORY = "Plugin commands" # tui_gateway/command_discovery.pyGONE = object() # run(): the gateway no longer has the command; the caller dispatches the name againSTOPPED = object() # call_unbounded(): Ctrl+C stopped the wait (the stopped line is printed)_GONE_LINE = " /{}: the gateway no longer has this plugin command; nothing was run."+_CHOICE_POLL_S = 0.1 # how often a running command's clarify requests are looked for_STOPPED_LINE = " /{}: stopped waiting. The command keeps running in the gateway and its reply will not be shown."@@ -220,6 +221,8 @@ def call_unbounded(cli, connection, name, command):from cli import _cprintfrom 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()try:return connection.call_until("slash.exec", wake, session_id=cli.session_id, command=command)except (CallStopped, KeyboardInterrupt) as exc:@@ -231,6 +234,23 @@ def call_unbounded(cli, connection, name, command):cli._gateway_command_wait = None+def _answer_choices(cli, connection, wake):+ """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 turn+ pump reads the session's frames between turns, so they are taken here; every other frame stays+ queued, 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]+ for frame in asks:+ events.queue.remove(frame)+ for frame in asks:+ connection.reply(frame["id"], clarify_reply(cli._clarify_callback, frame["params"]))++def run(cli, name, arg):"""True when the gateway answered ``/name arg`` (the local handler must not run); :data:`GONE`when it no longer has that plugin command and a fresh catalog read agrees (a plugin reload, e.g.diff --git a/hermes_cli/plugin_choices.py b/hermes_cli/plugin_choices.pynew file mode 100644index 00000000000..7e6ca17cc31--- /dev/null+++ b/hermes_cli/plugin_choices.py@@ -0,0 +1,95 @@+"""``PluginContext.ask_choice``: a plugin slash command asks its user to pick one option.++The surface that dispatches the command binds an asker around the handler call (:func:`bind_asker`).+Each asker is that surface's existing clarify prompt, so no surface grows a new kind of card:++* a messaging chat: ``adapter.send_clarify`` (buttons on Telegram, Discord and Slack, the numbered+ list answered by a typed reply elsewhere): ``gateway/plugin_command_choice.py``;+* a local session on the gateway (classic CLI, Ink TUI, Desktop): the ``clarify`` server request to+ its attached viewers (same module);+* the in-process classic CLI and the legacy ``hermes serve`` backend: their own clarify picker.++An asker takes ``(question, labels)`` and returns the label the user picked, or None; values are+mapped back here, so a surface never sees them. With no asker bound (a hook, a cron job, a handler+on an event loop, where blocking would stall the loop that must deliver the answer) the call+returns None and the handler falls back to its own text usage.+"""+from __future__ import annotations++import asyncio+import logging+from contextlib import contextmanager+from contextvars import ContextVar+from typing import Callable, Iterator, Optional++logger = logging.getLogger(__name__)++Asker = Callable[[str, list], Optional[str]]+Choice = str | dict++_ASKER: ContextVar[Optional[Asker]] = ContextVar("plugin_choice_asker", default=None)+++@contextmanager+def bind_asker(asker: Asker) -> Iterator[None]:+ """Make *asker* answer ``ask_choice`` for the calls in this context (and the executor thread a+ sync handler runs on: callers carry the context over)."""+ token = _ASKER.set(asker)+ try:+ yield+ finally:+ _ASKER.reset(token)+++def asker_bound() -> bool:+ return _ASKER.get() is not None+++def clarify_asker(callback: Callable[[list], dict]) -> Asker:+ """An asker over a clarify-tool callback (``questions -> {answers: {qid: raw}, outcome}``): the+ classic CLI's clarify panel, the legacy backend's ``clarify`` server request."""+ def ask(question: str, labels: list) -> Optional[str]:+ reply = callback([{"qid": "q0", "question": question, "choices": labels, "multi_select": False}])+ answer = ((reply or {}).get("answers") or {}).get("q0")+ return answer if isinstance(answer, str) else None+ 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."""+ options = []+ for choice in choices:+ if isinstance(choice, str):+ options.append((choice, choice))+ continue+ value = 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))+ return options+++def _running_on_loop() -> bool:+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return False+ return True+++def ask_choice(question: str, choices: list[Choice]) -> Optional[str]:+ """Ask the user who ran the current slash command to pick one of *choices*; the picked choice's+ value, or None when nothing can ask here, the user cancels or types something else, or the+ clarify timeout passes. A typed value or label (any case) also counts as that choice."""+ asker = _ASKER.get()+ options = _options(choices)+ if asker is None or not options:+ return None+ if _running_on_loop():+ 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])+ typed = (picked or "").strip().casefold()+ return next((value for value, label in options if typed and typed in (label.casefold(), value.casefold())),+ None)diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex fa4138b32ba..667eda53d8a 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -616,6 +616,12 @@ class PluginContext:from hermes_cli.plugin_messages import apostreturn await apost(self, text)+ def ask_choice(self, question: str, choices: list) -> Optional[str]:+ """From a sync slash-command handler: ask its user to pick one of *choices* (``str`` or+ ``{value, label?, description?}``); the value, or None if unanswerable: ``plugin_choices.py``."""+ from hermes_cli.plugin_choices import ask_choice+ return ask_choice(question, choices)+def _gateway_injection_allowed(self) -> bool:"""Return whether this plugin may trigger gateway session turns (read from the plugin'sown profile config, never the calling thread's ambient home)."""diff --git a/tests/gateway/test_cli_plugin_command_in_gateway.py b/tests/gateway/test_cli_plugin_command_in_gateway.pyindex 260349ec7c1..b8f38458c82 100644--- a/tests/gateway/test_cli_plugin_command_in_gateway.py+++ b/tests/gateway/test_cli_plugin_command_in_gateway.py@@ -10,6 +10,7 @@ import asynciofrom contextlib import asynccontextmanager, contextmanagerimport jsonimport os+import queuefrom http.server import ThreadingHTTPServerfrom pathlib import Pathimport signal@@ -118,6 +119,7 @@ class _Wire:self.thread = threading.Thread(target=self.loop.run_forever, daemon=True)self.thread.start()self.calls = []+ self.events = queue.Queue() # the session's frames (none reach this wire's ``call``)async def _open():return await websocket(home, desc)diff --git a/tests/gateway/test_plugin_command_choice.py b/tests/gateway/test_plugin_command_choice.pynew file mode 100644index 00000000000..95015eb3c66--- /dev/null+++ b/tests/gateway/test_plugin_command_choice.py@@ -0,0 +1,153 @@+"""A plugin slash command asks its user to pick an option (``PluginContext.ask_choice``) and gets the+picked value back, on the surfaces the gateway serves:++* a messaging chat gets the clarify prompt (here the base adapter's numbered text) and the typed+ number answers it while the command is still running;+* a local session (classic CLI, Ink TUI, Desktop over ``hermes-gateway-v1``) gets the ``clarify``+ server request on its own socket, and the viewer's response frame settles it although that+ socket's ``slash.exec`` is still waiting for the handler.+"""+import asyncio+import json+from datetime import datetime+from pathlib import Path+import signal+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import BasePlatformAdapter, SendResult+from gateway.platforms.event import MessageEvent, MessageType+from gateway.session import SessionEntry, SessionSource, build_session_key+from tests.gateway.fixtures.local_recovery_probe import child_env, daemon, rpc, websocket+from tests.waiting import async_wait_until++_CHOICES = [{"value": "default", "label": "Default", "description": "delegation.model / parent model"},+ {"value": "model_map", "label": "Model routes"}, "profile_routes"]+_LABELS = ["Default — delegation.model / parent model", "Model routes", "profile_routes"]+++class _TextAdapter(BasePlatformAdapter):+ """A chat with no native card: the base ``send_clarify`` numbered list is what the user sees."""++ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token="t"), Platform.TELEGRAM)+ self.sent = []++ async def connect(self):+ return True++ async def disconnect(self):+ pass++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent.append(content)+ return SendResult(success=True, message_id=str(len(self.sent)))++ async def get_chat_info(self, chat_id):+ return {"id": chat_id, "type": "private"}+++def _source():+ return SessionSource(platform=Platform.TELEGRAM, chat_id="c1", chat_type="dm", user_id="u1")+++def _runner(adapter):+ from gateway.run import GatewayRunner+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="t")})+ runner.adapters = {Platform.TELEGRAM: adapter}+ runner._voice_mode = {}+ runner.hooks = SimpleNamespace(emit=AsyncMock(), emit_collect=AsyncMock(return_value=[]), loaded_hooks=False)+ entry = SessionEntry(session_key=build_session_key(_source()), session_id="sess-1", created_at=datetime.now(),+ updated_at=datetime.now(), platform=Platform.TELEGRAM, chat_type="dm")+ runner.session_store = MagicMock()+ runner.session_store.get_or_create_session.return_value = entry+ runner.session_store.load_transcript.return_value = []+ runner.session_store.has_any_sessions.return_value = True+ runner._running_agents, runner._pending_messages, runner._pending_approvals = {}, {}, {}+ runner._session_db = None+ runner._is_user_authorized = lambda _source: True+ runner._set_session_env = lambda _context: None+ runner._emit_gateway_run_progress = AsyncMock()+ return runner+++async def test_a_chat_answers_the_plugin_command_choice_with_a_typed_number(monkeypatch):+ from hermes_cli import plugins as plugins_mod+ from hermes_cli.plugin_choices import ask_choice+ from tools import clarify_gateway++ adapter = _TextAdapter()+ runner = _runner(adapter)+ adapter.set_message_handler(runner._handle_message)+ monkeypatch.setattr(plugins_mod, "get_plugin_command_handler", lambda name: (+ (lambda arg: f"MODE={ask_choice('Delegation mode', _CHOICES)}") if name == "delegation" else None))+ monkeypatch.setattr(clarify_gateway, "get_clarify_timeout", lambda: 20)++ def event(text):+ return MessageEvent(text=text, message_type=MessageType.TEXT, source=_source(), message_id=text)++ await adapter.handle_message(event("/delegation"))+ await async_wait_until(lambda: any("Model routes" in s for s in adapter.sent), timeout=10)+ prompt = next(s for s in adapter.sent if "Model routes" in s)+ assert "Delegation mode" in prompt and "delegation.model / parent model" in prompt, prompt+ await adapter.handle_message(event("2")) # the command still runs: this must answer it, not queue+ await async_wait_until(lambda: any(s.startswith("MODE=") for s in adapter.sent), timeout=10)+ assert [s for s in adapter.sent if s.startswith("MODE=")] == ["MODE=model_map"], adapter.sent+++_PLUGIN = f'''+def register(ctx):+ choices = {json.dumps(_CHOICES)}+ ctx.register_command("delegation", lambda arg: "MODE=" + str(ctx.ask_choice("Delegation mode", choices)),+ description="Pick the delegation mode")+'''++[email protected]("linux")+def test_a_local_viewer_answers_the_choice_while_its_slash_exec_waits(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / "state", tmp_path / "user"+ home.mkdir(mode=0o700)+ user.mkdir()+ plugin = home / "plugins" / "pick"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: pick\nversion: '1.0'\n")+ (plugin / "__init__.py").write_text(_PLUGIN)+ (home / "config.yaml").write_text(json.dumps({+ "gateway": {"multiplex_profiles": False}, "clarify": {"timeout": 15},+ "model": {"provider": "custom", "default": "m", "base_url": "http://127.0.0.1:9/v1"},+ "platform_toolsets": {"cli": []}, "plugins": {"enabled": ["pick"]}}))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY="loopback-only", PYTHONUNBUFFERED="1", PYTHONDONTWRITEBYTECODE="1")++ async def viewer(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, "session.create", request_id="pick", source="cli", toolsets=[],+ cwd=str(tmp_path))+ sid = created["result"]["session_id"]+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": "exec", "method": "slash.exec",+ "params": {"session_id": sid, "command": "delegation"}}))+ asked = None+ async with asyncio.timeout(40):+ while True:+ frame = json.loads(await ws.recv())+ if frame.get("method") == "clarify": # answered as Desktop's and Ink's panels do+ asked = frame["params"]["questions"]+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": "lock", "method": "clarify.lock", "params": {+ "request_id": frame["id"], "question_id": asked[0]["qid"],+ "answer": asked[0]["choices"][2]}}))+ elif frame.get("id") == "exec":+ return asked, frame++ with daemon(root, home, env, barrier=False) as (proc, desc):+ asked, reply = asyncio.run(viewer(desc))+ proc.send_signal(signal.SIGINT)+ proc.wait(timeout=20)+ assert asked and asked[0]["question"] == "Delegation mode" and asked[0]["choices"] == _LABELS, asked+ assert reply["result"]["output"] == "MODE=profile_routes", replydiff --git a/tests/hermes_cli/test_plugin_ask_choice.py b/tests/hermes_cli/test_plugin_ask_choice.pynew file mode 100644index 00000000000..8df83fee56f--- /dev/null+++ b/tests/hermes_cli/test_plugin_ask_choice.py@@ -0,0 +1,112 @@+"""A plugin slash command asks the classic CLI's user to pick an option (``ctx.ask_choice``) with the+CLI's own clarify panel, and gets the picked choice's value back:++* in process (no gateway), the handler's ``ask_choice`` opens the panel directly;+* on the gateway, the handler runs there and asks with a ``clarify`` server request; the CLI answers+ it with the same panel while it still waits for its ``slash.exec`` reply.+"""+from __future__ import annotations++import json+import queue+import threading+from pathlib import Path++import pytest++import hermes_cli.plugins as plugins_mod+from hermes_cli.plugins import PluginManager++_CHOICES = [{"value": "default", "label": "Default", "description": "delegation.model / parent model"},+ {"value": "model_map", "label": "Model routes"}, "profile_routes"]+_LABELS = ["Default — delegation.model / parent model", "Model routes", "profile_routes"]+++def _panel(pick):+ """The CLI's clarify panel answering with the label at index *pick*; records what it showed."""+ shown = []++ def clarify_callback(questions):+ shown.append(questions)+ return {"answers": {questions[0]["qid"]: questions[0]["choices"][pick]}, "outcome": "submitted"}+ return clarify_callback, shown+++def plugin_home(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ plugin = home / "plugins" / "pick"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text(json.dumps({"name": "pick", "version": "0.1.0"}))+ (plugin / "__init__.py").write_text(+ "def register(ctx):\n"+ f" choices = {_CHOICES!r}\n"+ " ctx.register_command('delegation', lambda arg: 'MODE=%s' % ctx.ask_choice('Delegation mode', choices))\n")+ (home / "config.yaml").write_text(json.dumps({"plugins": {"enabled": ["pick"]}}))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: tmp_path / "empty-bundled")+ monkeypatch.setattr(PluginManager, "_scan_entry_points", lambda self: [])+ plugins_mod._reset_plugin_managers_for_tests()+ plugins_mod.discover_plugins()+ yield home+ plugins_mod._reset_plugin_managers_for_tests()+++def test_an_in_process_plugin_command_picks_with_the_cli_clarify_panel(plugin_home, monkeypatch, capsys):+ from cli import HermesCLI+ from hermes_cli.plugin_command_dispatch import invoke_plugin_command+ monkeypatch.setattr("hermes_cli.gateway_side.connection_for", lambda _cli: None)+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = "s1"+ cli._clarify_callback, shown = _panel(1)+ cli._run_plugin_slash_command("/delegation", "")+ assert "MODE=model_map" in capsys.readouterr().out+ assert shown == [[{"qid": "q0", "question": "Delegation mode", "choices": _LABELS, "multi_select": False}]]+ # Called where no surface binds an asker (a hook, a cron job): None, and the handler says so itself.+ assert invoke_plugin_command(plugins_mod.get_plugin_command_handler("delegation"), "") == "MODE=None"+++class _GatewayConnection:+ """The CLI's gateway connection while the gateway runs the command: its handler asks with a+ ``clarify`` server request on the session's event stream, and its reply waits for the answer."""+ closed = final = False+ epoch = 1++ def __init__(self, session_id):+ self.events: queue.Queue = queue.Queue()+ self.session_id = session_id+ self.answers: queue.Queue = queue.Queue()++ def call_until(self, method, wake, **params):+ assert (method, params["command"]) == ("slash.exec", "delegation")+ self.events.put({"jsonrpc": "2.0", "method": "event", "params": {+ "session_id": self.session_id, "type": "message.delta", "payload": {"text": "later turn"}}})+ self.events.put({"jsonrpc": "2.0", "id": "srq-1", "method": "clarify", "params": {+ "session_id": self.session_id,+ "questions": [{"qid": "q0", "question": "Delegation mode", "choices": _LABELS, "multi_select": False}]}})+ request_id, result = self.answers.get(timeout=10)+ assert request_id == "srq-1"+ return {"type": "exec", "output": "MODE=" + result["answers"]["q0"]}++ def reply(self, request_id, result):+ self.answers.put((request_id, result))+++def test_a_gateway_plugin_command_choice_is_answered_while_the_cli_waits(monkeypatch, capsys):+ from cli import HermesCLI+ from hermes_cli import gateway_plugin_commands+ cli = HermesCLI.__new__(HermesCLI)+ cli.session_id = "s1"+ cli._clarify_callback, shown = _panel(2)+ connection = _GatewayConnection("s1")+ 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 result == [True]+ assert "MODE=profile_routes" in capsys.readouterr().out+ assert 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"]diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 0d3fee75b93..a96976eaa17 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -497,7 +497,7 @@ def _plugin_command_handler(name: str):return None-def _run_plugin_command(handler, arg: str, session=None) -> str:+def _run_plugin_command(handler, arg: str, session=None, sid: str = "") -> str:"""Run a plugin slash-command handler under the session's ``HERMES_SESSION_*`` binding.Plugin handlers read ``get_session_env()`` for the chat/session they serve; these RPCs run on@@ -510,8 +510,11 @@ def _run_plugin_command(handler, arg: str, session=None) -> str:tokens = _set_session_context(key, cwd=str(session.get("cwd") or "")) if session else []context = {"source": None, "session_key": key, "platform": _session_source(session),"session_id": getattr(session.get("agent"), "session_id", None) or key if session else ""}+ # ctx.ask_choice: the ``clarify`` server request this backend's clarify tool sends.+ choices = _tools_mod("hermes_cli.plugin_choices")try:- return str(plugins.resolve_plugin_command_result(invoke(handler, arg, **context)) or "")+ with choices.bind_asker(choices.clarify_asker(lambda questions: _clarify_block(sid, questions))):+ return str(plugins.resolve_plugin_command_result(invoke(handler, arg, **context)) or "")finally:_clear_session_context(tokens)@@ -589,7 +592,8 @@ def _is_registry_command(base: str) -> bool:def _dispatch_plugin(rid, params, session, name, arg):if handler := _plugin_command_handler(name):with contextlib.suppress(Exception):- return _ok(rid, {"type": "plugin", "output": _run_plugin_command(handler, arg, session)})+ return _ok(rid, {"type": "plugin", "output": _run_plugin_command(+ handler, arg, session, params.get("session_id", ""))})return None@@ -1059,7 +1063,8 @@ def _(rid, params: dict) -> dict:return dispatchedif plugin_handler := _plugin_command_handler(base) if base else None:try:- return _ok(rid, {"output": _run_plugin_command(plugin_handler, arg, session) or "(no output)"})+ return _ok(rid, {"output": _run_plugin_command(plugin_handler, arg, session, params.get("session_id", ""))+ or "(no output)"})except Exception as e:return _ok(rid, {"output": f"Plugin command error: {e}"})worker = session.get("slash_worker")diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 310be695976..7d7cb5a0ff1 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -104,6 +104,15 @@ _WS_CONCURRENT_READ_METHODS = frozenset({"session.context_breakdown"})_WS_CONCURRENT_READ_LIMIT = 2# Reads admitted beyond the running ones; one more parks the reader (as the serial lane did)._WS_WAITING_READ_LIMIT = 8+# A viewer's answer to an open server→client request (its response frame, a batch clarify's+# ``clarify.lock``) settles in memory and never queues: the serial lane may be running the very handler+# that waits for it (a plugin slash command's ``ctx.ask_choice`` under ``slash.exec``).+_WS_ANSWER_METHODS = frozenset({"clarify.lock"})+++def _answers_open_request(req: Any) -> bool:+ from tui_gateway.server_requests import is_response_frame+ return isinstance(req, dict) and (req.get("method") in _WS_ANSWER_METHODS or is_response_frame(req))# Per-token streaming frames are coalesced: buffered and flushed as a batch on a short timer instead# of waking the loop once per token (each wakeup competes with the agent turn for the GIL). Keep this@@ -490,6 +499,9 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:await _dispatch_one(req)async def _queue_request(req: Any) -> None:+ if _answers_open_request(req):+ await _dispatch_one(req)+ returnif isinstance(req, dict) and req.get("method") in _WS_CONCURRENT_READ_METHODS:# A read past the waiting cap parks the reader, as the serial lane did; released# when its task ends (a read cancelled before it ran releases it too).diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 484ec9b9c18..16170694ef2 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -1799,6 +1799,37 @@ def _handle_todo(raw_args: str) -> str:return todo.read_text() if todo.exists() else "No TODO.md here."```+### Ask the user to pick an option++A sync slash-command handler can ask the user who ran it to pick one option with `ctx.ask_choice(question, choices)`. It blocks until the user answers and returns the picked choice's `value`, or `None`. Each surface shows it the way it shows the agent's `clarify` questions:++| Surface | What the user sees |+|---|---|+| Telegram, Discord, Slack | A card with one button per choice (plus "Other") |+| Other messaging platforms | A numbered list; the user replies with the number or the label |+| Classic CLI, Ink TUI, Desktop | The clarify picker |++A choice is a string (the label and the value) or a dict `{"value", "label", "description"}`; the description is shown after the label. A typed value or label, in any case, also picks that choice. `ask_choice` returns `None` when the user cancels, types something that is not a choice, or lets the clarify timeout (`agent.clarify_timeout`) pass. It also returns `None` when nothing can ask: a hook, a cron job, an async handler (blocking would stall the event loop that delivers the answer). The handler then falls back to its text usage:++```python+_MODES = [+ {"value": "default", "label": "Default", "description": "delegation.model / parent model"},+ {"value": "model_map", "label": "Model routes", "description": "per-task model map"},+ {"value": "profile_routes", "label": "Profiles", "description": "delegate to other profiles"},+]++def register(ctx):+ def delegation(raw_args: str) -> str:+ mode = raw_args.strip() or ctx.ask_choice("Delegation mode", _MODES)+ if mode not in {m["value"] for m in _MODES}:+ return "Usage: /delegation default|model_map|profile_routes"+ ctx.set_config("mode", mode)+ return f"Delegation mode: {mode}"++ ctx.register_command("delegation", delegation, description="Switch the delegation mode",+ args_hint="[mode]")+```+### Dispatch tools from slash commandsSlash command handlers that need to orchestrate tools (spawn a subagent via `delegate_task`, call `file_edit`, etc.) should use `ctx.dispatch_tool()` instead of reaching into framework internals. The parent-agent context (workspace hints, spinner, model inheritance) is wired up automatically.