sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] on_error='proceed' silently bypasses a handler-raised approval pause, running the tool unapproved

Open roshangardi opened this issue 2 months ago • 0 comments

Checks

  • [x] I have updated to the lastest minor and patch version of Strands
  • [x] I have checked the documentation and this is not expected behavior
  • [x] I have searched ./issues and there are no duplicates of my issue

SDK Language

Python

Strands Version

1.56.0 (reproduced on current main, e7fd22b6)

Language Runtime Version

Python 3.14.5

Operating System

macOS 15

Installation Method

pip

Steps to Reproduce

event.interrupt() is the documented human-in-the-loop mechanism on BeforeToolCallEvent (the interrupts user guide teaches exactly this call pattern in a hook callback), and it works by raising an interrupt exception that stops the agent loop. InterventionRegistry._dispatch wraps the handler lifecycle call in a bare except Exception routed through the handler's on_error policy, so an interrupt raised inside a handler's before_tool_call is treated as a handler crash instead of control flow:

  • on_error="proceed": the pause is logged as a skipped handler error and the tool executes without approval.
  • on_error="deny": the pause becomes an automatic denial — the human is never asked — and the interrupt's string form is sent to the model inside the tool result.

The registry already carves interrupts out of on_error in the action-apply phase (where Confirm raises), with the comment "InterruptError is intentional control flow (pauses the agent), not a handler failure. Always propagate regardless of onError" — the handler-call phase is missing the same carve-out.

Confirm is the sanctioned approval action on before_tool_call and is unaffected (its interrupt goes through the protected apply phase). Direct event.interrupt() from a handler still occurs naturally: an approval hook written per the interrupts guide ports to an InterventionHandler with the same event type and the same public method and no warning anywhere, and the human-in-the-loop docs themselves route users past Confirm to "raw interrupts when you need full control: custom interrupt shapes, multi-step interactions".

import asyncio
from collections.abc import AsyncGenerator
from typing import Any

from strands import Agent, tool
from strands.interventions import Deny, InterventionHandler, Proceed
from strands.models import Model

executions: list[str] = []


class OneToolModel(Model):
    """Requests the sensitive tool once, then finishes."""

    def __init__(self) -> None:
        self.call_count = 0

    def get_config(self) -> Any:
        return {}

    def update_config(self, **model_config: Any) -> None:
        pass

    async def structured_output(self, *args: Any, **kwargs: Any) -> AsyncGenerator[Any, None]:
        yield {}

    async def stream(self, *args: Any, **kwargs: Any) -> AsyncGenerator[Any, None]:
        self.call_count += 1
        yield {"messageStart": {"role": "assistant"}}
        if self.call_count == 1:
            yield {"contentBlockStart": {"start": {"toolUse": {"name": "sensitive_tool", "toolUseId": "t1"}}}}
            yield {"contentBlockDelta": {"delta": {"toolUse": {"input": "{}"}}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop": {"stopReason": "tool_use"}}
        else:
            yield {"contentBlockStart": {"start": {}}}
            yield {"contentBlockDelta": {"delta": {"text": "done"}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop": {"stopReason": "end_turn"}}


@tool
def sensitive_tool() -> str:
    """A tool that must not run without approval."""
    executions.append("ran")
    return "sensitive action performed"


def make_handler(on_error_mode: str) -> InterventionHandler:
    class ApprovalHandler(InterventionHandler):
        name = f"approval-{on_error_mode}"

        @property
        def on_error(self) -> Any:
            return on_error_mode

        def before_tool_call(self, event: Any, **kwargs: Any) -> Any:
            response = event.interrupt("tool-approval", reason="approve sensitive_tool?")
            return Proceed() if response == "yes" else Deny(reason="not approved")

    return ApprovalHandler()


async def run_case(on_error_mode: str) -> None:
    executions.clear()
    agent = Agent(
        model=OneToolModel(),
        tools=[sensitive_tool],
        interventions=[make_handler(on_error_mode)],
        callback_handler=None,
    )
    result = await agent.invoke_async("do the sensitive thing")
    paused = bool(result.interrupts)
    print(f"on_error={on_error_mode!r}: stop_reason={result.stop_reason}, paused={paused}, tool_executed={bool(executions)}")


async def main() -> None:
    await run_case("throw")
    await run_case("proceed")
    await run_case("deny")


asyncio.run(main())

Output on current main:

on_error='throw': stop_reason=interrupt, paused=True, tool_executed=False
on_error='proceed': stop_reason=end_turn, paused=False, tool_executed=True
on_error='deny': stop_reason=end_turn, paused=False, tool_executed=False

With on_error='proceed' the sensitive tool executed with no approval and no pause. With on_error='deny' the human is never asked and the tool result the model sees is DENIED: Handler threw: Interrupt(id='v1:before_tool_call:t1:...', ...) — the docs recommend deny for security-critical handlers, and even that fail-closed mode destroys the approval flow by auto-denying. The default on_error='throw' is unaffected, so the bug bites exactly the two non-default modes.

Expected Behavior

All three cases behave like on_error='throw': the agent pauses with stop_reason=interrupt and the tool does not run until resumed with an approval. The repo's own tests state this invariant in unqualified terms for the Confirm path ("InterruptException must propagate even when onError=proceed", TestInterruptPropagation in tests/strands/interventions/test_registry.py; "InterruptError always propagates regardless of onError" in strands-ts/src/interventions/__tests__/registry.test.ts), and the apply-phase comment in both SDKs says interrupts always propagate regardless of on_error. The handler-call phase should match. The interventions design doc (team/designs/0007-intervention-primitive.md) also specified handler-initiated pausing via event.interrupt() as intended semantics from the start.

Actual Behavior

A handler-raised interrupt is routed through _handle_error like a crash: swallowed under on_error='proceed' (fail-open on an approval gate), converted to an automatic denial under on_error='deny' (with the interrupt's string form in the tool result: the full Interrupt(...) repr in Python, Interrupt raised: <name> in TypeScript).

Additional Context

Root cause: the handler-call try/except Exception in InterventionRegistry._dispatch (strands-py/src/strands/interventions/registry.py, the block that awaits the handler's lifecycle method) has no InterruptException carve-out, while the apply-phase try a few lines below re-raises InterruptException before the generic handler. The TypeScript SDK has the identical asymmetry in strands-ts/src/interventions/registry.ts (_dispatch: the catch around handler[method](...) lacks the instanceof InterruptError check that the apply-phase catch has).

History: the apply-phase carve-out (and its comment) arrived with the Confirm action in the TypeScript SDK (PR #1072) and was ported verbatim to Python (PR #2693), so the carve-out covered the phase where the registry's own event.interrupt() call lives and the handler-call phase was left behind once, then copied.

Scope note: this is specific to before_tool_call — it is the only intervention lifecycle point whose event supports interrupt() (BeforeInvocationEvent and BeforeModelCallEvent are not interruptible).

Possible Solution

Add the same carve-out the apply phase already has to the handler-call phase in both SDKs (re-raise InterruptException / InterruptError before the on_error routing). I have this implemented with regression tests in both SDKs and am opening the PRs alongside this issue; the new tests fail on current main and pass with the fix.

Related Issues

#3934 (BidiAgent HIL gaps, adjacent but distinct: that issue is about interventions not being wired into BidiAgent at all; this one is about the regular Agent's registry mishandling interrupts under non-default on_error)

roshangardi avatar Sep 16 '26 22:09 roshangardi