The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(clarify): accept a questions batch in the clarify tool core
ethernetbd8b658a6334
diff --git a/tests/tools/test_clarify_tool.py b/tests/tools/test_clarify_tool.pyindex de721981dfd..7c40b639022 100644--- a/tests/tools/test_clarify_tool.py+++ b/tests/tools/test_clarify_tool.py@@ -360,3 +360,291 @@ class TestRegistryMultiSelectPassThrough:))assert seen["multi"] is Falseassert result["user_response"] == "a"+++class TestClarifyBatchValidation:+ """Validation of the `questions` batch parameter (issue #18450)."""++ def test_batch_takes_precedence_over_question(self):+ """When both are present, `questions` wins and `question` is ignored."""+ seen = {}++ def cb(question, choices, multi_select=False, questions=None):+ seen["questions"] = questions+ return {"answers": {"q0": "blue"}}++ result = json.loads(clarify_tool(+ "ignored single question",+ questions=[{"question": "What color?"}],+ callback=cb,+ ))+ assert "responses" in result+ assert len(result["responses"]) == 1+ assert result["responses"][0]["question"] == "What color?"+ assert seen["questions"][0]["question"] == "What color?"++ def test_batch_rejects_more_than_five(self):+ result = json.loads(clarify_tool(+ "",+ questions=[{"question": f"Q{i}?"} for i in range(6)],+ callback=lambda *a, **k: "",+ ))+ assert "error" in result++ def test_batch_rejects_blank_question_text(self):+ result = json.loads(clarify_tool(+ "",+ questions=[{"question": "Real?"}, {"question": " "}],+ callback=lambda *a, **k: "",+ ))+ assert "error" in result++ def test_batch_rejects_non_list(self):+ result = json.loads(clarify_tool(+ "", questions={"question": "Q?"}, callback=lambda *a, **k: "",+ ))+ assert "error" in result++ def test_batch_empty_list_falls_back_to_single_question(self):+ """An empty questions array degrades to the single-question path."""+ def cb(question, choices):+ assert question == "Single?"+ return "yes"++ result = json.loads(clarify_tool("Single?", questions=[], callback=cb))+ assert result["user_response"] == "yes"+ assert "responses" not in result++ def test_batch_choices_flattened_capped_and_labelled_per_question(self):+ """Each question gets the full choice pipeline: flatten, cap, label."""+ seen = {}++ def cb(question, choices, multi_select=False, questions=None):+ seen["questions"] = questions+ return {"answers": {"q0": "a", "q1": "Loose layout"}}++ clarify_tool(+ "",+ questions=[+ {"question": "Pick letter", "choices": ["a", "b", "c", "d", "e", "f"]},+ {"question": "Pick layout", "choices": [+ {"description": "Loose layout"}, "Tight",+ ]},+ ],+ callback=cb,+ )+ q0, q1 = seen["questions"]+ assert len(q0["choices"]) == MAX_CHOICES+ assert q0["choices"][0] == "a (Recommended)"+ assert q1["choices"] == ["Loose layout (Recommended)", "Tight"]++ def test_batch_internal_ids_are_stable_and_model_id_echoed(self):+ """Wire ids are q0..qN. A model-supplied id only shows in results."""+ seen = {}++ def cb(question, choices, multi_select=False, questions=None):+ seen["questions"] = questions+ return {"answers": {"q0": "A", "q1": "B"}}++ result = json.loads(clarify_tool(+ "",+ questions=[+ {"id": "approach", "question": "Which approach?"},+ {"question": "Timeline?"},+ ],+ callback=cb,+ ))+ assert [q["qid"] for q in seen["questions"]] == ["q0", "q1"]+ assert result["responses"][0]["id"] == "approach"+ assert "id" not in result["responses"][1]++ def test_batch_multi_select_needs_choices(self):+ """multi_select is only honored when the question has choices."""+ seen = {}++ def cb(question, choices, multi_select=False, questions=None):+ seen["questions"] = questions+ return {"answers": {"q0": "free text"}}++ clarify_tool(+ "",+ questions=[{"question": "Thoughts?", "multi_select": True}],+ callback=cb,+ )+ assert seen["questions"][0]["multi_select"] is False+++class TestClarifyBatchDispatch:+ """Batch-capable callbacks get the list once. Legacy callbacks loop."""++ def test_batch_callback_receives_list_once(self):+ calls = []++ def cb(question, choices, multi_select=False, questions=None):+ calls.append(questions)+ return {"answers": {"q0": "x", "q1": "y"}}++ result = json.loads(clarify_tool(+ "",+ questions=[{"question": "One?"}, {"question": "Two?"}],+ callback=cb,+ ))+ assert len(calls) == 1+ assert [r["user_response"] for r in result["responses"]] == ["x", "y"]++ def test_batch_callback_json_string_response(self):+ """A _block-style bridge returns the answers as a JSON string."""+ def cb(question, choices, multi_select=False, questions=None):+ return json.dumps({"answers": {"q0": "picked"}})++ result = json.loads(clarify_tool(+ "", questions=[{"question": "One?"}], callback=cb,+ ))+ assert result["responses"][0]["user_response"] == "picked"++ def test_batch_recommended_label_stripped_per_question(self):+ def cb(question, choices, multi_select=False, questions=None):+ return {"answers": {"q0": questions[0]["choices"][0]}}++ result = json.loads(clarify_tool(+ "",+ questions=[{"question": "Pick", "choices": ["Rebase", "Merge"]}],+ callback=cb,+ ))+ assert result["responses"][0]["user_response"] == "Rebase"+ assert result["responses"][0]["choices_offered"] == ["Rebase", "Merge"]++ def test_batch_multi_select_answer_parsed_to_list(self):+ def cb(question, choices, multi_select=False, questions=None):+ return {"answers": {"q0": '["red", "blue"]'}}++ result = json.loads(clarify_tool(+ "",+ questions=[{+ "question": "Colors?",+ "choices": ["red", "blue", "green"],+ "multi_select": True,+ }],+ callback=cb,+ ))+ assert result["responses"][0]["user_response"] == ["red", "blue"]++ def test_batch_timed_out_flag_passthrough_with_partials(self):+ """Timeout keeps the locked answers and sets the top-level flag."""+ def cb(question, choices, multi_select=False, questions=None):+ return {"answers": {"q0": "kept"}, "timed_out": True}++ result = json.loads(clarify_tool(+ "",+ questions=[{"question": "One?"}, {"question": "Two?"}],+ callback=cb,+ ))+ assert result["timed_out"] is True+ assert result["responses"][0]["user_response"] == "kept"+ assert result["responses"][1]["user_response"] == ""++ def test_batch_empty_response_is_skip_not_timeout(self):+ """A cancel-all resolves every answer empty with no timed_out flag."""+ def cb(question, choices, multi_select=False, questions=None):+ return ""++ result = json.loads(clarify_tool(+ "", questions=[{"question": "One?"}], callback=cb,+ ))+ assert result["responses"][0]["user_response"] == ""+ assert "timed_out" not in result++ def test_legacy_callback_gets_sequential_calls_in_order(self):+ """A callback without `questions` support is looped per question."""+ calls = []++ def legacy_cb(question, choices, multi_select=False):+ calls.append((question, tuple(choices or []) or None, multi_select))+ return f"answer to {question}"++ result = json.loads(clarify_tool(+ "",+ questions=[+ {"question": "One?", "choices": ["a", "b"]},+ {"question": "Two?"},+ ],+ callback=legacy_cb,+ ))+ assert [c[0] for c in calls] == ["One?", "Two?"]+ assert calls[0][1] == ("a (Recommended)", "b")+ assert calls[1][1] is None+ assert [r["user_response"] for r in result["responses"]] == [+ "answer to One?", "answer to Two?",+ ]+ assert "timed_out" not in result++ def test_legacy_loop_aborts_on_timeout_and_keeps_partials(self):+ """The loop stops on the first timeout. Collected answers survive."""+ from tools.clarify_tool import TIMEOUT_RESPONSE+ calls = []++ def legacy_cb(question, choices):+ calls.append(question)+ if len(calls) == 2:+ return TIMEOUT_RESPONSE+ return "answered"++ result = json.loads(clarify_tool(+ "",+ questions=[+ {"question": "One?"}, {"question": "Two?"}, {"question": "Three?"},+ ],+ callback=legacy_cb,+ ))+ assert calls == ["One?", "Two?"]+ assert result["timed_out"] is True+ assert [r["user_response"] for r in result["responses"]] == [+ "answered", "", "",+ ]++ def test_legacy_loop_skip_continues(self):+ """An explicit empty answer is a skip. The loop continues."""+ calls = []++ def legacy_cb(question, choices):+ calls.append(question)+ return "" if len(calls) == 1 else "second"++ result = json.loads(clarify_tool(+ "",+ questions=[{"question": "One?"}, {"question": "Two?"}],+ callback=legacy_cb,+ ))+ assert calls == ["One?", "Two?"]+ assert [r["user_response"] for r in result["responses"]] == ["", "second"]+ assert "timed_out" not in result++ def test_single_question_result_shape_unchanged(self):+ """No `questions` arg keeps the historic result keys exactly."""+ def cb(question, choices):+ return "blue"++ result = json.loads(clarify_tool(+ "Color?", choices=["red", "blue"], callback=cb,+ ))+ assert set(result.keys()) == {"question", "choices_offered", "user_response"}+++class TestRegistryBatchPassThrough:+ """The registered handler forwards `questions` from tool args."""++ def test_handler_passes_questions(self):+ from tools.registry import registry+ entry = registry.get_entry("clarify")+ seen = {}++ def cb(question, choices, multi_select=False, questions=None):+ seen["questions"] = questions+ return {"answers": {"q0": "yes"}}++ result = json.loads(entry.handler(+ {"questions": [{"question": "Go?"}]},+ callback=cb,+ ))+ assert seen["questions"][0]["question"] == "Go?"+ assert result["responses"][0]["user_response"] == "yes"diff --git a/tools/clarify_tool.py b/tools/clarify_tool.pyindex d4bc8abeb13..d90930306e1 100644--- a/tools/clarify_tool.py+++ b/tools/clarify_tool.py@@ -15,13 +15,25 @@ a thin dispatcher that delegates to a platform-provided callback."""import json-from typing import List, Optional, Callable+from typing import Dict, List, Optional, Callable# Maximum number of predefined choices the agent can offer.# A 5th "Other (type your answer)" option is always appended by the UI.MAX_CHOICES = 4+# Maximum number of independent questions in one batch clarify call.+MAX_QUESTIONS = 5++# Canonical timeout sentinel returned to the agent when the user never+# answers. The CLI has always returned this exact text; the batch fallback+# loop also recognises it (alongside ``None``) as "the user walked away",+# which aborts the remaining questions instead of pestering one by one.+TIMEOUT_RESPONSE = (+ "The user did not provide a response within the time limit. "+ "Use your best judgement to make the choice and proceed."+)+# Suffix appended to the first choice so the user can see, at a glance, which# option the agent actually recommends. Applied here rather than per-surface so# CLI, TUI, desktop, and messaging adapters all render the same label.@@ -150,10 +162,175 @@ def _parse_multi_select_response(raw_response) -> List[str]:return [s.strip() for s in raw.split(",") if s.strip()]+# =============================================================================+# Batch (multi-question) support — issue #18450+# =============================================================================++def _normalize_questions(questions) -> tuple:+ """Validate and normalize the ``questions`` batch parameter.++ Returns ``(normalized, error)`` where exactly one is non-None, except the+ empty-list case which returns ``(None, None)`` — an empty array is not an+ error, it just means "no batch here" and the caller falls back to the+ single-question path.++ Each normalized entry carries:+ - ``qid``: stable wire id (``q0``..``qN``, index order). Surfaces key+ their per-question answers by this; a model-supplied ``id`` is NOT+ used on the wire (it's unvalidated text) and only echoed in results.+ - ``id``: the model's optional identifier, or None.+ - ``question``: stripped question text.+ - ``choices``: decorated choice list (recommended label applied), or+ None for open-ended.+ - ``choices_offered``: the bare list as offered, for the result JSON.+ - ``multi_select``: honored only when choices exist.+ """+ if not isinstance(questions, list):+ return None, "questions must be an array of question objects."+ if not questions:+ return None, None+ if len(questions) > MAX_QUESTIONS:+ return None, f"questions supports at most {MAX_QUESTIONS} items."++ normalized = []+ for index, item in enumerate(questions):+ if isinstance(item, str):+ # Tolerate bare-string items: LLMs sometimes send ["Q1?", "Q2?"].+ item = {"question": item}+ if not isinstance(item, dict):+ return None, f"questions[{index}] must be an object with a 'question'."++ text = str(item.get("question") or "").strip()+ if not text:+ return None, f"questions[{index}].question must be non-empty text."++ choices = item.get("choices")+ if choices is not None:+ if not isinstance(choices, list):+ return None, f"questions[{index}].choices must be a list."+ choices = [s for s in (_flatten_choice(c) for c in choices) if s]+ if len(choices) > MAX_CHOICES:+ choices = choices[:MAX_CHOICES]+ if not choices:+ choices = None++ model_id = str(item.get("id") or "").strip() or None++ normalized.append({+ "qid": f"q{index}",+ "id": model_id,+ "question": text,+ "choices": mark_recommended(list(choices)) if choices else None,+ "choices_offered": list(choices) if choices else None,+ "multi_select": bool(item.get("multi_select")) and bool(choices),+ })++ return normalized, None+++def _callback_accepts_questions(callback) -> bool:+ """True when the platform callback understands the ``questions`` kwarg.++ Same signature-inspection approach as ``_invoke_callback`` (never a+ TypeError retry — that would re-prompt the user on an internal bug).+ """+ import inspect++ try:+ params = inspect.signature(callback).parameters+ return "questions" in params or any(+ p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()+ )+ except (TypeError, ValueError):+ return False+++def _clean_batch_answer(entry: dict, raw) -> object:+ """Strip presentation from one locked answer (label, multi-select JSON)."""+ if entry["multi_select"]:+ return [strip_recommended(r) for r in _parse_multi_select_response(raw)]+ return strip_recommended(raw)+++def _batch_result(normalized: List[dict], answers: dict, timed_out: bool) -> str:+ """Assemble the batch result JSON from per-qid answers.++ Unanswered questions surface as empty ``user_response`` — with the+ top-level ``timed_out`` flag (present only when true) telling the agent+ whether those blanks are deliberate skips or the user walking away.+ """+ responses = []+ for entry in normalized:+ row = {}+ if entry["id"]:+ row["id"] = entry["id"]+ row["question"] = entry["question"]+ row["choices_offered"] = entry["choices_offered"]+ raw = answers.get(entry["qid"])+ row["user_response"] = _clean_batch_answer(entry, raw) if raw else ""+ responses.append(row)++ result: Dict[str, object] = {"responses": responses}+ if timed_out:+ result["timed_out"] = True+ return json.dumps(result, ensure_ascii=False)+++def _run_batch(normalized: List[dict], callback, question: str) -> str:+ """Dispatch a validated batch to the platform callback.++ Batch-capable callbacks (a ``questions`` kwarg, detected by signature)+ get the whole list once and reply with ``{"answers": {qid: raw}}`` plus+ an optional ``timed_out`` flag — as a dict or a JSON string (the+ tui_gateway ``_block`` bridge can only carry strings).++ Legacy callbacks are looped one question at a time (messaging adapters,+ older plugins). An explicit empty answer is a skip and the loop+ continues; a timeout (``None`` or the ``TIMEOUT_RESPONSE`` sentinel)+ means the user walked away, so the loop aborts instead of pestering+ them with the remaining questions. Answers collected before the abort+ are kept either way.+ """+ if _callback_accepts_questions(callback):+ raw = callback(question, None, questions=normalized)++ answers: dict = {}+ timed_out = False+ if raw is None or (isinstance(raw, str) and raw.strip() == TIMEOUT_RESPONSE):+ timed_out = True+ elif isinstance(raw, dict):+ answers = dict(raw.get("answers") or {})+ timed_out = bool(raw.get("timed_out"))+ elif isinstance(raw, str) and raw.strip():+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ parsed = None+ if isinstance(parsed, dict):+ answers = dict(parsed.get("answers") or {})+ timed_out = bool(parsed.get("timed_out"))+ # Any other falsy/unparseable reply is a cancel-all: every answer+ # empty, no timeout flag (mirrors the single-question skip).+ return _batch_result(normalized, answers, timed_out)++ answers = {}+ timed_out = False+ for entry in normalized:+ raw = _invoke_callback(+ callback, entry["question"], entry["choices"], entry["multi_select"],+ )+ if raw is None or (isinstance(raw, str) and raw.strip() == TIMEOUT_RESPONSE):+ timed_out = True+ break+ answers[entry["qid"]] = raw+ return _batch_result(normalized, answers, timed_out)++def clarify_tool(question: str,choices: Optional[List[str]] = None,multi_select: bool = False,+ questions: Optional[List[dict]] = None,callback: Optional[Callable] = None,) -> str:"""@@ -167,16 +344,40 @@ def clarify_tool((checkboxes). The ``user_response`` in the output JSONwill be a list of strings instead of a single string.Has no effect when ``choices`` is omitted.+ questions: Up to 5 independent questions asked as one batch+ (issue #18450). Each item: ``{id?, question, choices?,+ multi_select?}``. When present (non-empty), the single+ ``question``/``choices``/``multi_select`` parameters+ are ignored and the result JSON is ``{"responses":+ [...]}`` (plus ``"timed_out": true`` when the user+ stopped answering partway).callback: Platform-provided function that handles the actual UIinteraction. Signature:``callback(question, choices, multi_select=False) -> str``.- The optional ``multi_select`` keyword is passed so the- platform can render checkboxes instead of radio buttons.+ Batch-capable platforms additionally accept a+ ``questions`` keyword and receive the normalized list+ in one call; platforms without it are looped one+ question at a time.Injected by the agent runner (cli.py / gateway).Returns:- JSON string with the user's response.+ JSON string with the user's response(s)."""+ if questions is not None:+ normalized, error = _normalize_questions(questions)+ if error:+ return tool_error(error)+ if normalized:+ if callback is None:+ return tool_error(+ "Clarify tool is not available in this execution context."+ )+ try:+ return _run_batch(normalized, callback, str(question or "").strip())+ except Exception as exc:+ return tool_error(f"Failed to get user input: {exc}")+ # Empty questions array → fall through to the single-question path.+if not question or not question.strip():return tool_error("Question text is required.")@@ -296,6 +497,43 @@ CLARIFY_SCHEMA = {"Has no effect when choices is omitted (open-ended question)."),},+ "questions": {+ "type": "array",+ "maxItems": MAX_QUESTIONS,+ "description": (+ "Ask 2-5 INDEPENDENT questions in one call instead of "+ "several sequential clarify calls — the user answers them "+ "on one form, in any order. Each item has its own "+ "question/choices/multi_select (same rules as the "+ "top-level parameters); optional `id` is echoed back in "+ "the matching response. When set, the top-level question/"+ "choices are ignored and the result is {responses: [...]}, "+ "with `timed_out: true` added if the user stopped part-way "+ "(unanswered entries have an empty user_response). Only "+ "batch questions that are truly independent — if one "+ "answer would change another question, ask separately."+ ),+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": (+ "Optional short identifier echoed in the "+ "matching response (e.g. 'approach')."+ ),+ },+ "question": {"type": "string"},+ "choices": {+ "type": "array",+ "items": {"type": "string"},+ "maxItems": MAX_CHOICES,+ },+ "multi_select": {"type": "boolean"},+ },+ "required": ["question"],+ },+ },},"required": ["question"],},@@ -313,6 +551,7 @@ registry.register(question=args.get("question", ""),choices=args.get("choices"),multi_select=args.get("multi_select", False),+ questions=args.get("questions"),callback=kw.get("callback")),check_fn=check_clarify_requirements,emoji="❓",