diff --git a/.pr/agent-ask-user.docs-guide.mdx b/.pr/agent-ask-user.docs-guide.mdx new file mode 100644 index 00000000000..f1a6671c308 --- /dev/null +++ b/.pr/agent-ask-user.docs-guide.mdx @@ -0,0 +1,224 @@ +--- +title: Ask User +description: Let an agent pause and ask the user structured questions mid-task, then resume with the answer. +--- + +import RunExampleCode from "/sdk/shared-snippets/how-to-run-example.mdx"; + +> A ready-to-run example is available [here](#ready-to-run-example)! + +Use `ask_user` when the agent hits genuine ambiguity that the code or task does +not resolve, and guessing would risk wasted work. The agent asks one or more +structured questions in a single call, the run pauses, and the user's answer +becomes the tool result that resumes the run. + +## When to Use It + +`ask_user` is useful when an agent faces: + +- Architecture decisions the code does not encode (session vs. JWT vs. OAuth) +- Destructive migrations with several valid paths +- Product decisions that cannot be inferred from the repository + +Do not use it for anything the agent can determine from the code, the task, or +its own tools. Prefer a single, well-scoped call over repeated questions. + +## How It Works + +When the agent calls `ask_user`: + +1. The tool validates its arguments. Each question has a short `header` (at most + 12 characters), 2-4 `options` (each with a stable `id`, a `label`, and a + `description`), and a `multiSelect` flag. An "Other" free-text escape hatch is + always available. +2. The run ends at the `WAITING_FOR_CONFIRMATION` execution status with one + pending `ask_user` request recorded. The call is not executed; there is no new + event type or endpoint. +3. The user answers by sending a message through `send_message()`. The message + carries a JSON answer object: + + ```json + { + "request_id": "", + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]} + } + ``` + + Answers are keyed by each question's `header`. A free-text "Other" value uses + a `null` `option_id` with the text in `label`. Only the option `id` is + trusted: the displayed label always comes from the pending question, so an + answer cannot relabel a known option with arbitrary text. + +4. The SDK matches the answer to the pending request by `request_id` and converts + it into the `ask_user` tool observation, instead of appending it as an + unrelated user turn. The run then resumes with that observation in history. + When the same LLM response also carried other tool calls, the SDK keeps them + grouped with `ask_user` so the answered call and its siblings resume together, + and the next LLM request never carries a tool result without its tool call. + +`action` distinguishes `accept` (the user answered), `decline` (the user said +stop asking), and `cancel` (the user dismissed the question). The observation +carries this alongside the answers. An accepted answer must select at least one +option for every question. + + + An ordinary message that does not parse as an answer is left to the normal + user-turn path. A malformed, mis-keyed, or stale answer does not resolve the + call: the request stays pending, a non-LLM `AskUserAnswerNoticeEvent` records + the reason for clients, and the user can retry with a valid answer. + + +## Add the Tool + +`ask_user` is opt-in: it is not part of the default tool set. Add it to the +agent's tools by name: + +```python icon="python" wrap focus={2, 5} +from openhands.sdk import Agent, Tool +from openhands.sdk.tool.builtins import AskUserTool + +agent = Agent( + llm=llm, + tools=[Tool(name=AskUserTool.name)], +) +``` + +When the run pauses, read the pending request from the conversation state and +answer it: + +```python icon="python" +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) + +conversation.send_message("Add authentication to the API.") +conversation.run() + +if conversation.state.execution_status == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION: + request = ConversationState.get_unmatched_actions(conversation.state.events)[0] + conversation.send_message( + json.dumps( + { + "request_id": request.id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + conversation.run() +``` + +## Non-Interactive Runs + +Because this slice reuses the confirmation pause/resume machinery, the tool is +simply not registered in headless or evaluation runs. There is no +`interactive` capability flag yet, and tool availability is process-global. +Dedicated transport, a typed `request_id` request/response event pair, and a +timeout that resolves to `cancel` are planned follow-ups. + +## Ready-to-run Example + + +This example is available on GitHub: [examples/01_standalone_sdk/60_ask_user/main.py](https://github.com/OpenHands/software-agent-sdk/blob/main/examples/01_standalone_sdk/60_ask_user/main.py) + + +```python icon="python" expandable examples/01_standalone_sdk/60_ask_user/main.py +"""Ask the user structured questions mid-task, then resume with the answer. + +The ``ask_user`` tool lets the agent pause and ask one or more questions, each +with a short header, 2-4 labelled options, and an always-available free-text +"Other" escape hatch. The call ends the run at ``WAITING_FOR_CONFIRMATION`` and +records a pending request; the next message sent through ``send_message()`` that +parses as an answer is consumed as the tool's observation, and the run resumes +with that observation in history. + +This example drives the flow end to end: it sends a task that forces a choice, +detects the pause, answers the request programmatically (picking an option and +demonstrating the free-text escape hatch), and resumes the agent. + +Usage: + LLM_API_KEY=... LLM_BASE_URL=https://llm-proxy.app.all-hands.dev \ + uv run python examples/01_standalone_sdk/60_ask_user/main.py +""" + +import json +import os +import tempfile + +from openhands.sdk import LLM, Agent, Conversation, Tool +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) +from openhands.sdk.tool.builtins import AskUserTool +from openhands.sdk.tool.builtins.ask_user import AskUserAction + + +model = os.getenv("LLM_MODEL", "gpt-5.5") +api_key = os.getenv("LLM_API_KEY") +base_url = os.getenv("LLM_BASE_URL") +llm = LLM(usage_id="agent", model=model, api_key=api_key, base_url=base_url) + +# ask_user is opt-in: it is not part of the default tool set. +agent = Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]) + +workspace = tempfile.mkdtemp(prefix="ask_user_demo_") +conversation = Conversation(agent=agent, workspace=workspace) + +conversation.send_message( + "I want to add authentication to a small HTTP API. Before writing any " + "code, ask me which authentication approach to use (offer JWT and " + "session cookies) and how the tokens should be stored. Use the ask_user " + "tool; do not guess." +) +conversation.run() + +if ( + conversation.state.execution_status + != ConversationExecutionStatus.WAITING_FOR_CONFIRMATION +): + print( + "The agent did not call ask_user this time " + f"(status: {conversation.state.execution_status})." + ) +else: + pending = ConversationState.get_unmatched_actions(conversation.state.events) + request = pending[0] + print("Agent is waiting for an answer to request:", request.id) + + # Answer the request: pick JWT, and use the free-text escape hatch to say + # how tokens should be stored. Answers are keyed by each question's header. + action = request.action + assert isinstance(action, AskUserAction) + headers = [q.header for q in action.questions] + answer: dict[str, list[dict[str, str | None]]] = { + headers[0]: [{"option_id": "jwt"}], + } + for header in headers[1:]: + answer[header] = [{"option_id": None, "label": "in an httpOnly cookie"}] + + conversation.send_message( + json.dumps({"request_id": request.id, "action": "accept", "answers": answer}) + ) + + # The answer resolved the pending request and became the tool observation; + # resume the run. + conversation.run() + print("Final status:", conversation.state.execution_status) + +cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost +print(f"EXAMPLE_COST: {cost}") +``` + + + +## Next Steps + +- **[Pause and Resume](/sdk/guides/convo-pause-and-resume)** - Control agent + execution without losing state +- **[Security & Action Confirmation](/sdk/guides/security)** - The confirmation + pause/resume shape this tool reuses +- **[Custom Tools](/sdk/guides/custom-tools)** - Build tools with custom + behavior diff --git a/.pr/agent-ask-user.docs-json.patch b/.pr/agent-ask-user.docs-json.patch new file mode 100644 index 00000000000..84a70d1ffcf --- /dev/null +++ b/.pr/agent-ask-user.docs-json.patch @@ -0,0 +1,12 @@ +diff --git a/docs.json b/docs.json +index 8572c83..e76f7d2 100644 +--- a/docs.json ++++ b/docs.json +@@ -396,6 +396,7 @@ + "sdk/guides/agent-file-based", + "sdk/guides/agent-stuck-detector", + "sdk/guides/agent-ask-oracle", ++ "sdk/guides/agent-ask-user", + "sdk/guides/agent-tom-agent", + "sdk/guides/critic" + ] diff --git a/.pr/ask_user_live_demo.py b/.pr/ask_user_live_demo.py new file mode 100644 index 00000000000..4695f5b18fb --- /dev/null +++ b/.pr/ask_user_live_demo.py @@ -0,0 +1,267 @@ +"""End-to-end live evidence for the ask_user pause/resume flow (PR evidence). + +Runs a real LocalConversation with a TestLLM that scripted the agent calling +``ask_user`` and then ``finish``. Prints the observable state at each step so a +reviewer can see: the run pauses at WAITING_FOR_CONFIRMATION with one pending +request, the answer sent via ``send_message()`` is consumed as the tool +observation, and the run resumes to FINISHED. + +Run: + uv run python .pr/ask_user_live_demo.py +""" + +import json + +from openhands.sdk import Agent, Conversation, Tool +from openhands.sdk.conversation import LocalConversation +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) +from openhands.sdk.event import MessageEvent, ObservationEvent +from openhands.sdk.event.llm_convertible.observation import AgentErrorEvent +from openhands.sdk.llm import Message, MessageToolCall, TextContent +from openhands.sdk.testing import TestLLM +from openhands.sdk.tool.builtins import AskUserTool +from openhands.sdk.tool.builtins.ask_user import AskUserObservation + + +ASK_ARGS = json.dumps( + { + "questions": [ + { + "question": "Which auth?", + "header": "auth", + "options": [ + {"id": "jwt", "label": "JWT", "description": "token"}, + {"id": "session", "label": "Session", "description": "cookie"}, + ], + "multiSelect": False, + } + ] + } +) + + +def call(name: str, call_id: str, arguments: str) -> Message: + return Message( + role="assistant", + content=[TextContent(text="")], + tool_calls=[ + MessageToolCall( + id=call_id, name=name, arguments=arguments, origin="completion" + ) + ], + ) + + +llm = TestLLM.from_messages( + [ + call("ask_user", "ask_1", ASK_ARGS), + call("finish", "finish_1", '{"message": "done"}'), + ] +) +agent = Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]) +conversation: LocalConversation = Conversation(agent=agent) + +print("== turn 1: agent calls ask_user ==") +conversation.send_message("add auth to the API") +conversation.run() +status = conversation.state.execution_status +print("status after run:", status) +assert status == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + +pending = ConversationState.get_unmatched_actions(conversation.state.events) +print("pending requests:", [(p.tool_name, p.id) for p in pending]) +assert len(pending) == 1 and pending[0].tool_name == "ask_user" +request_id = pending[0].id + +print("\n== turn 2: user answers via send_message() ==") +conversation.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) +) +remaining = ConversationState.get_unmatched_actions(conversation.state.events) +print("pending after answer:", remaining) +assert remaining == [] + +observations = [ + e.observation + for e in conversation.state.events + if isinstance(e, ObservationEvent) and isinstance(e.observation, AskUserObservation) +] +print("ask_user observations:", [o.model_dump() for o in observations]) +assert len(observations) == 1 +assert observations[0].answers[0].selected[0].option_id == "jwt" + +user_texts = [ + c.text + for e in conversation.state.events + if isinstance(e, MessageEvent) and e.source == "user" + for c in e.llm_message.content + if isinstance(c, TextContent) +] +print("user turns in history:", user_texts) +assert user_texts == ["add auth to the API"], "answer must not become a user turn" + +print("\n== turn 3: resume the run ==") +conversation.run() +print("final status:", conversation.state.execution_status) +assert conversation.state.execution_status == ConversationExecutionStatus.FINISHED +print("\nLIVE DEMO PASSED") + + +# --------------------------------------------------------------------------- +# Scenario 2: an invalid call gets a corrective observation, not a crash. +# --------------------------------------------------------------------------- +bad_args = json.dumps( + { + "questions": [ + { + "question": "Which auth?", + "header": "auth", + "options": [{"id": "jwt", "label": "JWT", "description": "token"}], + } + ] + } +) +llm2 = TestLLM.from_messages( + [ + call("ask_user", "ask_bad", bad_args), + call("finish", "finish_2", '{"message": "fixed"}'), + ] +) +conversation2: LocalConversation = Conversation( + agent=Agent(llm=llm2, tools=[Tool(name=AskUserTool.name)]) +) +print("\n== scenario 2: invalid ask_user call (1 option) ==") +conversation2.send_message("ask me") +conversation2.run() +errors = [e.error for e in conversation2.state.events if isinstance(e, AgentErrorEvent)] +print("corrective errors:", errors) +assert any("between 2 and 4 options" in e for e in errors) +assert conversation2.state.execution_status == ConversationExecutionStatus.FINISHED +print("\nSCENARIO 2 PASSED") + + +# --------------------------------------------------------------------------- +# Scenario 3: with confirmation mode on, a risky tool that shares the response +# with ask_user must not run when the question is answered. +# --------------------------------------------------------------------------- +from typing import ClassVar # noqa: E402 + +from openhands.sdk.event import UserRejectObservation # noqa: E402 +from openhands.sdk.event.llm_convertible.observation import ( # noqa: E402 + ObservationEvent as _ObservationEvent, +) +from openhands.sdk.security.confirmation_policy import AlwaysConfirm # noqa: E402 +from openhands.sdk.tool import ( # noqa: E402 + Action, + Observation, + ToolDefinition, + ToolExecutor, + register_tool, +) + + +class _RiskyAction(Action): + command: str + + +class _RiskyObservation(Observation): + result: str + + +class _RiskyExecutor(ToolExecutor[_RiskyAction, _RiskyObservation]): + def __call__(self, action, conversation=None): # noqa: ARG002 + return _RiskyObservation(result=f"Executed: {action.command}") + + +class _RiskyTool(ToolDefinition[_RiskyAction, _RiskyObservation]): + name: ClassVar[str] = "risky_write" + + @classmethod + def create(cls, conv_state=None, **params): # noqa: ARG003 + return [ + cls( + description="A write that must be confirmed", + action_type=_RiskyAction, + observation_type=_RiskyObservation, + executor=_RiskyExecutor(), + ) + ] + + +register_tool("risky_write", _RiskyTool) + +llm3 = TestLLM.from_messages( + [ + Message( + role="assistant", + content=[TextContent(text="")], + tool_calls=[ + MessageToolCall( + id="ask_3", name="ask_user", arguments=ASK_ARGS, origin="completion" + ), + MessageToolCall( + id="risky_3", + name="risky_write", + arguments=json.dumps({"command": "rm -rf build"}), + origin="completion", + ), + ], + ), + call("finish", "finish_3", '{"message": "done"}'), + ] +) +conversation3: LocalConversation = Conversation( + agent=Agent(llm=llm3, tools=[Tool(name=AskUserTool.name), Tool(name="risky_write")]) +) +conversation3.set_confirmation_policy(AlwaysConfirm()) +print("\n== scenario 3: ask_user + risky sibling under AlwaysConfirm ==") +conversation3.send_message("ship it") +conversation3.run() +print("status after run:", conversation3.state.execution_status) +assert conversation3.state.execution_status == ( + ConversationExecutionStatus.WAITING_FOR_CONFIRMATION +) +rejections = [ + e for e in conversation3.state.events if isinstance(e, UserRejectObservation) +] +print("rejected siblings:", [r.tool_name for r in rejections]) +assert [r.tool_name for r in rejections] == ["risky_write"] +risky_obs = [ + e + for e in conversation3.state.events + if isinstance(e, _ObservationEvent) and e.tool_name == "risky_write" +] +assert risky_obs == [], "the risky sibling must not run without approval" + +request_id3 = [ + p.id + for p in ConversationState.get_unmatched_actions(conversation3.state.events) + if p.tool_name == "ask_user" +][0] +conversation3.send_message( + json.dumps( + { + "request_id": request_id3, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) +) +conversation3.run() +print("final status:", conversation3.state.execution_status) +risky_obs = [ + e + for e in conversation3.state.events + if isinstance(e, _ObservationEvent) and e.tool_name == "risky_write" +] +assert risky_obs == [], "answering the question is not approval for the sibling" +print("\nSCENARIO 3 PASSED") diff --git a/examples/01_standalone_sdk/60_ask_user/main.py b/examples/01_standalone_sdk/60_ask_user/main.py new file mode 100644 index 00000000000..208cb42a4b2 --- /dev/null +++ b/examples/01_standalone_sdk/60_ask_user/main.py @@ -0,0 +1,85 @@ +"""Ask the user structured questions mid-task, then resume with the answer. + +The ``ask_user`` tool lets the agent pause and ask one or more questions, each +with a short header, 2-4 labelled options, and an always-available free-text +"Other" escape hatch. The call ends the run at ``WAITING_FOR_CONFIRMATION`` and +records a pending request; the next message sent through ``send_message()`` that +parses as an answer is consumed as the tool's observation, and the run resumes +with that observation in history. + +This example drives the flow end to end: it sends a task that forces a choice, +detects the pause, answers the request programmatically (picking an option and +demonstrating the free-text escape hatch), and resumes the agent. + +Usage: + LLM_API_KEY=... LLM_BASE_URL=https://llm-proxy.app.all-hands.dev \ + uv run python examples/01_standalone_sdk/60_ask_user/main.py +""" + +import json +import os +import tempfile + +from openhands.sdk import LLM, Agent, Conversation, Tool +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) +from openhands.sdk.tool.builtins import AskUserTool +from openhands.sdk.tool.builtins.ask_user import AskUserAction + + +model = os.getenv("LLM_MODEL", "gpt-5.5") +api_key = os.getenv("LLM_API_KEY") +base_url = os.getenv("LLM_BASE_URL") +llm = LLM(usage_id="agent", model=model, api_key=api_key, base_url=base_url) + +# ask_user is opt-in: it is not part of the default tool set. +agent = Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]) + +workspace = tempfile.mkdtemp(prefix="ask_user_demo_") +conversation = Conversation(agent=agent, workspace=workspace) + +conversation.send_message( + "I want to add authentication to a small HTTP API. Before writing any " + "code, ask me which authentication approach to use (offer JWT and " + "session cookies) and how the tokens should be stored. Use the ask_user " + "tool; do not guess." +) +conversation.run() + +if ( + conversation.state.execution_status + != ConversationExecutionStatus.WAITING_FOR_CONFIRMATION +): + print( + "The agent did not call ask_user this time " + f"(status: {conversation.state.execution_status})." + ) +else: + pending = ConversationState.get_unmatched_actions(conversation.state.events) + request = pending[0] + print("Agent is waiting for an answer to request:", request.id) + + # Answer the request: pick JWT, and use the free-text escape hatch to say + # how tokens should be stored. Answers are keyed by each question's header. + action = request.action + assert isinstance(action, AskUserAction) + headers = [q.header for q in action.questions] + answer: dict[str, list[dict[str, str | None]]] = { + headers[0]: [{"option_id": "jwt"}], + } + for header in headers[1:]: + answer[header] = [{"option_id": None, "label": "in an httpOnly cookie"}] + + conversation.send_message( + json.dumps({"request_id": request.id, "action": "accept", "answers": answer}) + ) + + # The answer resolved the pending request and became the tool observation; + # resume the run. + conversation.run() + print("Final status:", conversation.state.execution_status) + +cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost +print(f"EXAMPLE_COST: {cost}") diff --git a/openhands-sdk/openhands/sdk/agent/agent.py b/openhands-sdk/openhands/sdk/agent/agent.py index 28b3472226f..ae251c739f3 100644 --- a/openhands-sdk/openhands/sdk/agent/agent.py +++ b/openhands-sdk/openhands/sdk/agent/agent.py @@ -715,11 +715,27 @@ def _step( # and execute them before sampling new actions. pending_actions = ConversationState.get_unmatched_actions(state.active_branch()) if pending_actions: + # A pause-for-user-input call (e.g. ask_user) is resolved only by an + # answering user message, never by implicit confirmation. If one is + # still pending, re-signal the wait and leave it intact so a re-run + # before the answer does not execute its error-only executor and + # silently drop the question. + if any(self._pauses_for_user_input(ae.tool_name) for ae in pending_actions): + state.execution_status = ( + ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + return logger.info( "Confirmation mode: Executing %d pending action(s)", len(pending_actions), ) self._execute_actions(conversation, pending_actions, on_event) + # A batch that also carried a resolved pause-for-user-input call was + # kept intact (not collapsed) while it awaited the answer, so + # re-derive the view now that every sibling has an observation. This + # groups the whole action batch with all of its results and drops + # any batch still incomplete. + state.rebuild_view() return # Check if the last user message was blocked by a UserPromptSubmit hook @@ -928,11 +944,17 @@ async def _astep( # Check for pending actions (implicit confirmation) pending_actions = ConversationState.get_unmatched_actions(state.active_branch()) if pending_actions: + if any(self._pauses_for_user_input(ae.tool_name) for ae in pending_actions): + state.execution_status = ( + ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + return logger.info( "Confirmation mode: Executing %d pending action(s)", len(pending_actions), ) await self._aexecute_actions(conversation, pending_actions, on_event) + state.rebuild_view() return if state.last_user_message_id is not None: @@ -1150,17 +1172,81 @@ async def _arequires_user_confirmation( """Resolve audit secrets without blocking the loop or holding state.""" risks, event = self._analyze_for_confirmation(state, action_events) if event is not None: - while True: - sources = dict(state.secret_registry.secret_sources) - async with conversation._released_state_lock_during_io(): - event = await asyncio.to_thread( - state.secret_registry.mask_secrets_in_model, event - ) - if sources == state.secret_registry.secret_sources: - break - on_event(event) + on_event(await self._amask_security_event(conversation, state, event)) return self._set_confirmation_status(state, risks) + @staticmethod + async def _amask_security_event( + conversation: LocalConversation, + state: ConversationState, + event: SecurityAnalysisEvent, + ) -> SecurityAnalysisEvent: + """Mask secrets in a security-audit event without holding the state lock.""" + while True: + sources = dict(state.secret_registry.secret_sources) + async with conversation._released_state_lock_during_io(): + event = await asyncio.to_thread( + state.secret_registry.mask_secrets_in_model, event + ) + if sources == state.secret_registry.secret_sources: + break + return event + + def _gated_for_confirmation( + self, state: ConversationState, action_events: list[ActionEvent] + ) -> tuple[list[ActionEvent], SecurityAnalysisEvent | None]: + """The subset of ``action_events`` the confirmation policy would gate.""" + if not action_events: + return [], None + risks, event = self._analyze_for_confirmation(state, action_events) + gated = [ + ae + for ae, risk_level in zip(action_events, risks) + if state.confirmation_policy.should_confirm(risk_level) + ] + return gated, event + + def _gate_paused_siblings( + self, + conversation: LocalConversation, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> None: + """Apply the confirmation policy to a paused batch's non-pause calls. + + :meth:`_pause_for_user_input` returns before the confirmation gate, so + without this a response that pairs a pause call with another tool would + never have the policy consulted: the sibling would stay pending and be + executed by the run that delivers the user's *answer*, which is not an + approval. Reject any sibling the policy would gate so it cannot run + without confirmation; the agent can re-issue it on its own, where the + normal confirmation flow applies. + """ + gated, event = self._gated_for_confirmation( + state, self._sibling_actions(action_events) + ) + if event is not None: + on_event(state.secret_registry.mask_secrets_in_model(event)) + if gated: + self._reject_paused_siblings(conversation, gated, on_event) + + async def _agate_paused_siblings( + self, + conversation: LocalConversation, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> None: + """Async variant of :meth:`_gate_paused_siblings`.""" + gated, event = self._gated_for_confirmation( + state, self._sibling_actions(action_events) + ) + if event is not None: + on_event(await self._amask_security_event(conversation, state, event)) + if gated: + self._reject_paused_siblings(conversation, gated, on_event) + def _analyze_for_confirmation( self, state: ConversationState, action_events: list[ActionEvent] ) -> tuple[list[risk.SecurityRisk], SecurityAnalysisEvent | None]: @@ -1201,6 +1287,135 @@ def _set_confirmation_status( return False + def _pause_for_user_input( + self, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> bool: + """Pause the run for a tool that must hand control back to the user. + + A tool marked ``pauses_run_for_user_input`` (e.g. ``ask_user``) does not + execute here. Its ``ActionEvent`` is left unmatched so the next + ``send_message()`` can resolve it, and the run ends at + ``WAITING_FOR_CONFIRMATION``. An invalid call is reported as a + corrective error observation (and dropped from ``action_events`` so it + does not also execute) and the run continues so the agent can fix it. + + Returns True when the run should stop here. On True, ``action_events`` + holds only the pending request plus any sibling calls from the same + response; the caller must then apply the confirmation policy to those + siblings via :meth:`_sibling_actions`. + """ + pause_events = [ + ae for ae in action_events if self._pauses_for_user_input(ae.tool_name) + ] + if not pause_events: + return False + + current_ids = {ae.id for ae in action_events} + # At most one request may be pending. Exclude this step's own calls + # (already emitted, hence unmatched) when looking for an earlier one. + already_pending = any( + ae.id not in current_ids and self._pauses_for_user_input(ae.tool_name) + for ae in ConversationState.get_unmatched_actions(state.active_branch()) + ) + + pending: ActionEvent | None = None + for ae in pause_events: + tool = self.tools_map.get(ae.tool_name) + assert tool is not None, "pause tool must be in tools_map" + if already_pending: + error: str | None = ( + "another request for user input is already pending; wait for " + "its answer before asking again" + ) + elif pending is not None: + error = ( + "only one user-input request is allowed per step; combine " + "the questions into a single call" + ) + elif ae.action is None: + error = f"{ae.tool_name} call had no valid action" + else: + error = tool.pause_error_for(ae.action) + if error is not None: + self._emit_pause_error(on_event, ae, error) + action_events.remove(ae) + else: + pending = ae + + if pending is None: + return False + + state.execution_status = ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + return True + + def _sibling_actions(self, action_events: list[ActionEvent]) -> list[ActionEvent]: + """The non-pause calls that shared the paused request's response.""" + return [ + ae for ae in action_events if not self._pauses_for_user_input(ae.tool_name) + ] + + def _reject_paused_siblings( + self, + conversation: LocalConversation, + siblings: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> None: + """Reject sibling calls that require confirmation before they can run. + + The run is paused for the user's *answer*, not for action approval, so a + sibling the confirmation policy would gate must not ride along and + execute once the answer arrives. Rejecting it keeps the batch coherent + (its tool call still gets a result) and leaves approval to a fresh, + explicit step, where the normal confirmation flow applies. + """ + for ae in siblings: + logger.info( + "Rejecting unconfirmed sibling action '%s' from a paused batch", + ae.tool_name, + ) + rejection = UserRejectObservation( + action_id=ae.id, + tool_name=ae.tool_name, + tool_call_id=ae.tool_call_id, + rejection_reason=( + "Not executed: this action shared an LLM response with a " + "request for user input and requires confirmation. Re-issue " + "it on its own to be asked for approval." + ), + ) + record_tool_result( + conversation, + name=extract_action_name(ae), + tool_call_id=ae.tool_call_id, + tool_input=ae.action, + tool_output=rejection.to_llm_message(), + ) + on_event(rejection) + + def _pauses_for_user_input(self, tool_name: str) -> bool: + tool = self.tools_map.get(tool_name) + return tool is not None and tool.pauses_run_for_user_input + + def _emit_pause_error( + self, + on_event: ConversationCallbackType, + action_event: ActionEvent, + error: str, + ) -> None: + """Emit a corrective error observation for an invalid pause call.""" + logger.warning("Invalid user-input pause call: %s", error) + on_event( + AgentErrorEvent( + error=error, + tool_name=action_event.tool_name, + tool_call_id=action_event.tool_call_id, + classification=AGENT_OUTCOME, + ) + ) + def _extract_security_risk( self, arguments: dict, diff --git a/openhands-sdk/openhands/sdk/agent/response_dispatch.py b/openhands-sdk/openhands/sdk/agent/response_dispatch.py index 9796c7b6c15..d59d4cb7f58 100644 --- a/openhands-sdk/openhands/sdk/agent/response_dispatch.py +++ b/openhands-sdk/openhands/sdk/agent/response_dispatch.py @@ -139,6 +139,29 @@ async def _arequires_user_confirmation( on_event: ConversationCallbackType, ) -> bool: ... + def _pause_for_user_input( + self, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> bool: ... + + def _gate_paused_siblings( + self, + conversation: LocalConversation, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> None: ... + + async def _agate_paused_siblings( + self, + conversation: LocalConversation, + state: ConversationState, + action_events: list[ActionEvent], + on_event: ConversationCallbackType, + ) -> None: ... + def _maybe_emit_vllm_tokens( self, llm_response: LLMResponse, @@ -192,6 +215,10 @@ def _handle_tool_calls( continue action_events.append(action_event) + if self._pause_for_user_input(state, action_events, on_event): + self._gate_paused_siblings(conversation, state, action_events, on_event) + return + if self._requires_user_confirmation(state, action_events, on_event): return @@ -246,6 +273,12 @@ async def _ahandle_tool_calls( continue action_events.append(action_event) + if self._pause_for_user_input(state, action_events, on_event): + await self._agate_paused_siblings( + conversation, state, action_events, on_event + ) + return + if await self._arequires_user_confirmation( conversation, state, action_events, on_event ): diff --git a/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py b/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py index 9c56cf0b147..a7fb33cfed6 100644 --- a/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py +++ b/openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py @@ -40,6 +40,7 @@ from openhands.sdk.event import ( ActionEvent, AgentErrorEvent, + AskUserAnswerNoticeEvent, CondensationRequest, Event, EventID, @@ -1881,6 +1882,13 @@ def send_message(self, message: str | Message, sender: str | None = None) -> Non ConversationExecutionStatus.IDLE ) # new message resets terminal states + # Resolve a pending pause-for-user-input call *before* touching + # per-turn skill state: the answer is consumed as the tool + # observation, so its text must not activate knowledge skills that + # would then be marked delivered without ever reaching the LLM. + if self._try_resolve_ask_user(message): + return + activated_skill_names: list[str] = [] extended_content: list[TextContent] = [] @@ -1912,6 +1920,128 @@ def send_message(self, message: str | Message, sender: str | None = None) -> Non ) self._on_event(user_msg_event) + def _pending_ask_user_action(self) -> ActionEvent | None: + """The single unmatched pause-for-user-input action, or None. + + The pending request is derived from the event log rather than a separate + field, so it survives a resume and needs no new persisted state. Its + ``id`` is the ``request_id`` the answer is matched against. + """ + for ae in ConversationState.get_unmatched_actions(self._state.active_branch()): + if self._tool_pauses_for_user_input(ae.tool_name): + return ae + return None + + def _tool_pauses_for_user_input(self, tool_name: str) -> bool: + # ACPAgent initialization is deliberately deferred to run(), so this + # resolver can run from send_message() before tools_map exists. An + # uninitialized agent has no resolved tools, hence nothing pauses. + if not self.agent._initialized: + return False + tool = self.agent.tools_map.get(tool_name) + return tool is not None and tool.pauses_run_for_user_input + + def _try_resolve_ask_user(self, message: Message) -> bool: + """Resolve a pending pause-for-user-input call from a user message. + + Returns True when the message was consumed here (as the tool + observation, or as a corrective signal for a malformed answer), so the + caller must not append it as a normal user turn. Returns False when + there is no pending request or the message is not an answer, leaving it + to the normal user-turn path. + """ + pending = self._pending_ask_user_action() + if pending is None: + return False + tool = self.agent.tools_map.get(pending.tool_name) + if tool is None: + return False + + try: + observation = tool.resolve_user_input(pending, message) + except ValueError as e: + # Answer-shaped but unusable: keep the request pending and record a + # client-visible notice. The notice is deliberately not + # LLM-convertible so it cannot land between the pending tool call + # and its eventual result (which Anthropic rejects). + logger.warning("Rejected ask_user answer: %s", e) + self._on_event( + AskUserAnswerNoticeEvent(request_id=pending.id, detail=str(e)) + ) + return True + if observation is None: + return False + + observation_event = ObservationEvent( + observation=observation, + action_id=pending.id, + tool_name=pending.tool_name, + tool_call_id=pending.tool_call_id, + ) + record_tool_result( + self, + name=pending.tool_name, + tool_call_id=pending.tool_call_id, + tool_input=pending.action, + tool_output=observation_event.to_llm_message(), + ) + self._on_event(observation_event) + # A refusal (ask_user decline/cancel) is not approval for the rest of the + # batch: reject any sibling calls that were still awaiting the answer so + # the resumed run cannot execute them without the user's consent. On an + # accepting resolution the siblings stay pending and resume normally. + if tool.resolution_rejects_pending(observation): + self._reject_paused_siblings(pending) + # On a cold load the cached view dropped this pending action (tool-call + # matching removes actions without observations), so appending only the + # observation would leave a tool result without its tool call. When the + # whole batch is now resolved, re-derive the view to restore the pair. + # When sibling calls in the same response are still pending, leave the + # view alone: full enforcement would drop the incomplete batch, and the + # post-execution rebuild groups the complete batch once the siblings run. + if not self._has_pending_sibling_action(pending): + self._state.rebuild_view() + return True + + def _reject_paused_siblings(self, pending: ActionEvent) -> None: + """Reject sibling calls that shared ``pending``'s response and are pending. + + Used when the user declines or dismisses the question: the siblings were + part of the same step, and the user's refusal must not be treated as + approval for them. Each still-unmatched sibling gets a + ``UserRejectObservation`` so the batch stays coherent and the agent can + re-issue the work if it is still needed. + """ + for ae in ConversationState.get_unmatched_actions(self._state.active_branch()): + if ae.id == pending.id or ae.llm_response_id != pending.llm_response_id: + continue + rejection = UserRejectObservation( + action_id=ae.id, + tool_name=ae.tool_name, + tool_call_id=ae.tool_call_id, + rejection_reason=( + "Not executed: the user declined the request for input that " + "shared this step. Re-issue it if it is still needed." + ), + ) + record_tool_result( + self, + name=extract_action_name(ae), + tool_call_id=ae.tool_call_id, + tool_input=ae.action, + tool_output=rejection.to_llm_message(), + ) + self._on_event(rejection) + + def _has_pending_sibling_action(self, action: ActionEvent) -> bool: + """Whether another unresolved call shares ``action``'s batch.""" + return any( + ae.llm_response_id == action.llm_response_id + for ae in ConversationState.get_unmatched_actions( + self._state.active_branch() + ) + ) + def _on_event_with_state_lock(self, event: Event) -> None: """Emit an event while holding the conversation state lock.""" with self._state: diff --git a/openhands-sdk/openhands/sdk/conversation/visualizer/default.py b/openhands-sdk/openhands/sdk/conversation/visualizer/default.py index a1317e72ac1..a9690fb6368 100644 --- a/openhands-sdk/openhands/sdk/conversation/visualizer/default.py +++ b/openhands-sdk/openhands/sdk/conversation/visualizer/default.py @@ -17,6 +17,7 @@ ACPToolCallEvent, ActionEvent, AgentErrorEvent, + AskUserAnswerNoticeEvent, ConversationStateUpdateEvent, MessageEvent, ObservationEvent, @@ -242,6 +243,10 @@ def _get_message_color(event: Event) -> str: title="User Paused", color=_PAUSE_COLOR, ), + AskUserAnswerNoticeEvent: EventVisualizationConfig( + title="Rejected Answer", + color=_ERROR_COLOR, + ), Condensation: EventVisualizationConfig( title="Condensation", color="white", diff --git a/openhands-sdk/openhands/sdk/event/__init__.py b/openhands-sdk/openhands/sdk/event/__init__.py index 6bda3f0a7f8..70447f0c28e 100644 --- a/openhands-sdk/openhands/sdk/event/__init__.py +++ b/openhands-sdk/openhands/sdk/event/__init__.py @@ -1,4 +1,5 @@ from openhands.sdk.event.acp_tool_call import ACPToolCallEvent +from openhands.sdk.event.ask_user import AskUserAnswerNoticeEvent from openhands.sdk.event.base import Event, LLMConvertibleEvent from openhands.sdk.event.condenser import ( Condensation, @@ -31,6 +32,7 @@ __all__ = [ "ACPToolCallEvent", + "AskUserAnswerNoticeEvent", "Event", "LLMConvertibleEvent", "SystemPromptEvent", diff --git a/openhands-sdk/openhands/sdk/event/ask_user.py b/openhands-sdk/openhands/sdk/event/ask_user.py new file mode 100644 index 00000000000..5d6c2cce891 --- /dev/null +++ b/openhands-sdk/openhands/sdk/event/ask_user.py @@ -0,0 +1,28 @@ +"""Out-of-band notice that a malformed ``ask_user`` answer was rejected. + +This event is emitted on the user-message path (not generated by the agent) and +is intentionally **not** LLM-convertible: a corrective note placed in the LLM +stream would sit between the pending tool call and its eventual result, so the +resumed history would contain ``assistant tool_use`` -> ``user note`` -> +``tool_result``. Providers such as Anthropic require the tool result to directly +follow its tool call and reject that ordering. Keeping the notice outside the +LLM event stream lets clients surface the feedback while the pending request +stays open for a valid retry. +""" + +from pydantic import Field + +from openhands.sdk.event.base import Event +from openhands.sdk.event.types import SourceType + + +class AskUserAnswerNoticeEvent(Event): + """A malformed answer was rejected while an ``ask_user`` call is pending.""" + + source: SourceType = "environment" + request_id: str = Field( + description="Id of the pending ``ask_user`` request the answer targeted." + ) + detail: str = Field( + description="Human-readable reason the answer could not be used." + ) diff --git a/openhands-sdk/openhands/sdk/tool/builtins/__init__.py b/openhands-sdk/openhands/sdk/tool/builtins/__init__.py index 8d931ecb254..4adeeb1d3e7 100644 --- a/openhands-sdk/openhands/sdk/tool/builtins/__init__.py +++ b/openhands-sdk/openhands/sdk/tool/builtins/__init__.py @@ -6,6 +6,15 @@ Tools that require interacting with the environment belong in `openhands-tools`. """ +from openhands.sdk.tool.builtins.ask_user import ( + AskUserAction, + AskUserAnswerAction, + AskUserExecutor, + AskUserObservation, + AskUserTool, + OptionInfo, + QuestionInfo, +) from openhands.sdk.tool.builtins.classify_and_switch_llm import ( ClassifyAndSwitchLLMAction, ClassifyAndSwitchLLMExecutor, @@ -59,6 +68,7 @@ SwitchLLMTool.__name__: SwitchLLMTool, VisionInspectTool.__name__: VisionInspectTool, ClassifyAndSwitchLLMTool.__name__: ClassifyAndSwitchLLMTool, + AskUserTool.__name__: AskUserTool, } BUILT_IN_TOOLS_WITH_PARAMS = frozenset({ClassifyAndSwitchLLMTool.__name__}) @@ -78,6 +88,13 @@ def builtin_tool_class(name: str) -> type[ToolDefinition] | None: "BUILT_IN_TOOL_CLASSES", "BUILT_IN_TOOLS_WITH_PARAMS", "builtin_tool_class", + "AskUserTool", + "AskUserAction", + "AskUserObservation", + "AskUserExecutor", + "OptionInfo", + "QuestionInfo", + "AskUserAnswerAction", "ClassifyAndSwitchLLMTool", "ClassifyAndSwitchLLMAction", "ClassifyAndSwitchLLMObservation", diff --git a/openhands-sdk/openhands/sdk/tool/builtins/ask_user.py b/openhands-sdk/openhands/sdk/tool/builtins/ask_user.py new file mode 100644 index 00000000000..ea05e9d9338 --- /dev/null +++ b/openhands-sdk/openhands/sdk/tool/builtins/ask_user.py @@ -0,0 +1,519 @@ +"""``ask_user``: ask the user structured questions and pause the run. + +The agent calls ``ask_user`` with one or more questions, each offering 2-4 +labelled options (plus an always-available free-text "Other" escape hatch). +The call pauses the run at ``WAITING_FOR_CONFIRMATION`` and records a pending +request; the next user message sent through ``send_message()`` that parses as an +answer for that request is converted into the tool observation, and the run +resumes with that observation in history. + +This slice reuses the confirmation pause/resume shape: there is no dedicated +Agent Server endpoint or event type, and no new serialized status value. The +pending request is derived from the unmatched ``ask_user`` ``ActionEvent`` in +the event log, and the answer is matched to it by ``request_id`` (the action +event id). The typed request/response transport lands in a follow-up. +""" + +from __future__ import annotations + +import json +from collections.abc import Sequence +from enum import Enum +from typing import TYPE_CHECKING, Any, ClassVar, Self + +from pydantic import BaseModel, ConfigDict, Field +from rich.text import Text + +from openhands.sdk.llm import TextContent +from openhands.sdk.tool.registry import register_tool +from openhands.sdk.tool.tool import ( + Action, + Observation, + ToolAnnotations, + ToolDefinition, + ToolExecutor, +) + + +if TYPE_CHECKING: + from openhands.sdk.conversation.base import BaseConversation + from openhands.sdk.conversation.state import ConversationState + from openhands.sdk.event import ActionEvent + from openhands.sdk.llm import Message + + +MAX_OPTIONS = 4 +MIN_OPTIONS = 2 +MAX_QUESTIONS = 4 +MAX_HEADER_LENGTH = 12 + + +class OptionInfo(BaseModel): + """One selectable answer for a question.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + id: str = Field( + description=( + "Stable identifier for this option, referenced by the answer. " + "Must be unique within the question." + ) + ) + label: str = Field(description="Short display label for the option.") + description: str = Field( + description="Explanation of what choosing this option means." + ) + + +class QuestionInfo(BaseModel): + """A single structured question with a fixed set of options.""" + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + question: str = Field(description="The full question text to show the user.") + header: str = Field( + description=( + "Short label (at most 12 characters) used to key the answer and to " + "render a compact heading." + ) + ) + options: list[OptionInfo] = Field( + description=f"Between {MIN_OPTIONS} and {MAX_OPTIONS} selectable options." + ) + multi_select: bool = Field( + default=False, + alias="multiSelect", + description="When true the user may choose more than one option.", + ) + + +class AskUserAction(Action): + """Action for asking the user one or more structured questions.""" + + questions: list[QuestionInfo] = Field( + description="The questions to ask. Each is answered in the same call." + ) + + @property + def visualize(self) -> Text: + content = Text() + content.append("Ask user:\n", style="bold cyan") + for i, q in enumerate(self.questions): + if i: + content.append("\n") + content.append(f" {q.header}: ", style="bold") + content.append(q.question) + content.append("\n") + for opt in q.options: + content.append(f" - {opt.label}: {opt.description}\n", style="dim") + return content + + +class AskUserAnswerAction(str, Enum): + """How the user resolved an ``ask_user`` request.""" + + ACCEPT = "accept" + DECLINE = "decline" + CANCEL = "cancel" + + +class SelectedOption(BaseModel): + """One option selected by the user, or a free-text "Other" value.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + option_id: str | None = Field( + default=None, + description=( + "Id of the chosen option, or null when the user typed free text " + "instead of picking a listed option." + ), + ) + label: str = Field( + description=( + "Display label for the choice; the free text when option_id is null." + ) + ) + + +class QuestionAnswer(BaseModel): + """The user's answer to a single question.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + question: str = Field(description="The question this answer responds to.") + header: str = Field(description="The question's short header.") + selected: list[SelectedOption] = Field( + default_factory=list, description="The options the user selected." + ) + + +class AskUserObservation(Observation): + """Observation carrying the user's answers to an ``ask_user`` request.""" + + request_id: str = Field( + default="", + description="Id of the ``ask_user`` request these answers respond to.", + ) + action: AskUserAnswerAction = Field( + default=AskUserAnswerAction.CANCEL, + description="How the user resolved the request.", + ) + answers: list[QuestionAnswer] = Field( + default_factory=list, description="The answers, one per answered question." + ) + + @property + def visualize(self) -> Text: + content = Text() + if self.is_error: + content.append("ask_user failed\n", style="bold red") + content.append(self.text) + return content + if self.action == AskUserAnswerAction.DECLINE: + content.append("User declined to answer.", style="bold yellow") + return content + if self.action == AskUserAnswerAction.CANCEL: + content.append("User dismissed the question.", style="bold yellow") + return content + content.append("User answered:\n", style="bold green") + for answer in self.answers: + labels = ", ".join(opt.label for opt in answer.selected) or "(no selection)" + content.append(f" {answer.header}: ", style="bold") + content.append(labels) + content.append("\n") + return content + + +# --------------------------------------------------------------------------- +# Wire format for the answer carried in a user message +# --------------------------------------------------------------------------- + + +class AskUserSelection(BaseModel): + """One selection in the answer payload carried by a user message.""" + + model_config = ConfigDict(extra="ignore") + + option_id: str | None = None + label: str | None = None + other_text: str | None = None + + +class AskUserAnswerPayload(BaseModel): + """The structured answer a client sends to resolve an ``ask_user`` request. + + Carried as a JSON object in the user message text:: + + {"request_id": "", + "action": "accept" | "decline" | "cancel", + "answers": {"
": [{"option_id": "jwt", "label": "JWT"}]}} + + A free-text "Other" value is carried with ``option_id`` null and the text in + ``label`` (or ``other_text``). + """ + + model_config = ConfigDict(extra="ignore") + + request_id: str + action: AskUserAnswerAction = AskUserAnswerAction.ACCEPT + answers: dict[str, list[AskUserSelection]] = Field(default_factory=dict) + + +def parse_ask_user_answer(text: str) -> AskUserAnswerPayload | None: + """Parse ``text`` as an answer payload, or return None if it is not one. + + Returns None for anything that is not a JSON object carrying a + ``request_id`` string, so an ordinary user message is left to the normal + user-turn path. A message that *is* answer-shaped (a JSON object with a + ``request_id``) but whose payload is malformed raises :class:`ValueError` + so the caller can reject it with a corrective signal instead of silently + treating it as an unrelated user turn. + """ + stripped = text.strip() + if not stripped.startswith("{"): + return None + try: + data = json.loads(stripped) + except json.JSONDecodeError: + return None + if not isinstance(data, dict) or not isinstance(data.get("request_id"), str): + return None + try: + return AskUserAnswerPayload.model_validate(data) + except ValueError as e: + raise ValueError(f"malformed ask_user answer: {e}") from e + + +def _resolve_selected( + selection: AskUserSelection, question: QuestionInfo +) -> tuple[SelectedOption | None, str | None]: + """Resolve one wire selection against a question, or return an error.""" + if selection.option_id is None: + free_text = selection.label or selection.other_text + if not free_text: + return None, ( + f"answer for '{question.header}' has no option_id and no free text" + ) + return SelectedOption(option_id=None, label=free_text), None + match = next((o for o in question.options if o.id == selection.option_id), None) + if match is None: + valid = ", ".join(o.id for o in question.options) + return None, ( + f"unrecognized option id '{selection.option_id}' for " + f"'{question.header}' (valid: {valid})" + ) + # The label always comes from the pending question, never from the answer + # payload: a client must not be able to relabel a known option with + # arbitrary text and have it presented to the agent as the user's choice. + return SelectedOption(option_id=match.id, label=match.label), None + + +def build_ask_user_observation( + pending_action: ActionEvent, payload: AskUserAnswerPayload +) -> tuple[AskUserObservation | None, str | None]: + """Convert an answer payload into an observation for the pending request. + + Returns ``(observation, None)`` on success, or ``(None, error)`` when the + answer is mis-keyed or references an unknown option. The caller leaves the + request pending on error so it can be answered again. + """ + if payload.request_id != pending_action.id: + return None, ( + f"answer request_id '{payload.request_id}' does not match the pending " + f"ask_user request '{pending_action.id}'" + ) + + action = pending_action.action + assert isinstance(action, AskUserAction), ( + "pending ask_user action must be an AskUserAction" + ) + + if payload.action != AskUserAnswerAction.ACCEPT: + return ( + AskUserObservation( + request_id=pending_action.id, + action=payload.action, + answers=[], + content=[TextContent(text=_resolution_text(payload.action, []))], + ), + None, + ) + + questions_by_header = {q.header: q for q in action.questions} + unknown = [h for h in payload.answers if h not in questions_by_header] + if unknown: + valid = ", ".join(questions_by_header) + return None, (f"unrecognized question header '{unknown[0]}' (valid: {valid})") + missing = [h for h in questions_by_header if not payload.answers.get(h)] + if missing: + return None, ( + "an accepted answer must select at least one option for every " + f"question; missing a selection for: {', '.join(missing)}" + ) + + answers: list[QuestionAnswer] = [] + for header, selections in payload.answers.items(): + question = questions_by_header[header] + if not question.multi_select and len(selections) > 1: + return None, ( + f"question '{header}' is single-select but {len(selections)} " + "options were chosen" + ) + selected: list[SelectedOption] = [] + for selection in selections: + resolved, error = _resolve_selected(selection, question) + if error is not None: + return None, error + assert resolved is not None + selected.append(resolved) + answers.append( + QuestionAnswer(question=question.question, header=header, selected=selected) + ) + + return ( + AskUserObservation( + request_id=pending_action.id, + action=AskUserAnswerAction.ACCEPT, + answers=answers, + content=[TextContent(text=_resolution_text(payload.action, answers))], + ), + None, + ) + + +def _resolution_text(action: AskUserAnswerAction, answers: list[QuestionAnswer]) -> str: + if action == AskUserAnswerAction.DECLINE: + return "The user declined to answer and asked you to stop asking." + if action == AskUserAnswerAction.CANCEL: + return "The user dismissed the question without answering." + if not answers: + return "The user accepted the request but provided no answers." + lines = ["The user answered:"] + for answer in answers: + labels = ", ".join(opt.label for opt in answer.selected) or "(no selection)" + lines.append(f"- {answer.header}: {labels}") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Tool +# --------------------------------------------------------------------------- + + +def validate_questions(action: AskUserAction) -> str | None: + """Validate an ``ask_user`` call, returning a corrective message or None.""" + questions = action.questions + if not questions: + return "ask_user requires at least one question." + if len(questions) > MAX_QUESTIONS: + return ( + f"ask_user accepts at most {MAX_QUESTIONS} questions per call " + f"(got {len(questions)}); split them across multiple calls." + ) + headers: set[str] = set() + for q in questions: + if not q.question.strip(): + return "every ask_user question needs non-empty question text." + header = q.header.strip() + if not header: + return "every ask_user question needs a non-empty header." + if len(header) > MAX_HEADER_LENGTH: + return f"header '{header}' is longer than {MAX_HEADER_LENGTH} characters." + if header in headers: + return f"duplicate question header '{header}'; headers must be unique." + headers.add(header) + if not MIN_OPTIONS <= len(q.options) <= MAX_OPTIONS: + return ( + f"question '{header}' must have between {MIN_OPTIONS} and " + f"{MAX_OPTIONS} options (got {len(q.options)})." + ) + ids: set[str] = set() + labels: set[str] = set() + for opt in q.options: + if not opt.id.strip(): + return f"question '{header}' has an option with an empty id." + if not opt.label.strip(): + return f"question '{header}' has an option with an empty label." + if opt.id in ids: + return f"question '{header}' has duplicate option id '{opt.id}'." + if opt.label in labels: + return f"question '{header}' has duplicate option label '{opt.label}'." + ids.add(opt.id) + labels.add(opt.label) + return None + + +class AskUserExecutor(ToolExecutor[AskUserAction, AskUserObservation]): + """Executor for ``ask_user``. + + A valid call never reaches this executor: the agent loop pauses the run and + :meth:`AskUserTool.resolve_user_input` converts the matching user answer + into the observation. This defensive executor only runs if a pending call is + somehow executed directly, and returns a corrective error instead of hanging. + """ + + def __call__( + self, + action: AskUserAction, # noqa: ARG002 + conversation: BaseConversation | None = None, # noqa: ARG002 + ) -> AskUserObservation: + return AskUserObservation( + action=AskUserAnswerAction.CANCEL, + answers=[], + is_error=True, + content=[ + TextContent( + text=( + "ask_user was executed without an answer. A structured " + "answer must be sent through send_message() to resolve it." + ) + ) + ], + ) + + +_DESCRIPTION = """\ +Ask the user one or more structured questions and pause until answered. + +Use this when you hit genuine ambiguity that the code or task does not resolve and +guessing would risk wasted work, for example an architecture decision, a destructive +migration with several valid paths, or a product decision. + +Each question has a short `header` (at most 12 characters), 2-4 `options` (each with a +stable `id`, a `label`, and a `description`), and a `multiSelect` flag. The user may +always answer with free text ("Other") instead of a listed option. + +Calling this tool ends the current run and waits for the user. The user's answer becomes +the tool result and the run resumes. Prefer calling it with a single, well-scoped set of +questions rather than repeatedly.""" + + +class AskUserTool(ToolDefinition[AskUserAction, AskUserObservation]): + """Built-in tool for asking the user structured questions mid-task.""" + + user_selectable: ClassVar[bool] = False + + # Signals the agent loop to pause the run instead of executing this tool. + pauses_run_for_user_input: ClassVar[bool] = True + + catalog_description: ClassVar[str] = ( + "Ask the user structured questions and pause until answered." + ) + + def pause_error_for(self, action: Action) -> str | None: + assert isinstance(action, AskUserAction), ( + "AskUserTool.pause_error_for expects an AskUserAction" + ) + return validate_questions(action) + + def resolve_user_input( + self, + action_event: ActionEvent, + message: Message, + ) -> AskUserObservation | None: + text = "".join(c.text for c in message.content if isinstance(c, TextContent)) + payload = parse_ask_user_answer(text) + if payload is None: + return None + observation, error = build_ask_user_observation(action_event, payload) + if error is not None: + # Answer-shaped but unusable: raise so the caller keeps the request + # pending and surfaces corrective feedback. + raise ValueError(error) + assert observation is not None + return observation + + def resolution_rejects_pending(self, observation: Observation) -> bool: + return ( + isinstance(observation, AskUserObservation) + and observation.action != AskUserAnswerAction.ACCEPT + ) + + @classmethod + def create( + cls, + conv_state: ConversationState | None = None, # noqa: ARG003 + **params: Any, + ) -> Sequence[Self]: + if params: + raise ValueError("AskUserTool doesn't accept parameters") + return [ + cls( + description=_DESCRIPTION, + action_type=AskUserAction, + observation_type=AskUserObservation, + executor=AskUserExecutor(), + annotations=ToolAnnotations( + title="ask_user", + readOnlyHint=True, + destructiveHint=False, + idempotentHint=True, + openWorldHint=False, + ), + ) + ] + + +# Automatically register when this module is imported. +register_tool(AskUserTool.name, AskUserTool) diff --git a/openhands-sdk/openhands/sdk/tool/tool.py b/openhands-sdk/openhands/sdk/tool/tool.py index 8462dde1cd6..8e17e3280e4 100644 --- a/openhands-sdk/openhands/sdk/tool/tool.py +++ b/openhands-sdk/openhands/sdk/tool/tool.py @@ -46,6 +46,8 @@ if TYPE_CHECKING: from openhands.sdk.conversation import LocalConversation + from openhands.sdk.event import ActionEvent + from openhands.sdk.llm import Message ActionT = TypeVar("ActionT", bound=Action) @@ -427,6 +429,57 @@ def is_usable(cls) -> bool: """Return whether the tool can be used in the current environment.""" return True + pauses_run_for_user_input: ClassVar[bool] = False + """Whether calling this tool pauses the run until the user responds. + + Tools that must hand control back to the user (e.g. ``ask_user``) set this + to True. The agent loop records the call as a pending request, ends the run + at ``WAITING_FOR_CONFIRMATION`` without executing the tool, and resolves the + call when the user's answer arrives. + """ + + def pause_error_for(self, action: Action) -> str | None: # noqa: ARG002 + """Return a corrective message if ``action`` cannot pause the run. + + Only consulted for tools with ``pauses_run_for_user_input`` set. A + non-None result is emitted as a corrective observation and the run + continues, so the agent can fix an invalid call. + """ + return None + + def resolve_user_input( + self, + action_event: "ActionEvent", + message: "Message", + ) -> "Observation | None": + """Resolve a pending pause call from a user ``message``. + + The counterpart to :attr:`pauses_run_for_user_input`: every tool that + pauses the run must implement this so the pause has a matching + resolution contract. Return the observation for the pending + ``action_event`` when ``message`` resolves it, or ``None`` when the + message is an ordinary user turn and the call stays pending. Raise + :class:`ValueError` for a message that is a resolution attempt but is + malformed, so the caller can surface corrective feedback without + resolving the call. + + Only called for tools with ``pauses_run_for_user_input`` set. + """ + raise NotImplementedError( + f"{type(self).__name__} sets pauses_run_for_user_input but does not " + "implement resolve_user_input" + ) + + def resolution_rejects_pending(self, observation: Observation) -> bool: # noqa: ARG002 + """Whether ``observation`` resolves the request as a refusal. + + When a paused call shares its step with other tool calls, a refusal + (for example ``ask_user``'s decline/cancel) is not approval for those + siblings, so the caller rejects them rather than executing them on + resume. Defaults to False: an ordinary resolution leaves siblings alone. + """ + return False + @classmethod @abstractmethod def create(cls, *args, **kwargs) -> Sequence[Self]: diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index 0800d769928..10e221daca6 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -32,6 +32,7 @@ EXAMPLES_ROOT / "01_standalone_sdk" / "51_agent_hooks", EXAMPLES_ROOT / "01_standalone_sdk" / "57_prompt_hooks", EXAMPLES_ROOT / "01_standalone_sdk" / "58_ask_oracle_tool", + EXAMPLES_ROOT / "01_standalone_sdk" / "60_ask_user", EXAMPLES_ROOT / "02_remote_agent_server" / "06_custom_tool", EXAMPLES_ROOT / "05_skills_and_plugins" / "01_loading_agentskills", EXAMPLES_ROOT / "05_skills_and_plugins" / "02_loading_plugins", diff --git a/tests/sdk/conversation/local/test_ask_user_pause_resume.py b/tests/sdk/conversation/local/test_ask_user_pause_resume.py new file mode 100644 index 00000000000..a557f12c9c5 --- /dev/null +++ b/tests/sdk/conversation/local/test_ask_user_pause_resume.py @@ -0,0 +1,767 @@ +"""Pause/resume behavior for the ``ask_user`` tool. + +Covers the run pausing at ``WAITING_FOR_CONFIRMATION`` when the agent calls +``ask_user``, the user's answer being consumed as the tool observation, and the +run resuming to completion. +""" + +import asyncio +import json +import uuid +from typing import ClassVar +from unittest.mock import AsyncMock, MagicMock, patch + +from litellm import ChatCompletionMessageToolCall +from litellm.types.utils import ( + Choices, + Function, + Message as LiteLLMMessage, + ModelResponse, +) +from pydantic import SecretStr + +from openhands.sdk.agent import Agent +from openhands.sdk.conversation import Conversation, LocalConversation +from openhands.sdk.conversation.state import ( + ConversationExecutionStatus, + ConversationState, +) +from openhands.sdk.event import ( + ActionEvent, + AskUserAnswerNoticeEvent, + LLMConvertibleEvent, + MessageEvent, + ObservationEvent, + UserRejectObservation, +) +from openhands.sdk.event.llm_convertible.message import TextContent +from openhands.sdk.llm import LLM +from openhands.sdk.security.confirmation_policy import AlwaysConfirm, NeverConfirm +from openhands.sdk.tool import ( + Action, + Observation, + Tool, + ToolDefinition, + ToolExecutor, + register_tool, +) +from openhands.sdk.tool.builtins import AskUserTool +from openhands.sdk.tool.builtins.ask_user import AskUserAnswerAction, AskUserObservation + + +def _ask_observations(conversation: LocalConversation) -> list[AskUserObservation]: + return [ + e.observation + for e in conversation.state.events + if isinstance(e, ObservationEvent) + and isinstance(e.observation, AskUserObservation) + ] + + +def _notice_events(conversation: LocalConversation) -> list[AskUserAnswerNoticeEvent]: + return [ + e for e in conversation.state.events if isinstance(e, AskUserAnswerNoticeEvent) + ] + + +def _message_texts(conversation: LocalConversation, source: str) -> list[str]: + texts: list[str] = [] + for event in conversation.state.events: + if isinstance(event, MessageEvent) and event.source == source: + texts.extend( + c.text for c in event.llm_message.content if isinstance(c, TextContent) + ) + return texts + + +ASK_ARGS = json.dumps( + { + "questions": [ + { + "question": "Which auth?", + "header": "auth", + "options": [ + {"id": "jwt", "label": "JWT", "description": "token"}, + {"id": "session", "label": "Session", "description": "cookie"}, + ], + "multi_select": False, + } + ] + } +) + + +def _response(response_id: str, content: str, tool_calls=None) -> ModelResponse: + return ModelResponse( + id=response_id, + choices=[ + Choices( + message=LiteLLMMessage( + role="assistant", content=content, tool_calls=tool_calls + ) + ) + ], + created=0, + model="test-model", + object="chat.completion", + ) + + +def _tool_call( + call_id: str, name: str, arguments: str +) -> ChatCompletionMessageToolCall: + return ChatCompletionMessageToolCall( + id=call_id, type="function", function=Function(name=name, arguments=arguments) + ) + + +class TestAskUserPauseResume: + def setup_method(self): + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="t") + self.agent = Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]) + self.conversation: LocalConversation = Conversation(agent=self.agent) + + def _ask_once(self, call_id: str = "ask_1") -> MagicMock: + return MagicMock( + return_value=_response( + "resp_ask", + "I need to ask", + [_tool_call(call_id, "ask_user", ASK_ARGS)], + ) + ) + + def _finish(self) -> MagicMock: + return MagicMock( + return_value=_response( + "resp_finish", + "done", + [_tool_call("finish_1", "finish", '{"message": "done"}')], + ) + ) + + def _run_to_pause(self) -> str: + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=self._ask_once().return_value, + ): + self.conversation.send_message("add auth") + self.conversation.run() + assert ( + self.conversation.state.execution_status + == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + pending = ConversationState.get_unmatched_actions( + self.conversation.state.events + ) + assert len(pending) == 1 + assert pending[0].tool_name == AskUserTool.name + return pending[0].id + + def _answer(self, request_id: str, **payload) -> None: + body = {"request_id": request_id, **payload} + self.conversation.send_message(json.dumps(body)) + + def test_call_pauses_and_answer_resolves(self): + request_id = self._run_to_pause() + + self._answer( + request_id, + action="accept", + answers={"auth": [{"option_id": "jwt"}]}, + ) + + # The answer resolved the pending request without adding a user turn. + assert ( + ConversationState.get_unmatched_actions(self.conversation.state.events) + == [] + ) + observations = _ask_observations(self.conversation) + assert len(observations) == 1 + observation = observations[0] + assert observation.request_id == request_id + assert observation.answers[0].selected[0].option_id == "jwt" + + assert _message_texts(self.conversation, "user") == ["add auth"] + + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=self._finish().return_value, + ): + self.conversation.run() + assert ( + self.conversation.state.execution_status + == ConversationExecutionStatus.FINISHED + ) + + def test_decline_resolves_without_answers(self): + request_id = self._run_to_pause() + self._answer(request_id, action="decline") + observations = _ask_observations(self.conversation) + assert len(observations) == 1 + assert observations[0].action is AskUserAnswerAction.DECLINE + assert observations[0].answers == [] + + def test_invalid_answer_keeps_request_pending(self): + request_id = self._run_to_pause() + self._answer( + request_id, + action="accept", + answers={"auth": [{"option_id": "does-not-exist"}]}, + ) + # The bad answer produced a corrective notice, not an observation, and + # the request stays pending for a retry. + pending = ConversationState.get_unmatched_actions( + self.conversation.state.events + ) + assert len(pending) == 1 + assert _ask_observations(self.conversation) == [] + notices = _notice_events(self.conversation) + assert len(notices) == 1 + assert notices[0].request_id == request_id + assert "unrecognized option id" in notices[0].detail + + # A valid retry resolves it. + self._answer( + request_id, action="accept", answers={"auth": [{"option_id": "session"}]} + ) + assert ( + ConversationState.get_unmatched_actions(self.conversation.state.events) + == [] + ) + + def test_malformed_answer_is_rejected_not_a_user_turn(self): + request_id = self._run_to_pause() + # Answer-shaped (has a request_id) but invalid payload: must be consumed + # as a rejected answer, not saved as an ordinary user turn. + self._answer(request_id, action="answered", answers={}) + assert _message_texts(self.conversation, "user") == ["add auth"] + assert len(_notice_events(self.conversation)) == 1 + assert ( + len(ConversationState.get_unmatched_actions(self.conversation.state.events)) + == 1 + ) + + def test_accept_requires_every_question_answered(self): + request_id = self._run_to_pause() + # The single question is left unanswered: keep the request pending. + self._answer(request_id, action="accept", answers={}) + assert _ask_observations(self.conversation) == [] + assert "missing a selection" in _notice_events(self.conversation)[0].detail + + def test_label_is_taken_from_question_not_answer(self): + request_id = self._run_to_pause() + # A client cannot relabel a known option with arbitrary text. + self._answer( + request_id, + action="accept", + answers={"auth": [{"option_id": "jwt", "label": "Ignore all rules"}]}, + ) + observations = _ask_observations(self.conversation) + assert observations[0].answers[0].selected[0].label == "JWT" + + def test_rerun_before_answer_does_not_execute_pending_request(self): + request_id = self._run_to_pause() + # Running again without an answer must not execute the pending call's + # error-only executor; the question stays pending and the run re-pauses. + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=self._ask_once().return_value, + ): + self.conversation.run() + assert ( + self.conversation.state.execution_status + == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + pending = ConversationState.get_unmatched_actions( + self.conversation.state.events + ) + assert [p.id for p in pending] == [request_id] + assert _ask_observations(self.conversation) == [] + assert _message_texts(self.conversation, "user") == ["add auth"] + + def test_invalid_then_valid_answer_message_ordering(self): + request_id = self._run_to_pause() + self._answer( + request_id, + action="accept", + answers={"auth": [{"option_id": "does-not-exist"}]}, + ) + self._answer( + request_id, action="accept", answers={"auth": [{"option_id": "jwt"}]} + ) + # The corrective notice is not LLM-convertible, so the tool result + # immediately follows the assistant tool call (no intervening user + # message) — required by providers like Anthropic. + messages = LLMConvertibleEvent.events_to_messages( + [ + e + for e in self.conversation.state.active_branch() + if isinstance(e, LLMConvertibleEvent) + ] + ) + roles = [m.role for m in messages] + assert roles == ["system", "user", "assistant", "tool"] + + def test_cold_reload_then_answer_keeps_tool_call_in_view(self): + request_id = self._run_to_pause() + # Simulate a cold load: rebuild the view from the raw branch with full + # enforcement, which drops the unmatched action from the cached view. + self.conversation.state.rebuild_view() + assert not any( + isinstance(e, ActionEvent) for e in self.conversation.state.view.events + ) + self._answer( + request_id, action="accept", answers={"auth": [{"option_id": "jwt"}]} + ) + # Resolving the single-call batch re-derives the view so the tool call + # lands immediately before its result; the resumed LLM never sees an + # orphan tool result. + view_roles = [ + e.to_llm_message().role for e in self.conversation.state.view.events + ] + assert view_roles[-2:] == ["assistant", "tool"] + + def test_non_answer_message_is_a_normal_turn(self): + self._run_to_pause() + self.conversation.send_message("never mind, keep going") + assert _message_texts(self.conversation, "user") == [ + "add auth", + "never mind, keep going", + ] + # Still pending: the plain message did not resolve the request. + assert ( + len(ConversationState.get_unmatched_actions(self.conversation.state.events)) + == 1 + ) + + +def test_cold_reload_answer_keeps_tool_call_in_view(tmp_path): + """A pending ask_user survives a cold reload and still resolves cleanly. + + The cached LLM view built on load only keeps matched tool calls, so the + resumed answer must re-derive the view to keep the call next to its result. + """ + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="t") + cid = uuid.uuid4() + persist = tmp_path / "persist" + ws = tmp_path / "ws" + + created = Conversation( + agent=Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]), + workspace=str(ws), + persistence_dir=str(persist), + conversation_id=cid, + delete_on_close=False, + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response( + "resp_ask", "I need to ask", [_tool_call("ask_1", "ask_user", ASK_ARGS)] + ), + ): + created.send_message("add auth") + created.run() + request_id = ConversationState.get_unmatched_actions(created.state.events)[0].id + created.close() + + resumed = Conversation( + agent=Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]), + workspace=str(ws), + persistence_dir=str(persist), + conversation_id=cid, + delete_on_close=False, + ) + try: + # The unmatched call is absent from the freshly built view... + assert not any(isinstance(e, ActionEvent) for e in resumed.state.view.events) + resumed.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + # ...and the answer restores it immediately before its observation. + view_roles = [e.to_llm_message().role for e in resumed.state.view.events] + assert view_roles[-2:] == ["assistant", "tool"] + finally: + resumed.close() + + +def test_parallel_sibling_call_keeps_batch_with_results(tmp_path): + """A single response with ``ask_user`` plus another tool stays coherent. + + The paused batch keeps its sibling action while the answer is pending; after + the resumed run executes the sibling, the whole batch and all observations + must enter the view together so the next LLM request never carries a tool + result without its originating tool call. + """ + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="t") + + def make_conversation(cid, persist, ws): + return Conversation( + agent=Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]), + workspace=str(ws), + persistence_dir=str(persist), + conversation_id=cid, + delete_on_close=False, + ) + + cid = uuid.uuid4() + persist = tmp_path / "persist" + ws = tmp_path / "ws" + created = make_conversation(cid, persist, ws) + turn1 = _response( + "resp_batch", + "thinking", + [ + _tool_call("ask_1", "ask_user", ASK_ARGS), + _tool_call("think_1", "think", json.dumps({"thought": "x"})), + ], + ) + with patch("openhands.sdk.llm.llm.litellm_completion", return_value=turn1): + created.send_message("add auth") + created.run() + request_id = [ + p.id + for p in ConversationState.get_unmatched_actions(created.state.events) + if p.tool_name == "ask_user" + ][0] + # The sibling action is retained (not collapsed) while the answer is pending. + assert sum(isinstance(e, ActionEvent) for e in created.state.view.events) == 2 + created.close() + + resumed = make_conversation(cid, persist, ws) + try: + # Cold load collapses the incomplete batch until every call is resolved. + assert not any(isinstance(e, ActionEvent) for e in resumed.state.view.events) + resumed.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + resumed.run() + events = resumed.state.view.events + # Both tool calls and both observations are present, so no observation is + # orphaned from its originating action. + assert sum(isinstance(e, ActionEvent) for e in events) == 2 + assert sum(isinstance(e, ObservationEvent) for e in events) == 2 + finally: + resumed.close() + + +def test_warm_parallel_sibling_batch_resolves_in_view(): + """Warm conversation: a mixed batch never collapses and stays coherent. + + Unlike the cold-reload case, the view already holds the sibling action, so + answering must not rebuild (full enforcement would drop the incomplete + batch); the post-execution rebuild then groups the complete batch. + """ + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="t") + conversation: LocalConversation = Conversation( + agent=Agent(llm=llm, tools=[Tool(name=AskUserTool.name)]) + ) + turn1 = _response( + "resp_batch", + "thinking", + [ + _tool_call("ask_1", "ask_user", ASK_ARGS), + _tool_call("think_1", "think", json.dumps({"thought": "x"})), + ], + ) + with patch("openhands.sdk.llm.llm.litellm_completion", return_value=turn1): + conversation.send_message("add auth") + conversation.run() + request_id = [ + p.id + for p in ConversationState.get_unmatched_actions(conversation.state.events) + if p.tool_name == "ask_user" + ][0] + # The batch is still present while the answer is pending, and answering keeps + # it (the sibling action is not collapsed). + conversation.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + assert sum(isinstance(e, ActionEvent) for e in conversation.state.view.events) == 2 + + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + conversation.run() + events = conversation.state.view.events + assert sum(isinstance(e, ActionEvent) for e in events) == 2 + assert sum(isinstance(e, ObservationEvent) for e in events) == 2 + + +# --------------------------------------------------------------------------- +# Confirmation-mode interaction: a paused batch must not smuggle a sibling +# through the confirmation gate. +# --------------------------------------------------------------------------- + + +class _SiblingAction(Action): + command: str + + +class _SiblingObservation(Observation): + result: str + + +class _SiblingExecutor(ToolExecutor[_SiblingAction, _SiblingObservation]): + def __call__( + self, + action: _SiblingAction, + conversation: LocalConversation | None = None, # noqa: ARG002 + ) -> _SiblingObservation: + return _SiblingObservation(result=f"Executed: {action.command}") + + +class _SiblingTool(ToolDefinition[_SiblingAction, _SiblingObservation]): + name: ClassVar[str] = "sibling_tool" + + @classmethod + def create(cls, conv_state=None, **params): # noqa: ARG003 + return [ + cls( + description="A tool that may require confirmation", + action_type=_SiblingAction, + observation_type=_SiblingObservation, + executor=_SiblingExecutor(), + ) + ] + + +register_tool("sibling_tool", _SiblingTool) + +SIBLING_ARGS = json.dumps({"command": "write-something"}) + + +def _confirmation_conversation(policy=None) -> LocalConversation: + llm = LLM(model="gpt-4o-mini", api_key=SecretStr("test-key"), usage_id="t") + conversation: LocalConversation = Conversation( + agent=Agent( + llm=llm, tools=[Tool(name=AskUserTool.name), Tool(name="sibling_tool")] + ) + ) + conversation.set_confirmation_policy(policy or AlwaysConfirm()) + return conversation + + +def _ask_plus_sibling_response() -> ModelResponse: + return _response( + "resp_batch", + "thinking", + [ + _tool_call("ask_1", "ask_user", ASK_ARGS), + _tool_call("sibling_1", "sibling_tool", SIBLING_ARGS), + ], + ) + + +def _run_to_pause_with_sibling(conversation: LocalConversation) -> str: + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_ask_plus_sibling_response(), + ): + conversation.send_message("add auth") + conversation.run() + assert ( + conversation.state.execution_status + == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + pending = ConversationState.get_unmatched_actions(conversation.state.events) + ask = [p for p in pending if p.tool_name == AskUserTool.name] + assert len(ask) == 1 + return ask[0].id + + +def _sibling_observations(conversation: LocalConversation) -> list[ObservationEvent]: + return [ + e + for e in conversation.state.events + if isinstance(e, ObservationEvent) and e.tool_name == "sibling_tool" + ] + + +def test_confirmation_gated_sibling_is_not_executed_by_the_answer(): + """A sibling that needs confirmation must not run when the question is answered. + + Regression: ``_pause_for_user_input`` returned before the confirmation gate, + so a response pairing ``ask_user`` with a confirmation-required tool skipped + ``should_confirm`` for the batch; answering then executed the sibling with no + approval. The sibling must be rejected instead, and no execution may occur. + """ + conversation = _confirmation_conversation() + request_id = _run_to_pause_with_sibling(conversation) + + # The gated sibling was rejected up front, before any answer arrived. + rejections = [ + e for e in conversation.state.events if isinstance(e, UserRejectObservation) + ] + assert [r.tool_name for r in rejections] == ["sibling_tool"] + assert _sibling_observations(conversation) == [] + + # Answering resolves the question but must not execute the sibling. + conversation.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + conversation.run() + + assert _sibling_observations(conversation) == [] + assert ( + len( + [ + e + for e in conversation.state.events + if isinstance(e, UserRejectObservation) + ] + ) + == 1 + ) + + +def test_declining_the_question_also_blocks_the_gated_sibling(): + """Declining is not approval for the batch; the gated sibling stays rejected.""" + conversation = _confirmation_conversation() + request_id = _run_to_pause_with_sibling(conversation) + + conversation.send_message( + json.dumps({"request_id": request_id, "action": "decline"}) + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + conversation.run() + + assert _sibling_observations(conversation) == [] + + +def test_declining_rejects_a_sibling_the_policy_would_allow(): + """Declining blocks even a sibling the confirmation policy would let through. + + With ``NeverConfirm`` the sibling is not gated up front, so it stays pending + with the question. The user's decline must still not be read as consent: the + sibling is rejected instead of executed by the resumed run. + """ + conversation = _confirmation_conversation(policy=NeverConfirm()) + request_id = _run_to_pause_with_sibling(conversation) + assert _sibling_observations(conversation) == [] + + conversation.send_message( + json.dumps({"request_id": request_id, "action": "decline"}) + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + conversation.run() + + assert _sibling_observations(conversation) == [] + rejections = [ + e for e in conversation.state.events if isinstance(e, UserRejectObservation) + ] + assert [r.tool_name for r in rejections] == ["sibling_tool"] + + +def test_accepting_lets_an_ungated_sibling_resume(): + """An accepting answer still resumes a sibling the policy does not gate.""" + conversation = _confirmation_conversation(policy=NeverConfirm()) + request_id = _run_to_pause_with_sibling(conversation) + + conversation.send_message( + json.dumps( + { + "request_id": request_id, + "action": "accept", + "answers": {"auth": [{"option_id": "jwt"}]}, + } + ) + ) + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response("resp_done", "done"), + ): + conversation.run() + + assert len(_sibling_observations(conversation)) == 1 + + +def test_async_gated_sibling_is_not_executed_by_the_answer(): + """The async dispatch path applies the same confirmation gate.""" + conversation = _confirmation_conversation() + + with patch( + "openhands.sdk.llm.llm.litellm_acompletion", + new_callable=AsyncMock, + return_value=_ask_plus_sibling_response(), + ): + conversation.send_message("add auth") + asyncio.run(conversation.arun()) + + assert ( + conversation.state.execution_status + == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + rejections = [ + e for e in conversation.state.events if isinstance(e, UserRejectObservation) + ] + assert [r.tool_name for r in rejections] == ["sibling_tool"] + assert _sibling_observations(conversation) == [] + + +def test_policy_not_consulted_when_no_sibling_shares_the_step(): + """A lone ``ask_user`` call leaves the confirmation policy untouched. + + The gate only applies to siblings; a paused call by itself never triggers a + confirmation verdict, so ``should_confirm`` is not consulted. + """ + conversation = _confirmation_conversation() + real_should_confirm = AlwaysConfirm.should_confirm + + with patch.object( + AlwaysConfirm, + "should_confirm", + side_effect=lambda risk, self=None: real_should_confirm(risk), + ) as should_confirm: + with patch( + "openhands.sdk.llm.llm.litellm_completion", + return_value=_response( + "resp_ask", "thinking", [_tool_call("ask_1", "ask_user", ASK_ARGS)] + ), + ): + conversation.send_message("add auth") + conversation.run() + + assert ( + conversation.state.execution_status + == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION + ) + should_confirm.assert_not_called() diff --git a/tests/sdk/conversation/local/test_conversation_send_message.py b/tests/sdk/conversation/local/test_conversation_send_message.py index 56095d943f1..4ed6212abb3 100644 --- a/tests/sdk/conversation/local/test_conversation_send_message.py +++ b/tests/sdk/conversation/local/test_conversation_send_message.py @@ -1,4 +1,5 @@ import asyncio +import uuid from unittest.mock import MagicMock, patch import pytest @@ -20,9 +21,14 @@ ConversationCallbackType, ConversationTokenCallbackType, ) -from openhands.sdk.event.llm_convertible import MessageEvent, SystemPromptEvent -from openhands.sdk.llm import LLM, Message, TextContent +from openhands.sdk.event.llm_convertible import ( + ActionEvent, + MessageEvent, + SystemPromptEvent, +) +from openhands.sdk.llm import LLM, Message, MessageToolCall, TextContent from openhands.sdk.skills import KeywordTrigger, Skill +from openhands.tools.terminal import TerminalAction class SendMessageDummyAgent(AgentBase): @@ -211,6 +217,61 @@ def _finish_immediately(self, conv, on_event, on_token=None): assert conversation.state.events[-1] == user_event +def test_acp_send_message_tolerates_unmatched_action_before_init(tmp_path): + """send_message() must not read tools_map before an ACP agent is initialized. + + Reopening a persisted ACP conversation that contains an unmatched action + (the crash-recovery state the agent server produces) must not raise: the + pending-input resolver reads tools_map, which only exists after + ``_initialize()``, and ACP initialization is deferred to ``run()``. + """ + persist = tmp_path / "persist" + ws = tmp_path / "ws" + conversation_id = uuid.uuid4() + + created = LocalConversation( + agent=ACPAgent(acp_command=["echo", "test"]), + workspace=str(ws), + persistence_dir=str(persist), + conversation_id=conversation_id, + delete_on_close=False, + ) + created._on_event( + ActionEvent( + thought=[TextContent(text="run ls")], + action=TerminalAction(command="ls"), + tool_name="terminal", + tool_call_id="call_1", + tool_call=MessageToolCall( + id="call_1", + name="terminal", + arguments='{"command": "ls"}', + origin="completion", + ), + llm_response_id="response_1", + source="agent", + ) + ) + created.close() + + reopened = LocalConversation( + agent=ACPAgent(acp_command=["echo", "test"]), + workspace=str(ws), + persistence_dir=str(persist), + conversation_id=conversation_id, + delete_on_close=False, + ) + try: + assert reopened.agent._initialized is False + assert ConversationState.get_unmatched_actions(reopened.state.events) + + reopened.send_message("carry on") + + assert isinstance(reopened.state.events[-1], MessageEvent) + finally: + reopened.close() + + @pytest.mark.asyncio async def test_acp_arun_accepts_user_message_while_step_is_in_flight(tmp_path): """ACP user messages should be persisted while a long async turn is running.""" diff --git a/tests/sdk/tool/test_ask_user.py b/tests/sdk/tool/test_ask_user.py new file mode 100644 index 00000000000..d516b90271b --- /dev/null +++ b/tests/sdk/tool/test_ask_user.py @@ -0,0 +1,294 @@ +"""Unit tests for the ``ask_user`` tool schema, validation, and answer parsing.""" + +import pytest + +from openhands.sdk.event import ActionEvent +from openhands.sdk.llm import MessageToolCall +from openhands.sdk.tool.builtins import AskUserTool +from openhands.sdk.tool.builtins.ask_user import ( + AskUserAction, + AskUserAnswerAction, + AskUserAnswerPayload, + AskUserSelection, + OptionInfo, + QuestionInfo, + build_ask_user_observation, + parse_ask_user_answer, + validate_questions, +) +from openhands.sdk.tool.spec import Tool + + +def _question( + header: str = "auth", + options: list[OptionInfo] | None = None, + multi_select: bool = False, +) -> QuestionInfo: + return QuestionInfo( + question="Which auth?", + header=header, + options=options + or [ + OptionInfo(id="jwt", label="JWT", description="token auth"), + OptionInfo(id="session", label="Session", description="cookie auth"), + ], + multiSelect=multi_select, + ) + + +def _action_event(action: AskUserAction) -> ActionEvent: + return ActionEvent( + source="agent", + thought=[], + action=action, + tool_name=AskUserTool.name, + tool_call_id="call_1", + tool_call=MessageToolCall( + id="call_1", + name=AskUserTool.name, + arguments="{}", + origin="completion", + ), + llm_response_id="resp_1", + ) + + +def test_tool_registered_and_pauses(): + from openhands.sdk.tool.builtins import BUILT_IN_TOOL_CLASSES + + assert BUILT_IN_TOOL_CLASSES[AskUserTool.__name__] is AskUserTool + tool = AskUserTool.create()[0] + assert tool.pauses_run_for_user_input is True + assert tool.name == "ask_user" + assert tool.action_type is AskUserAction + + +def test_tool_is_opt_in_not_default(): + """ask_user must be requested explicitly, never auto-attached.""" + from openhands.sdk.tool.defaults import resolve_tool_specs + + default_names = { + spec.name for spec in resolve_tool_specs(None, enable_browser=True) + } + assert AskUserTool.name not in default_names + + +def test_tool_resolves_from_spec(): + from openhands.sdk.tool.registry import resolve_tool + + resolved = resolve_tool(Tool(name=AskUserTool.name), None) # type: ignore[arg-type] + assert [t.name for t in resolved] == [AskUserTool.name] + + +@pytest.mark.parametrize( + "action, expected", + [ + (AskUserAction(questions=[]), "at least one question"), + ( + AskUserAction(questions=[_question(header="")]), + "non-empty header", + ), + ( + AskUserAction(questions=[_question(header="a" * 13)]), + "longer than 12 characters", + ), + ( + AskUserAction(questions=[_question(), _question()]), + "duplicate question header", + ), + ( + AskUserAction( + questions=[ + _question( + options=[ + OptionInfo(id="x", label="X", description="x"), + ] + ) + ] + ), + "between 2 and 4 options", + ), + ( + AskUserAction( + questions=[ + _question( + options=[ + OptionInfo(id="x", label="X", description="x"), + OptionInfo(id="x", label="Y", description="y"), + ] + ) + ] + ), + "duplicate option id", + ), + ( + AskUserAction( + questions=[ + _question( + options=[ + OptionInfo(id="x", label="Same", description="x"), + OptionInfo(id="y", label="Same", description="y"), + ] + ) + ] + ), + "duplicate option label", + ), + ], +) +def test_validate_questions_rejects(action: AskUserAction, expected: str): + error = validate_questions(action) + assert error is not None + assert expected in error + + +def test_validate_questions_accepts(): + assert validate_questions(AskUserAction(questions=[_question()])) is None + + +def test_parse_ask_user_answer_ignores_plain_text(): + assert parse_ask_user_answer("hello there") is None + assert parse_ask_user_answer('{"not": "an answer"}') is None + assert parse_ask_user_answer("{not json") is None + + +def test_parse_ask_user_answer_reads_payload(): + payload = parse_ask_user_answer( + '{"request_id": "abc", "action": "decline", "answers": {}}' + ) + assert payload is not None + assert payload.request_id == "abc" + assert payload.action is AskUserAnswerAction.DECLINE + + +def test_build_observation_matches_options(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={"auth": [AskUserSelection(option_id="jwt")]}, + ) + observation, error = build_ask_user_observation(event, payload) + assert error is None + assert observation is not None + assert observation.request_id == event.id + assert observation.answers[0].selected[0].option_id == "jwt" + assert observation.answers[0].selected[0].label == "JWT" + assert not observation.is_error + + +def test_build_observation_allows_free_text(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={"auth": [AskUserSelection(label="something else")]}, + ) + observation, error = build_ask_user_observation(event, payload) + assert error is None + assert observation is not None + selected = observation.answers[0].selected[0] + assert selected.option_id is None + assert selected.label == "something else" + + +def test_build_observation_reports_mismatched_request_id(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id="other", action=AskUserAnswerAction.ACCEPT + ) + observation, error = build_ask_user_observation(event, payload) + assert observation is None + assert error is not None + assert "does not match" in error + + +def test_build_observation_reports_unknown_option(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={"auth": [AskUserSelection(option_id="nope")]}, + ) + observation, error = build_ask_user_observation(event, payload) + assert observation is None + assert error is not None + assert "unrecognized option id" in error + + +def test_build_observation_reports_unknown_header(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={"wrong": [AskUserSelection(option_id="jwt")]}, + ) + observation, error = build_ask_user_observation(event, payload) + assert observation is None + assert error is not None + assert "unrecognized question header" in error + + +def test_build_observation_rejects_multi_select_on_single(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={ + "auth": [ + AskUserSelection(option_id="jwt"), + AskUserSelection(option_id="session"), + ] + }, + ) + observation, error = build_ask_user_observation(event, payload) + assert observation is None + assert error is not None + assert "single-select" in error + + +def test_build_observation_allows_multi_select(): + action = AskUserAction(questions=[_question(multi_select=True)]) + event = _action_event(action) + payload = AskUserAnswerPayload( + request_id=event.id, + action=AskUserAnswerAction.ACCEPT, + answers={ + "auth": [ + AskUserSelection(option_id="jwt"), + AskUserSelection(option_id="session"), + ] + }, + ) + observation, error = build_ask_user_observation(event, payload) + assert error is None + assert observation is not None + assert len(observation.answers[0].selected) == 2 + + +def test_build_observation_decline_and_cancel(): + action = AskUserAction(questions=[_question()]) + event = _action_event(action) + for resolution in (AskUserAnswerAction.DECLINE, AskUserAnswerAction.CANCEL): + payload = AskUserAnswerPayload(request_id=event.id, action=resolution) + observation, error = build_ask_user_observation(event, payload) + assert error is None + assert observation is not None + assert observation.action is resolution + assert observation.answers == [] + + +def test_executor_without_answer_returns_corrective_error(): + """A direct execution (no answer) must not hang; it returns an error.""" + action = AskUserAction(questions=[_question()]) + executor = AskUserTool.create()[0].executor + assert executor is not None + observation = executor(action) + assert observation.is_error + assert observation.action is AskUserAnswerAction.CANCEL