Skip to content

feat(sdk): add ask_user tool for structured mid-task questions - #5574

Open
analisaperlengkapan wants to merge 9 commits into
OpenHands:mainfrom
analisaperlengkapan:feat/ask-user-tool
Open

analisaperlengkapan wants to merge 9 commits into
OpenHands:mainfrom
analisaperlengkapan:feat/ask-user-tool

Conversation

@analisaperlengkapan

@analisaperlengkapan analisaperlengkapan commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

The ask_user tool closes the gap where an agent has to guess when it hits
mid-task ambiguity. This is the first slice of #5570 (the tool plus pause/resume
only); the dedicated transport and the Canvas dialog follow in their own issues.
Please review.


AGENT:

Why

When the agent hits genuine ambiguity mid-task it has no structured way to ask the
user: it either guesses (risking wasted work) or drops a question into a chat
message, which does not pause execution and offers no clear choices. This is the
first, self-contained slice of issue #5570: a first-class SDK ask_user tool that
pauses the run and is resolved by the user's answer.

Summary

  • Add the ask_user built-in tool (AskUserTool) with AskUserAction carrying
    questions: list[QuestionInfo], where each QuestionInfo has question,
    short header, 2-4 options (id/label/description), and a multiSelect
    flag (JSON schema emits multiSelect, and snake_case multi_select is accepted).
  • Reuse the confirmation pause/resume shape: the call ends the run at
    WAITING_FOR_CONFIRMATION with one pending request, and the next user message
    via send_message() that parses as an answer for that request becomes the tool
    observation (consumed as the tool result, not appended as an unrelated turn).
    No new Agent Server endpoint, event type, or serialized status value.
  • Add AskUserObservation (with request_id, action in
    accept/decline/cancel, and per-question answers keyed by stable option id
    with the label for display; free-text "Other" uses a null option id).
  • Keep parallel tool batches coherent across the pause: when the same LLM response
    also calls other tools, they stay 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 originating tool call.
  • Honor the confirmation policy for the paused batch: a sibling the policy would
    gate is rejected up front (it cannot run on the answer, which is not an
    approval), and a decline/cancel answer rejects the remaining siblings too,
    since a refusal is not consent for the rest of the batch.
  • Invalid calls and malformed/mis-keyed/stale answers produce a corrective
    observation instead of a crash.

Issue Number

Closes #5570

How to Test

Unit tests (SDK tool + pause/resume path):

uv run pytest tests/sdk/tool/test_ask_user.py \
  tests/sdk/conversation/local/test_ask_user_pause_resume.py -q
# 41 passed

Full SDK suite:

uv run pytest tests/sdk -q
# 7500 passed, 7 skipped, 19 deselected, 12 xfailed

Pre-commit (ruff format/lint, pycodestyle, pyright, import/tool-registration gates):

uv run pre-commit run --files \
  openhands-sdk/openhands/sdk/tool/builtins/ask_user.py \
  openhands-sdk/openhands/sdk/tool/builtins/__init__.py \
  openhands-sdk/openhands/sdk/tool/tool.py \
  openhands-sdk/openhands/sdk/agent/agent.py \
  openhands-sdk/openhands/sdk/agent/response_dispatch.py \
  openhands-sdk/openhands/sdk/conversation/impl/local_conversation.py \
  tests/sdk/tool/test_ask_user.py \
  tests/sdk/conversation/local/test_ask_user_pause_resume.py \
  examples/01_standalone_sdk/60_ask_user/main.py \
  tests/examples/test_examples.py
# all hooks Passed

End-to-end live run (real LocalConversation, scripted TestLLM, no network):

uv run python .pr/ask_user_live_demo.py

This exercises the full flow: the agent calls ask_user, the run pauses at
WAITING_FOR_CONFIRMATION with one pending request, the answer sent through
send_message() is consumed as the tool observation (the user-turn history keeps
only the original task), and the run resumes to FINISHED. A second scenario
shows an invalid call (1 option) producing a corrective AgentErrorEvent and the
agent recovering. A third scenario turns on AlwaysConfirm and puts ask_user
and a risky risky_write in one response: the run pauses, the sibling is
rejected, and answering the question does not execute it.

Parallel-batch regression (an ask_user call sharing one LLM response with another
tool) is covered by test_parallel_sibling_call_keeps_batch_with_results (cold
reload) and test_warm_parallel_sibling_batch_resolves_in_view (warm
conversation), which reproduce the orphaned-tool-result failure and assert the
whole batch and all observations land together. Confirmation interaction is
covered by test_confirmation_gated_sibling_is_not_executed_by_the_answer,
test_declining_the_question_also_blocks_the_gated_sibling,
test_declining_rejects_a_sibling_the_policy_would_allow,
test_policy_not_consulted_when_no_sibling_shares_the_step, and
test_async_gated_sibling_is_not_executed_by_the_answer.

Regression fix (deferred ACP init): LocalConversation.send_message() runs the
pending-input resolver before the agent is initialized, and ACP init is deferred
to run(). The resolver read self.agent.tools_map, which raises for an
uninitialized agent, so send_message() failed on a reopened conversation whose
log holds an unmatched action (the crash-recovery state the agent server
produces). _tool_pauses_for_user_input now returns False when the agent is
not initialized; the initialized path is unchanged. Covered by
test_acp_send_message_tolerates_unmatched_action_before_init, which reopens a
persisted ACP conversation containing an unmatched action and asserts
send_message() succeeds (it fails on the pre-fix head).

uv run pytest tests/sdk/conversation/local/test_conversation_send_message.py -q
# 26 passed
uv run pytest tests/sdk -q
# 7509 passed, 19 deselected, 12 xfailed

Example (LLM-backed, requires a key):

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

Video/Screenshots

Live-run stdout from .pr/ask_user_live_demo.py (trimmed):

== turn 1: agent calls ask_user ==
status after run: ConversationExecutionStatus.WAITING_FOR_CONFIRMATION
pending requests: [('ask_user', '72228041-1933-4f09-9e35-1513e5074775')]

== turn 2: user answers via send_message() ==
pending after answer: []
ask_user observations: [{'content': [{'text': 'The user answered:\n- auth: JWT', ...}], 'request_id': '72228041-...', 'action': <AskUserAnswerAction.ACCEPT: 'accept'>, 'answers': [{'question': 'Which auth?', 'header': 'auth', 'selected': [{'option_id': 'jwt', 'label': 'JWT'}]}]}]
user turns in history: ['add auth to the API']

== turn 3: resume the run ==
final status: ConversationExecutionStatus.FINISHED
LIVE DEMO PASSED

== scenario 2: invalid ask_user call (1 option) ==
corrective errors: ["question 'auth' must have between 2 and 4 options (got 1)."]
SCENARIO 2 PASSED

== scenario 3: ask_user + risky sibling under AlwaysConfirm ==
status after run: ConversationExecutionStatus.WAITING_FOR_CONFIRMATION
rejected siblings: ['risky_write']
final status: ConversationExecutionStatus.FINISHED
SCENARIO 3 PASSED

Design Doc

The change is small and additive, so no separate design doc is included; the
mechanism is described in the module docstring of
openhands-sdk/openhands/sdk/tool/builtins/ask_user.py.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

Scope matches issue #5570 (PR 1): the SDK tool plus pause/resume resolution only.
Explicit non-goals deferred to follow-ups: the dedicated request/response event
pair and Agent Server endpoint (#5566), the clients/typescript method (#5566),
the Agent Canvas dialog (OpenHands/OpenHands), an interactive capability flag,
and the timeout -> cancel path.

Non-interactive handling is deferred in this slice: the tool is opt-in (not in
BUILT_IN_TOOLS, so it is not part of the default tool set) and is not registered
in headless/eval runs.

  • pauses_run_for_user_input / pause_error_for() are added to the base
    ToolDefinition so a tool can request the pause without a bespoke agent-loop
    branch per tool.
  • ask_user is resolved from WAITING_FOR_CONFIRMATION by matching the pending
    request's action-event id as request_id; the pending request is derived from
    the event log, so it survives a resume and needs no new persisted state.
  • A batch that mixes ask_user with sibling tool calls is kept intact while the
    answer is pending, and both step paths re-derive the view after the resumed
    pending actions execute, so a complete batch and all its results enter the view
    together (an incomplete batch is dropped rather than orphaned).
  • The pause path applies the confirmation policy to the batch's non-pause siblings
    (_gate_paused_siblings / _agate_paused_siblings) and rejects any gated
    sibling, so a risky call cannot ride along beside ask_user and run on the
    answer without approval. resolution_rejects_pending lets a pausing tool
    declare a refusal, so a decline/cancel answer also rejects the remaining
    siblings.

Companion docs PR

The repo asks public SDK changes to land with a docs PR. The current token
cannot push to OpenHands/docs, so the ready-to-apply guide
(sdk/guides/agent-ask-user.mdx) plus its docs.json registration are staged
under .pr/agent-ask-user.docs-guide.mdx and
.pr/agent-ask-user.docs-json.patch for a maintainer to land.

@analisaperlengkapan can click here to continue refining the PR

Add a first-class `ask_user` SDK tool that lets an agent pause mid-task and
ask one or more structured questions in a single call. Each question carries a
short header, 2-4 labelled options (stable id + label + description), a
`multiSelect` flag, and an always-available free-text "Other" escape hatch.

The call reuses the confirmation pause/resume shape: the run ends at
`WAITING_FOR_CONFIRMATION` with one pending request recorded, and the next user
message sent through `send_message()` that parses as an answer for that request
is consumed as the tool observation and resumes the run (it is not appended as
an unrelated user turn). No new Agent Server endpoint, event type, or serialized
status value.

Answers key by stable option id, are matched to the pending request by
`request_id`, and carry the label for display; a free-text value uses a null
option id. `accept`/`decline`/`cancel` are distinguishable in the observation.
Invalid calls and malformed/mis-keyed/stale answers produce a corrective
observation rather than a crash.

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR contains a .pr/ directory with temporary PR-specific documents. The directory will be automatically removed after this PR merges to main through a cleanup PR.

The repo requires a companion PR to OpenHands/docs for public SDK changes, but
the current token cannot push there. Stage the ready-to-apply guide and
docs.json patch under .pr/ so a maintainer can land it.

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
- Trust only the option id: the observation label always comes from the
  pending question, so an answer cannot relabel a known option with
  arbitrary text (CWE-20).
- Reject answer-shaped but malformed payloads instead of treating them as
  ordinary user turns; keep the request pending and emit a non-LLM
  AskUserAnswerNoticeEvent so the tool result still directly follows its
  tool call (Anthropic-safe ordering).
- Require an accepted answer to select at least one option for every
  question.
- Do not execute a pending pause-for-user-input call on re-run; re-signal
  WAITING_FOR_CONFIRMATION so the question is not silently dropped.
- Re-derive the cached LLM view when an answer resolves a call so a
  cold-loaded (unmatched) action is restored next to its observation.
- Resolve pending answers before per-turn skill activation, and give the
  pause/resume contract a general ToolDefinition.resolve_user_input hook.

Co-authored-by: openhands <openhands@all-hands.dev>
A single LLM response can carry ask_user alongside other tool calls that
share an llm_response_id. After only the ask_user call was answered, the
view enforcer dropped the whole batch: the still-unmatched sibling action
was removed by tool-call matching, the answered action by batch atomicity,
and the answer observation as orphaned. The sibling then executed on the
next run and its observation was appended to an empty view, so the next
LLM request carried a tool result without its originating tool call and
failed provider validation.

- Re-derive the view after the resumed pending actions execute (both step
  paths) so a complete batch and all of its results enter together, and
  any batch still incomplete is dropped.
- Only re-derive on answer when the whole batch is resolved; when sibling
  calls from the same response are still pending, leave the view alone so
  full enforcement cannot collapse the answer away.

Co-authored-by: openhands <openhands@all-hands.dev>
Add a warm-conversation regression for a single response that calls
ask_user alongside another tool: answering must not collapse the
incomplete batch, and the resumed run must group the full batch with all
observations. Together with test_parallel_sibling_call_keeps_batch_with_results
it covers both halves of the fix (guarded answer-time rebuild and the
post-execution rebuild).

Co-authored-by: openhands <openhands@all-hands.dev>
@all-hands-bot

all-hands-bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

⏳ Review waiting on checks

The current head e913f798cbf2 still has checks that have not finished, so no review conversation was started:

  • Agent Server
  • Check Docstrings
  • Check duplicate example numbers
  • Deprecation deadlines
  • Persisted settings compatibility checks
  • Pre-commit checks
  • REST API breakage checks
  • Review Thread Gate
  • Run tests
  • Run tests (macOS)
  • TypeScript client CI
  • TypeScript client endpoint audit
  • TypeScript client integration tests
  • Version bump guard
  • [Optional] Docs example

No action is needed. The scheduled scan retries once every check on the head reports a conclusion.

This is an automated check - no AI was used to generate this comment.

@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot October 15, 2026 20:59

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Summary

The ask_user tool itself is well built: input validation is thorough, the answer payload is parsed defensively (labels always come from the pending question, never the client), malformed answers raise and keep the request pending, and the non-LLM-convertible AskUserAnswerNoticeEvent correctly avoids interleaving a user note between tool_use and tool_result. I reproduced the intended pause/resume flow end to end, and tests/sdk/tool/test_ask_user.py + tests/sdk/conversation/local/test_ask_user_pause_resume.py pass (35 passed). Broader focused suites also pass (869 passed across tests/sdk/context/view, tests/sdk/conversation/local, tests/sdk/agent/test_response_dispatch.py, tests/sdk/tool, tests/sdk/event).

However, there is one material defect on the current head.

Material finding: confirmation policy is bypassed when ask_user shares a response with another tool call

In both dispatch handlers, the new _pause_for_user_input check runs before _requires_user_confirmation and returns early:

if self._pause_for_user_input(state, action_events, on_event):
    return
if self._requires_user_confirmation(state, action_events):
    return

So when one LLM response contains ask_user plus any other tool call, state.confirmation_policy.should_confirm(...) is never consulted for the batch. The sibling ActionEvent is left unmatched, and on resume Agent._step / _astep takes the pending-actions branch and calls _execute_actions(conversation, pending_actions, on_event) (agent.py:731 / :955) with no policy check - _execute_actions has none. The sibling therefore executes as soon as the user answers the question.

Reproduced on the head (AlwaysConfirm confirmation policy, a write tool with readOnlyHint=False):

  • risky write alone: should_confirm called 1x, status WAITING_FOR_CONFIRMATION, no execution (correct).
  • write + ask_user in one response: should_confirm called 0 times; after answering, DANGEROUS was executed with no approval.
  • same batch, user answers {"action": "decline"}: the sibling still executed.

This is a real regression against the confirmation contract, not just a missing test: on the base revision the same batch shape (two tool calls, one risky) stops at WAITING_FOR_CONFIRMATION and nothing runs, because _requires_user_confirmation gates the whole batch. It matters most in exactly the intended use case - a user who turned on confirmation mode so the agent must ask before acting - because the agent can now place a risky call next to ask_user and have it run without approval, and the user's refusal (decline/cancel) does not stop it either.

A fix that keeps the batch intact but honors the policy would consult _requires_user_confirmation for the non-pause members (or route the resume path through the same gate) before executing the pending siblings, and treat a decline/cancel resolution as a rejection for the rest of the batch. A regression test that pairs ask_user with a confirmation-required sibling and asserts nothing executes without approval would lock this down.

Other observations (non-blocking)

  • AskUserAnswerNoticeEvent is exported from openhands.sdk.event and registered in the default visualizer, so clients that enumerate event kinds see a new kind. No agent-server endpoint or serialized status changed, consistent with the PR description; the TypeScript client is not updated, which the PR lists as a follow-up.
  • The companion docs guide is staged under .pr/ rather than opened against OpenHands/docs; the repository expects a docs PR for public SDK changes. Per the review guide, .pr/ artifacts are owned by the cleanup workflow, so this is only a note for the maintainer.

Verdict

🔄 CHANGES REQUESTED

@analisaperlengkapan

Copy link
Copy Markdown
Contributor Author

This review was posted by an AI agent (OpenHands).

Summary

The ask_user tool itself is well built: input validation is thorough, the answer payload is parsed defensively (labels always come from the pending question, never the client), malformed answers raise and keep the request pending, and the non-LLM-convertible AskUserAnswerNoticeEvent correctly avoids interleaving a user note between tool_use and tool_result. I reproduced the intended pause/resume flow end to end, and tests/sdk/tool/test_ask_user.py + tests/sdk/conversation/local/test_ask_user_pause_resume.py pass (35 passed). Broader focused suites also pass (869 passed across tests/sdk/context/view, tests/sdk/conversation/local, tests/sdk/agent/test_response_dispatch.py, tests/sdk/tool, tests/sdk/event).

However, there is one material defect on the current head.

Material finding: confirmation policy is bypassed when ask_user shares a response with another tool call

In both dispatch handlers, the new _pause_for_user_input check runs before _requires_user_confirmation and returns early:

if self._pause_for_user_input(state, action_events, on_event):
    return
if self._requires_user_confirmation(state, action_events):
    return

So when one LLM response contains ask_user plus any other tool call, state.confirmation_policy.should_confirm(...) is never consulted for the batch. The sibling ActionEvent is left unmatched, and on resume Agent._step / _astep takes the pending-actions branch and calls _execute_actions(conversation, pending_actions, on_event) (agent.py:731 / :955) with no policy check - _execute_actions has none. The sibling therefore executes as soon as the user answers the question.

Reproduced on the head (AlwaysConfirm confirmation policy, a write tool with readOnlyHint=False):

  • risky write alone: should_confirm called 1x, status WAITING_FOR_CONFIRMATION, no execution (correct).
  • write + ask_user in one response: should_confirm called 0 times; after answering, DANGEROUS was executed with no approval.
  • same batch, user answers {"action": "decline"}: the sibling still executed.

This is a real regression against the confirmation contract, not just a missing test: on the base revision the same batch shape (two tool calls, one risky) stops at WAITING_FOR_CONFIRMATION and nothing runs, because _requires_user_confirmation gates the whole batch. It matters most in exactly the intended use case - a user who turned on confirmation mode so the agent must ask before acting - because the agent can now place a risky call next to ask_user and have it run without approval, and the user's refusal (decline/cancel) does not stop it either.

A fix that keeps the batch intact but honors the policy would consult _requires_user_confirmation for the non-pause members (or route the resume path through the same gate) before executing the pending siblings, and treat a decline/cancel resolution as a rejection for the rest of the batch. A regression test that pairs ask_user with a confirmation-required sibling and asserts nothing executes without approval would lock this down.

Other observations (non-blocking)

  • AskUserAnswerNoticeEvent is exported from openhands.sdk.event and registered in the default visualizer, so clients that enumerate event kinds see a new kind. No agent-server endpoint or serialized status changed, consistent with the PR description; the TypeScript client is not updated, which the PR lists as a follow-up.
  • The companion docs guide is staged under .pr/ rather than opened against OpenHands/docs; the repository expects a docs PR for public SDK changes. Per the review guide, .pr/ artifacts are owned by the cleanup workflow, so this is only a note for the maintainer.

Verdict

🔄 CHANGES REQUESTED

@OpenHands fix it and resolve conflicts

@openhands-ai

openhands-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

I'm on it! analisaperlengkapan can track my progress at all-hands.dev

@openhands-ai

openhands-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

-dispatch time (confirmation gate), and after the answer, the user must explicitly confirm (run()) to execute the siblings — and if the user declines/cancels the question, the siblings are rejected.

To make this work without a loop, I'll use this mechanism:

  • At dispatch: if the batch has a pause call, evaluate confirmation for the non-pause members. If required, then... we need the sibling to be executed only after an explicit run() that is NOT the answer's run.

Hmm, the answer's run() is indistinguishable. So maybe the semantics should be: after answering, the run should pause AGAIN at WAITING_FOR_CONFIRMATION so the user gets an explicit confirmation prompt, and the NEXT run() executes. That requires distinguishing.

Actually — maybe it IS distinguishable! When the answer arrives via send_message, we could set the status to something... The answer's send_message could leave status as WAITING_FOR_CONFIRMATION. Then run() clears it. Hmm.

Wait, what if, when the answer resolves an ask_user in a batch with confirmation-required siblings, we set the status to WAITING_FOR_CONFIRMATION and we ALSO emit something? No.

Alternatively: what if the answer's run() executes the siblings but the siblings were already "confirmed" by... no.

Let me try yet another framing. Maybe the intended behavior is: the confirmation prompt and the question are both surfaced; the user's answer resolves the question; the user's confirmation (run) resolves the siblings. That's the base-like behavior. The regression the reviewer found is that should_confirm is not called → so the user is not told the sibling needs confirmation → and decline doesn't reject.

So maybe the minimal fix the reviewer wants:
(a) consult should_confirm for siblings at dispatch (so the batch is recognized as needing confirmation), and
(b) when the answer is decline/cancel, reject the sibling actions (and keep the batch coherent with UserRejectObservations).

And for accept, the sibling executes on the next run() (which the user must call, having seen the confirmation). That satisfies "nothing executes without approval" if approval = run().

Hmm, but with (a) alone, after accept the sibling is pending and the user's run() executes it. Is that "approval"? Yes, in the SDK model.

But then (a) has no behavioral effect except should_confirm being called (and possibly setting WAITING_FOR_CONFIRMATION, which is already set). So the reviewer's "material defect" would be only about should_confirm being called and decline. Hmm, the reviewer framed it as a real regression where the sibling "executes as soon as the user answers the question" — "as soon as the user answers" suggests the execution happens on the answer's run().

Hmm, let me test: what if after answering, we DON'T call run()? Then nothing executes. So the execution requires run(). The reviewer's phrasing "as soon as the user answers the question" implies they consider the answer's run() part of answering.

OK. Let me look at this from the "what would a maintainer merge" angle. I'll implement a fix where:

  1. When a batch contains a pause call, the confirmation policy is consulted for the non-pause members. If confirmation is required, those members are marked as requiring confirmation and the run pauses (WAITING_FOR_CONFIRMATION) — with the pause-for-user-input request pending.
  2. On the resume path (_step/_astep), the pending actions are routed through the confirmation gate: if the pending actions include a confirmation-required action that has not been explicitly confirmed, pause for confirmation instead of executing. To avoid the loop, we need an explicit approval signal.

Hmm, the loop. Let me actually check: does the run loop clear WAITING_FOR_CONFIRMATION before step() in a way we can observe? "clear the flag before calling agent.step() (user approved)". So during _step, status is RUNNING (not WAITING_FOR_CONFIRMATION). We could set a conversation-level flag in the run loop when clearing. But that flag would be per-run.

Hmm, what about this: the run loop sets status RUNNING when it was WAITING_FOR_CONFIRMATION. In _step's pending branch, we can't tell if the previous status was WAITING_FOR_CONFIRMATION or if this is a fresh run after an answer. Actually — the answer's send_message does NOT clear WAITING_FOR_CONFIRMATION. So when the user calls run() after answering, the loop sees WAITING_FOR_CONFIRMATION and clears it → approval. Same as a normal confirmation. So both are "approval".

Therefore, requiring a separate approval after the answer would need the answer's send_message to NOT leave the status as WAITING_FOR_CONFIRMATION... but it must, so that run() is treated as approval. Circular.

Conclusion: In the SDK's model, the answer's run() IS an approval. So the correct fix is:

  • Consult the policy for the siblings (so the user is shown a confirmation / the status reflects confirmation), and
  • Reject the siblings on decline/cancel.

And to make it truly safe ("nothing executes without approval"), we ensure that a batch with confirmation-required siblings does not execute them during the answer resolution (it doesn't) and requires an explicit run() (which it does).

Hmm, but I worry the reviewer's regression test might do: answer(accept) → assert no execution → and then... maybe they don't run. Then it passes trivially. Or they might test that after answer(accept), the sibling is still pending and the status is WAITING_FOR_CONFIRMATION.

Hmm, hold on. Let me reconsider whether, with the bug, the sibling executes during the answer's run even though the user might not intend it. Actually, maybe the real fix is to make the answer's run NOT execute the siblings, by having the confirmation gate on the resume path, combined with marking the siblings as "awaiting confirmation" persistently, and using the existing blocked_actions... no.

Let me look at whether upstream main has any notion of an explicit confirmation per action. Let me grep for "confirmation" in the SDK more broadly, and for any "approved" state.

Actually, let me reconsider. Maybe the cleanest fix that satisfies everything: reject the non-pause siblings at pause time when they require confirmation, keeping the batch intact via UserRejectObservation. Then:

  • should_confirm is called for the siblings. ✓
  • Nothing executes without approval: the sibling is rejected (not executed) unless the user explicitly approves. But with a rejection, the user never gets to approve it in this batch; the agent must re-propose. Then the re-proposal goes through normal confirmation. ✓
  • decline/cancel → also rejects siblings (already rejected). ✓
  • The batch stays coherent: the sibling's tool call gets a UserRejectObservation. ✓

Hmm, but "reject at pause time" means the user's confirmation is not even offered for the sibling. The reviewer says "keeps the batch intact but honors the policy" — rejecting is honoring the policy (not executing without approval). But the user might want to approve. Hmm, with confirmation mode on, the normal flow offers approval. Rejecting outright is harsher.

Alternatively: don't reject; leave pending; consult policy at dispatch; and on resume, if the siblings require confirmation, keep them pending and set WAITING_FOR_CONFIRMATION (which is already the case). Then the user's run() executes them = approval. decline/cancel → reject.

I'll go with this. But I want to make sure the fix has a material behavioral effect beyond calling should_confirm. The material effects:

  • decline/cancel rejects siblings (behavioral change, fixes a real bug).
  • should_confirm is consulted (fixes the reported "0 times"), which matters because with ConfirmRisky, an UNKNOWN-risk ask_user would... hmm, actually the ask_user action itself is part of the batch and _requires_user_confirmation includes all action_events. With ConfirmRisky(threshold=HIGH, confirm_unknown=True), the ask_user action has UNKNOWN risk → should_confirm True. So on base, ask_user alone with ConfirmRisky would require confirmation! Interesting.

Hmm OK. Actually, maybe there's an even cleaner approach: route the resume path through the confirmation gate, and treat the ask_user answer as the approval for the question but not for the siblings, by making the siblings' execution require the status transition.

Hmm, let me look at this from the angle of: what if the pause-for-user-input batch does NOT set WAITING_FOR_CONFIRMATION but rather a distinct internal marker, so that run() after the answer is not treated as approval... but the PR says no new serialized status.

I think I need to make a decision. Let me look at the actual upstream main version of _step and _requires_user_confirmation to see if there's a cleaner integration point, and check if there's an existing "pending confirmation" concept I can reuse. Let me also check the agent server's respond_to_confirmation semantics: accept → run(). So the agent server's confirmation is run(). And the ask_user answer goes through send_message. So a client would: send_message(answer) then, if status is WAITING_FOR_CONFIRMATION, respond_to_confirmation(accept) → run(). Both. So the sibling executes on the confirmation. That's the intended UI flow! The bug is that the client might not know a confirmation is needed (because should_confirm was never called / no confirmation was surfaced). Hmm, but the status is WAITING_FOR_CONFIRMATION, so the client would show it.

Hmm, wait, but actually there's a subtlety: after send_message(answer) resolves the ask_user, if the client checks status and sees WAITING_FOR_CONFIRMATION, it might think "still waiting for confirmation" and show the confirm dialog. OK.

So maybe the real bug is narrower: on the resume path, the pending branch executes ALL pending actions as implicit confirmation — but this includes actions that were never confirmed. For the mixed batch, the ask_user is resolved by the answer, and the sibling is executed by the answer's run. But the client would have to explicitly accept. Hmm.

OK you know what, let me just look at the reviewer's reproduction more concretely by writing tests that match their description and see what fails. They said:

  • write alone: should_confirm 1x, pause, no execution.
  • write + ask_user: should_confirm 0x; after answering, DANGEROUS executed with no approval.
  • same batch, decline: sibling still executed.

"after answering" — in their repro, answering likely includes calling run() (since answering alone doesn't execute). Or maybe they call conversation.run() after send_message. Let me write a test that mimics: after answer, call run(), and assert the write did NOT execute. That would be the strictest interpretation. But is that the right behavior? If we require a separate confirmation, then the answer's run() should not execute the sibling. How? The answer's run() is an approval...

Hmm, unless: the ask_user answer should be delivered while the status is RUNNING/IDLE, not WAITING_FOR_CONFIRMATION. Wait! What if the fix makes the pause-for-user-input NOT use WAITING_FOR_CONFIRMATION when the batch also requires confirmation... no, that's the opposite.

Hmm, let me think about the distinguishing signal differently. What if, when the ask_user is resolved, we set the execution status to IDLE (or leave RUNNING), so that the subsequent run() is NOT treated as an implicit confirmation? Then the pending siblings would be executed by the pending branch without confirmation — worse.

What if, when the ask_user is resolved, we set the status to WAITING_FOR_CONFIRMATION specifically because siblings need confirmation, and we clear the "pause" aspect? Then the run() after the answer is the confirmation — approval. Same.

I think the answer is: the answer's run() IS the approval, and that's acceptable. The reviewer's concern is that should_confirm isn't consulted and decline doesn't reject.

Hmm, but the reviewer's test "asserts nothing executes without approval" — with my fix, after answer(accept), the sibling is pending; without a run(), nothing executes. With a run(), it executes (approval). I think that passes.

Hmm, but actually, wait. Let me reconsider: maybe the reviewer's repro is:

conv.run()  # pause
conv.send_message(answer)  # resolve ask_user
conv.run()  # ??? executes sibling

and they consider the second run() as "answering" (because in the agent server, answering triggers run()). And they want the sibling to still not execute, requiring a third step.

To achieve that, we'd need the answer resolution to result in a state where the next run() pauses for confirmation rather than executing. That means: after the answer, the status should be... hmm, if status is IDLE (not WAITING_FOR_CONFIRMATION), then run() → status RUNNING → step → pending branch → executes siblings. Still executes.

Unless the pending branch is gated: after the answer, pending = [sibling]. run() → step → pending branch → gate _requires_user_confirmation for the sibling → True → pause (WAITING_FOR_CONFIRMATION), don't execute. Then the NEXT run() → step → pending branch → gate again → True → pause again. LOOP.

To break the loop, we need the gate to pass on the second attempt. The gate is should_confirm(risk), which always returns True for AlwaysConfirm. So we need an additional "already confirmed" signal. That signal must be set when the user explicitly confirms. In the SDK, explicit confirmation = run() while WAITING_FOR_CONFIRMATION. The run loop clears the flag. We could detect that: in the run loop, when clearing WAITING_FOR_CONFIRMATION, set state.<flag> = True. Then in the gate, if the flag is set, allow execution and clear it.

But that's new state (persisted). Hmm, but maybe acceptable? The PR says "No new Agent Server endpoint, event type, or serialized status value." A new boolean field would be serialized state. The reviewer didn't forbid it, but the PR's design constraint is "the pending request is derived from the event log, so it survives a resume and needs no new persisted state."

Hmm, we could derive "confirmed" from the event log too: e.g., a confirmation is recorded as... hmm, there's no confirmation event.

Alternatively, use state.blocked_actions semantics differently...

Hmm, let me reconsider. Maybe the correct fix is much simpler than I think, and the reviewer just wants:

  1. Consult _requires_user_confirmation for the non-pause members at dispatch.
  2. If confirmation is required, reject/decline the siblings when the answer is decline/cancel.

And the "material defect" is that should_confirm is never called. The reviewer's proposed test: "pairs ask_user with a confirmation-required sibling and asserts nothing executes without approval". With fix #1, at dispatch the batch requires confirmation → pause. Nothing executes. Then answer + run → executes (approval). So "nothing executes without approval" holds because the run is the approval.

Wait, but that's already the case without fix #1! The bug repro says the sibling executed after answering — which required a run(). So fix #1 wouldn't change that test. Unless the reviewer's test asserts the sibling is still pending after answer+run...

Hmm, I bet the reviewer's test is more like:

run()  # pause
send_message(decline)
run()  # assert no observation for write

OR

run()
assert should_confirm called (spy)

Let me just be pragmatic: implement a fix that:
(a) Consults the confirmation policy for the non-pause members of a mixed batch at dispatch (so should_confirm is called and the status is set by confirmation, not just by the pause).
(b) On decline/cancel, rejects the sibling pending actions in the same batch (UserRejectObservation), so nothing executes.
(c) Ensures that on accept, the siblings do not execute until the user explicitly confirms — i.e., route the resume path through the confirmation gate so that a pending sibling that requires confirmation triggers a WAITING_FOR_CONFIRMATION pause, and only a subsequent explicit confirmation executes it.

For (c) to avoid a loop, I'll use the event log to determine whether the batch's confirmation has already been granted. How? Hmm.

Actually, maybe simpler: for (c), when the answer is accepted and the siblings require confirmation, we can reject the ask_user pause as resolved and leave the siblings pending; the run() after the answer will execute them (implicit confirmation) — that's the approval. So (c) is satisfied by (a). I'll skip the extra gate.

Hmm, but then what's the difference from the buggy version? Only (a) should_confirm called and (b) decline/cancel rejection. Is (a) enough to change behavior? With AlwaysConfirm, should_confirm returns True and sets WAITING_FOR_CONFIRMATION — already set. With ConfirmRisky, the ask_user action (UNKNOWN risk) would trigger confirmation. Hmm.

Actually, (a) DOES change behavior in one important way: if the confirmation policy requires confirmation for the siblings, then... hmm, the pause already happens. No change.

Hmm, so the only real behavioral fix would be (b) + maybe requiring a separate confirmation.

Let me reconsider (c) with a fresh idea: what if the fix is to not execute the sibling batch on the answer's run, but instead re-pause at WAITING_FOR_CONFIRMATION, and to break the loop, mark the batch as "confirmation pending" in a way derived from the event log — specifically, emit a confirmation-required marker? Hmm.

OK, alternative fresh idea: What if the fix is to defer the ask_user resolution when the batch also requires confirmation? I.e., at dispatch, if the batch requires confirmation, we pause for confirmation and do NOT treat the ask_user as a pause-for-user-input (leave it pending as a normal pending action). Then the user's confirmation (run()) executes the batch — but ask_user's executor returns an error. Hmm, bad.

Hmm, what if, when confirmation is required for the batch, we reject the ask_user too? No.

Let me look at how the existing tests in the PR treat the mixed batch with NeverConfirm: test_warm_parallel_sibling_batch_resolves_in_view expects both actions

openhands-agent and others added 2 commits October 19, 2026 05:58
Resolve the `response_dispatch.py` conflict by keeping both sides: main's
`on_event` plumbing for `_requires_user_confirmation`, and this branch's
`_pause_for_user_input` check.

Also fix the confirmation-policy bypass raised in review. A response that
pairs `ask_user` with another tool call skipped the confirmation gate
because the pause check returned first, so the sibling stayed pending and
was executed by the run that delivered the user's answer, which is not an
approval. Now:

- the confirmation policy is applied to a paused batch's non-pause
  siblings and any gated sibling is rejected up front, so it cannot run
  without approval and the batch stays coherent;
- a decline/cancel answer rejects the remaining siblings as well, since a
  refusal is not consent for the rest of the batch;
- `_gate_paused_siblings` / `_agate_paused_siblings` handle the sync and
  async dispatch paths, and `resolution_rejects_pending` lets a pausing
  tool declare that a resolution is a refusal;
- regression tests cover the gated-sibling, decline, ungated-resume,
  lone-call, and async paths.

Full SDK suite: 7500 passed, 7 skipped, 19 deselected, 12 xfailed.

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot October 19, 2026 16:06

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Summary

This head (9f05dc53d3cc, 16 files) is a solid revision of the ask_user slice. The previously reported confirmation-policy bypass is genuinely fixed: _pause_for_user_input no longer returns before the policy gate, the non-pause siblings are evaluated through _gate_paused_siblings / _agate_paused_siblings, resolution_rejects_pending makes a decline/cancel reject the remaining siblings, and the new tests cover those paths (test_confirmation_gated_sibling_is_not_executed_by_the_answer, test_declining_rejects_a_sibling_the_policy_would_allow, test_async_gated_sibling_is_not_executed_by_the_answer all pass). The ask_user tool itself remains well built: input validation is thorough, the answer payload is parsed defensively (labels always come from the pending question, never the client), malformed answers raise ValueError and keep the request pending, and the non-LLM-convertible AskUserAnswerNoticeEvent avoids interleaving a user note between tool_use and tool_result.

I verified locally on this head:

  • uv run pytest tests/sdk/tool/test_ask_user.py tests/sdk/conversation/local/test_ask_user_pause_resume.py -q -> 41 passed.
  • uv run pytest tests/sdk/conversation/local -q -> 253 passed; tests/sdk/agent/test_acp_agent.py + tests/sdk/conversation/local/test_conversation_send_message.py -> 510 passed.
  • AskUserAnswerNoticeEvent round-trips through Event.model_validate with the new kind.
  • ask_user is registered in BUILT_IN_TOOL_CLASSES but not BUILT_IN_TOOLS, consistent with the stated opt-in scope.

CI on this exact head has not run the substantive checks yet: only check-pr-artifacts and Validate PR description are success, while Run tests, Agent Server, Pre-commit checks, Check Docstrings, etc. are action_required (combined status pending). That is not itself a defect, but the verdict below rests on my local runs, not on a green CI for this head.

However, there is one material defect introduced by this PR.

Material finding: send_message() now touches agent.tools_map before an ACP agent is initialized, and raises RuntimeError

LocalConversation.send_message() unconditionally calls the new resolver before anything else in the state block:

if self._should_initialize_agent_on_send_message():
    self._ensure_agent_ready()
...
with self._state:
    ...
    if self._try_resolve_ask_user(message):
        return

_should_initialize_agent_on_send_message() is deliberately not isinstance(self.agent, ACPAgent) so ACP init stays deferred to run(). The new resolver then reads self.agent.tools_map, which raises for an uninitialized agent (AgentBase.tools_map: if not self._initialized: raise RuntimeError("Agent not initialized; call _initialize() before use")). The read happens through _pending_ask_user_action -> _tool_pauses_for_user_input whenever ConversationState.get_unmatched_actions(...) is non-empty, so the new code makes send_message() depend on an initialized tools_map in a path whose whole purpose is to run before initialization.

Reproduced on this head through the supported persistence-reopen flow (Conversation(agent=ACPAgent(...), persistence_dir=..., conversation_id=...), an unmatched ActionEvent in the log, close, reopen, send_message):

reopened initialized: False | events: 1
send_message RAISED: RuntimeError | Agent not initialized; call _initialize() before use
  File ".../local_conversation.py", line 1889, in send_message
    if self._try_resolve_ask_user(message):
  File ".../local_conversation.py", line 1948, in _try_resolve_ask_user
    pending = self._pending_ask_user_action()
  File ".../local_conversation.py", line 1931, in _pending_ask_user_action
    if self._tool_pauses_for_user_input(ae.tool_name):
  File ".../local_conversation.py", line 1936, in _tool_pauses_for_user_input
    tool = self.agent.tools_map.get(tool_name)
  File ".../agent/base.py", line 1039, in tools_map
    raise RuntimeError("Agent not initialized; call _initialize() before use")

On the base revision 3f3294581ebf, the identical flow returns send_message OK, so this is a regression, not a pre-existing gap. It matters because an unmatched action is exactly the crash-recovery state this repository already treats as real: EventService.start() synthesizes an AgentErrorEvent for a RUNNING-status orphan, and it deliberately skips patching when an observation matches by tool_call_id but not action_id (tests/agent_server/test_event_service.py::test_start_skips_error_event_when_observation_already_exists), leaving the action unmatched. In that state the agent-server's initial send_message on an ACP conversation would hit this RuntimeError at startup, and standalone SDK users reopening a persisted ACP conversation (the flow the PR's own cold-reload tests use) hit it directly. Non-ACP agents are unaffected because _ensure_agent_ready() has already run by then.

A minimal fix keeps the new behavior for initialized agents while tolerating the deferred ACP case: gate the call on the agent being ready (or reuse _should_initialize_agent_on_send_message()), or have _tool_pauses_for_user_input return False when not self.agent._initialized rather than reading tools_map. A regression test that reopens a persisted ACP conversation containing an unmatched action and asserts send_message() succeeds would lock it down.

Non-blocking notes

  • AskUserAnswerNoticeEvent is exported from openhands.sdk.event and registered in the default visualizer, so clients enumerating event kinds see a new kind. No endpoint or serialized status changed, and the TypeScript client is listed as a follow-up; fine for this slice.
  • The companion docs guide is staged under .pr/; the repository expects a docs PR for public SDK changes. .pr/ artifacts are owned by the cleanup workflow, so this is only a note for the maintainer.

Verdict

🔄 CHANGES REQUESTED

@analisaperlengkapan

Copy link
Copy Markdown
Contributor Author

This review was posted by an AI agent (OpenHands).

Summary

This head (9f05dc53d3cc, 16 files) is a solid revision of the ask_user slice. The previously reported confirmation-policy bypass is genuinely fixed: _pause_for_user_input no longer returns before the policy gate, the non-pause siblings are evaluated through _gate_paused_siblings / _agate_paused_siblings, resolution_rejects_pending makes a decline/cancel reject the remaining siblings, and the new tests cover those paths (test_confirmation_gated_sibling_is_not_executed_by_the_answer, test_declining_rejects_a_sibling_the_policy_would_allow, test_async_gated_sibling_is_not_executed_by_the_answer all pass). The ask_user tool itself remains well built: input validation is thorough, the answer payload is parsed defensively (labels always come from the pending question, never the client), malformed answers raise ValueError and keep the request pending, and the non-LLM-convertible AskUserAnswerNoticeEvent avoids interleaving a user note between tool_use and tool_result.

I verified locally on this head:

  • uv run pytest tests/sdk/tool/test_ask_user.py tests/sdk/conversation/local/test_ask_user_pause_resume.py -q -> 41 passed.
  • uv run pytest tests/sdk/conversation/local -q -> 253 passed; tests/sdk/agent/test_acp_agent.py + tests/sdk/conversation/local/test_conversation_send_message.py -> 510 passed.
  • AskUserAnswerNoticeEvent round-trips through Event.model_validate with the new kind.
  • ask_user is registered in BUILT_IN_TOOL_CLASSES but not BUILT_IN_TOOLS, consistent with the stated opt-in scope.

CI on this exact head has not run the substantive checks yet: only check-pr-artifacts and Validate PR description are success, while Run tests, Agent Server, Pre-commit checks, Check Docstrings, etc. are action_required (combined status pending). That is not itself a defect, but the verdict below rests on my local runs, not on a green CI for this head.

However, there is one material defect introduced by this PR.

Material finding: send_message() now touches agent.tools_map before an ACP agent is initialized, and raises RuntimeError

LocalConversation.send_message() unconditionally calls the new resolver before anything else in the state block:

if self._should_initialize_agent_on_send_message():
    self._ensure_agent_ready()
...
with self._state:
    ...
    if self._try_resolve_ask_user(message):
        return

_should_initialize_agent_on_send_message() is deliberately not isinstance(self.agent, ACPAgent) so ACP init stays deferred to run(). The new resolver then reads self.agent.tools_map, which raises for an uninitialized agent (AgentBase.tools_map: if not self._initialized: raise RuntimeError("Agent not initialized; call _initialize() before use")). The read happens through _pending_ask_user_action -> _tool_pauses_for_user_input whenever ConversationState.get_unmatched_actions(...) is non-empty, so the new code makes send_message() depend on an initialized tools_map in a path whose whole purpose is to run before initialization.

Reproduced on this head through the supported persistence-reopen flow (Conversation(agent=ACPAgent(...), persistence_dir=..., conversation_id=...), an unmatched ActionEvent in the log, close, reopen, send_message):

reopened initialized: False | events: 1
send_message RAISED: RuntimeError | Agent not initialized; call _initialize() before use
  File ".../local_conversation.py", line 1889, in send_message
    if self._try_resolve_ask_user(message):
  File ".../local_conversation.py", line 1948, in _try_resolve_ask_user
    pending = self._pending_ask_user_action()
  File ".../local_conversation.py", line 1931, in _pending_ask_user_action
    if self._tool_pauses_for_user_input(ae.tool_name):
  File ".../local_conversation.py", line 1936, in _tool_pauses_for_user_input
    tool = self.agent.tools_map.get(tool_name)
  File ".../agent/base.py", line 1039, in tools_map
    raise RuntimeError("Agent not initialized; call _initialize() before use")

On the base revision 3f3294581ebf, the identical flow returns send_message OK, so this is a regression, not a pre-existing gap. It matters because an unmatched action is exactly the crash-recovery state this repository already treats as real: EventService.start() synthesizes an AgentErrorEvent for a RUNNING-status orphan, and it deliberately skips patching when an observation matches by tool_call_id but not action_id (tests/agent_server/test_event_service.py::test_start_skips_error_event_when_observation_already_exists), leaving the action unmatched. In that state the agent-server's initial send_message on an ACP conversation would hit this RuntimeError at startup, and standalone SDK users reopening a persisted ACP conversation (the flow the PR's own cold-reload tests use) hit it directly. Non-ACP agents are unaffected because _ensure_agent_ready() has already run by then.

A minimal fix keeps the new behavior for initialized agents while tolerating the deferred ACP case: gate the call on the agent being ready (or reuse _should_initialize_agent_on_send_message()), or have _tool_pauses_for_user_input return False when not self.agent._initialized rather than reading tools_map. A regression test that reopens a persisted ACP conversation containing an unmatched action and asserts send_message() succeeds would lock it down.

Non-blocking notes

  • AskUserAnswerNoticeEvent is exported from openhands.sdk.event and registered in the default visualizer, so clients enumerating event kinds see a new kind. No endpoint or serialized status changed, and the TypeScript client is listed as a follow-up; fine for this slice.
  • The companion docs guide is staged under .pr/; the repository expects a docs PR for public SDK changes. .pr/ artifacts are owned by the cleanup workflow, so this is only a note for the maintainer.

Verdict

🔄 CHANGES REQUESTED

@OpenHands fix it

@openhands-ai

openhands-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

I'm on it! analisaperlengkapan can track my progress at all-hands.dev

`LocalConversation.send_message()` runs the pending-input resolver before
anything else in the state block, and ACP initialization is deliberately
deferred to `run()`. The resolver read `self.agent.tools_map`, which raises
`RuntimeError` for an uninitialized agent, so `send_message()` failed
whenever the log held an unmatched action.

That is exactly the crash-recovery state the agent server produces: an
unmatched `ActionEvent` (an observation matched by `tool_call_id` but not
`action_id`) leaves `get_unmatched_actions()` non-empty, so the first
`send_message()` on a reopened ACP conversation raised.

`_tool_pauses_for_user_input` now returns False when the agent is not
initialized. An uninitialized agent has no resolved tools, so nothing can
pause, and the initialized path is unchanged.

Adds `test_acp_send_message_tolerates_unmatched_action_before_init`, which
reopens a persisted ACP conversation containing an unmatched action and
asserts `send_message()` succeeds (fails before this fix).

Co-authored-by: openhands <openhands@all-hands.dev>
@openhands-ai

openhands-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

Fixed the regression and pushed it to the PR.

Root cause

LocalConversation.send_message() calls the new pending-input resolver (_try_resolve_ask_user → _pending_ask_user_action → _tool_pauses_for_user_input) at the top of its state block. ACP agent initialization is deliberately deferred to run() (_should_initialize_agent_on_send_message() returns False for ACPAgent), so on a reopened conversation _tool_pauses_for_user_input read self.agent.tools_map, which raises RuntimeError("Agent not initialized; call _initialize() before use"). The read only happens when ConversationState.get_unmatched_actions(...) is non-empty — exactly the crash-recovery state the agent server produces.

Fix (commit e913f79)

_tool_pauses_for_user_input now returns False when not self.agent._initialized, so the resolver never touches tools_map before the agent is ready. An uninitialized agent has no resolved tools, hence nothing can pause; the initialized path is unchanged. This matches the reviewer's suggested minimal fix.

Regression test

Added test_acp_send_message_tolerates_unmatched_action_before_init in tests/sdk/conversation/local/test_conversation_send_message.py: it creates a persisted LocalConversation with an ACPAgent, injects an unmatched ActionEvent, closes it, reopens it (asserting the agent is uninitialized and the action is unmatched), and asserts send_message() succeeds. I confirmed it fails on the unpatched head and passes with the fix.

Verification

  • uv run pytest tests/sdk/conversation/local/test_conversation_send_message.py -q → 26 passed
  • uv run pytest tests/sdk/tool/test_ask_user.py tests/sdk/conversation/local/test_ask_user_pause_resume.py tests/sdk/agent/test_acp_agent.py tests/sdk/conversation/local/test_conversation_send_message.py -q → 552 passed
  • uv run pytest tests/sdk/conversation/local tests/sdk/agent -q → 1223 passed
  • uv run pytest tests/sdk -q → 7509 passed, 19 deselected, 12 xfailed
  • uv run pyright on both changed files → 0 errors
  • uv run pre-commit run --files <both changed files> → all hooks Passed
  • uv run pytest tests/agent_server -q → 2726 passed, 12 failed; the 12 failures are all in tests/agent_server/canvas_extensions/test_canvas_extension_backend.py (process-lifecycle) and reproduce identically on the base revision, so they are pre-existing/environmental, not caused by this change.

PR hygiene

  • Pushed e913f79 to analisaperlengkapan/software-agent-sdk:feat/ask-user-tool; PR feat(sdk): add ask_user tool for structured mid-task questions #5574 head is now e913f798cbf2ff0620ebf32126a73b055654456f.
  • Replied to the review thread on local_conversation.py referencing the fix commit and resolved it.
  • Updated the AGENT section of the PR description with the regression-fix note and test evidence; the HUMAN section was left untouched.

Note for the maintainer (not addressed, as it is out of scope for this slice): the docs guide remains staged under .pr/ pending a docs PR.

@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot October 20, 2026 08:41

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Summary

This head (e913f798, the same 17 files) resolves the one material finding from the previous review, and I found no new material defect. The change is in scope for this repository: it adds a first-class SDK tool plus the agent-loop/conversation pause-resume path, and the linked issue #5570 carries ready-for-dev. No backend behavior moved across an ownership boundary.

The previously reported ACP regression is genuinely fixed

The prior review found that LocalConversation.send_message() reached self.agent.tools_map before an ACP agent was initialized. The fix is minimal and correct:

def _tool_pauses_for_user_input(self, tool_name: str) -> bool:
    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

I reproduced the before/after through the real supported lifecycle (create a persisted LocalConversation with an ACPAgent, inject an unmatched ActionEvent, close, reopen, send_message), restoring the pre-fix method body by monkeypatch rather than editing files:

PRE-FIX RAISED: RuntimeError: Agent not initialized; call _initialize() before use
FIXED: send_message OK; last event: MessageEvent

The gate is safe for every supported path: a non-ACP agent is initialized by _ensure_agent_ready() earlier in send_message(), and ACPAgent does not use the pauses_run_for_user_input path (its _step bypasses ResponseDispatchMixin), so an uninitialized agent has no resolved pause tool to mask. test_acp_send_message_tolerates_unmatched_action_before_init locks this down.

Verified on this head

  • uv run pytest tests/sdk/tool/test_ask_user.py tests/sdk/conversation/local/test_ask_user_pause_resume.py tests/sdk/conversation/local/test_conversation_send_message.py -q -> 67 passed.
  • uv run pytest tests/sdk/conversation/local tests/sdk/agent -q -> 1223 passed.
  • Answer path end to end: pause at WAITING_FOR_CONFIRMATION, answer via send_message() consumed as the tool observation, resume to FINISHED; a malformed (unknown option id) answer keeps the request pending and emits a non-LLM-convertible AskUserAnswerNoticeEvent, and a later valid answer still resolves it.
  • AskUserAnswerNoticeEvent round-trips through Event.model_validate / model_validate_json and survives a cold reload of the persisted log.
  • Hard-kill (no graceful close()) while a request is pending: the request survives reopen and a subsequent send_message() answer resolves it to FINISHED.
  • The answer's label is taken from the pending question, never from the client payload (_resolve_selected), so a client cannot relabel a known option.
  • ask_user is in BUILT_IN_TOOL_CLASSES but not BUILT_IN_TOOLS, matching the stated opt-in/non-interactive scope.
  • npm run check:agent-server-api passes with the pinned release contract (the CI resolver reports use_source_contract=false), and this PR does not touch clients/typescript/, so the deferred TS method is consistent with the stated #5566 follow-up.

The new ToolDefinition hooks (pauses_run_for_user_input, pause_error_for, resolve_user_input, resolution_rejects_pending) are defaults with backward-compatible behavior, and the new event type does not alter any existing serialized shape.

Non-blocking note

After a confirmation-mode run that ends FINISHED with a finish call followed by trailing calls, the added unconditional state.rebuild_view() can leave state.view momentarily inconsistent with state.events (the incomplete batch is dropped). I traced this and could not demonstrate a user-visible effect: the trailing action stays unmatched, so the next step enters the pending_actions branch and rebuilds before any LLM request, and I confirmed the subsequent LLM request carries the full executed history. This is also strictly better than the base behavior, which loses that history after a cold reload. Noting it only so the maintainer is aware of the extra O(n) rebuild per confirmation approval.

CI

The substantive checks for this head are action_required (fork PR awaiting maintainer approval): Run tests, Pre-commit checks, Agent Server, TypeScript client CI, and others have not run. PR Artifacts and PR Description Check are success. The verdict rests on my local runs above, not on a green CI for this head; a maintainer should confirm the checks run before merge.

Verdict

✅ APPROVED

@enyst

enyst commented Nov 14, 2026

Copy link
Copy Markdown
Member

Thank you for this work, @analisaperlengkapan. It shaped #6852, which brings ask_user in behind an experimental feature, and you're a co-author of its commit.

We tried this PR live and it worked well for a tap answer and across a restart. The one thing we couldn't get around was the pause in waiting_for_confirmation. When the person replies in chat instead of answering the card, the conversation gets stuck, and a later answer puts a user message between the tool call and its result, which the model request rejects. Canvas would also show its Approve/Reject card for a question.

#6852 keeps your design (a server-side tool, options with descriptions, free-text answers) but makes the question a tool call that ends the turn. The answer, a tap or a chat reply, arrives as the person's next message. If you have time, we'd value your review there.


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: ask_user tool for structured questions

4 participants