Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
73077ed
fix(agent): resume nested agent-as-tool interrupts across rehydration
strandly-the-agent Aug 6, 2026
b3dc2cd
fix(agent): keep a sub-agent continuation that fails to load
strandly-the-agent Aug 6, 2026
40e08f2
fix(agent): escape the tool use id when namespacing sub-agent interrupts
strandly-the-agent Aug 6, 2026
b097fc3
test(agent): pin the interrupt id encoding, and drop a consumed turn …
strandly-the-agent Aug 6, 2026
65d3730
fix(agent): keep a nested interrupt pending when its parked turn cann…
strandly-the-agent Aug 6, 2026
3e5ff99
refactor(event-loop): name the interrupt-context keys the loop owns
strandly-the-agent Aug 6, 2026
30f0355
docs(interrupts): document how a nested interrupt resumes for each pr…
strandly-the-agent Aug 6, 2026
21fd240
fix(agent): re-raise only the interrupts a parked sub-agent turn stil…
strandly-the-agent Aug 6, 2026
a61c9f3
refactor(agent): one vocabulary and fewer indirections for nested int…
strandly-the-agent Aug 12, 2026
8f0238e
Merge branch 'main' into agent-tasks/3076
strandly-the-agent Sep 29, 2026
1fc7d24
docs(agent): keep the interrupt note under preserve_context after the…
strandly-the-agent Sep 29, 2026
35ede11
refactor(agent): lift the resume path out of _AgentAsTool.stream
strandly-the-agent Sep 29, 2026
4a70bc0
refactor(agent): strip the nested-interrupt fix down to the change it…
strandly-the-agent Sep 30, 2026
92e4fae
test(agent): pin tool-use-id escaping on resume, restore the resume d…
strandly-the-agent Sep 30, 2026
903d8dd
fix(agent): keep the cannot-resume log line under 120 columns
strandly-the-agent Sep 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 220 additions & 12 deletions strands-py/src/strands/agent/_agent_as_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@
import logging
import threading
from typing import TYPE_CHECKING, Any
from urllib.parse import quote

from typing_extensions import override

from ..agent.state import AgentState
from ..interrupt import Interrupt
from ..types._events import AgentAsToolStreamEvent, ToolInterruptEvent, ToolResultEvent
from ..types._snapshot import Snapshot
from ..types.content import Messages
from ..types.interrupt import InterruptResponseContent
from ..types.tools import AgentTool, ToolGenerator, ToolSpec, ToolUse
Expand All @@ -24,6 +27,9 @@

logger = logging.getLogger(__name__)

_CONTINUATIONS_KEY = "sub_agent_continuations"
"""Key under which an orchestrator's interrupt context holds interrupted sub-agent turns, keyed by tool use id."""


class _AgentAsTool(AgentTool):
"""Adapter that exposes an Agent as a tool for use by other agents.
Expand Down Expand Up @@ -183,8 +189,25 @@ async def stream(self, tool_use: ToolUse, invocation_state: dict[str, Any], **kw

try:
# Determine if we are resuming the sub-agent from an interrupt.
Comment thread
mkmeral marked this conversation as resolved.
Resolved
if self._is_sub_agent_interrupted():
prompt = self._build_interrupt_responses()
if self._parent_awaiting_resume(invocation_state, tool_use_id):
restored = self._restore_continuation(invocation_state, tool_use_id)
if not restored and not self._is_sub_agent_interrupted():
logger.error(
"tool_name=<%s>, tool_use_id=<%s> | cannot resume: the sub-agent's interrupted turn "
"is not available, so the interrupt response cannot be applied",
self._tool_name,
tool_use_id,
)
yield ToolResultEvent(
{
"toolUseId": tool_use_id,
"status": "error",
"content": [{"text": self._unresumable_message(invocation_state, tool_use_id)}],
}
)
return

prompt = self._interrupt_responses(invocation_state, tool_use_id)
logger.debug(
"tool_name=<%s>, tool_use_id=<%s> | resuming sub-agent from interrupt",
self._tool_name,
Expand Down Expand Up @@ -214,7 +237,9 @@ async def stream(self, tool_use: ToolUse, invocation_state: dict[str, Any], **kw

# Propagate sub-agent interrupts to the parent agent.
if result.stop_reason == "interrupt" and result.interrupts:
yield ToolInterruptEvent(tool_use, list(result.interrupts))
interrupts = list(result.interrupts)
self._stash_continuation(invocation_state, tool_use_id)
yield ToolInterruptEvent(tool_use, self._namespace_interrupts(tool_use_id, interrupts))
return

if result.structured_output:
Expand Down Expand Up @@ -257,6 +282,12 @@ def _reset_agent_state(self, tool_use_id: str) -> None:
Restores messages and state to the values captured at construction time.
This mirrors the pattern used by ``GraphNode.reset_executor_state()``.

The reset is unconditional, so exposing one ``Agent`` instance as a tool to several
orchestrators at once lets one orchestrator's call clear a turn another one has parked on an
interrupt. The parked orchestrator still resumes correctly, because it reinstates the turn
from its own interrupt record, but the other call fails; give each orchestrator its own
sub-agent instance instead of sharing one.

Args:
tool_use_id: Tool use ID for logging context.
"""
Expand All @@ -272,22 +303,199 @@ def _is_sub_agent_interrupted(self) -> bool:
"""Check whether the wrapped agent is in an activated interrupt state."""
return self._agent._interrupt_state.activated

def _build_interrupt_responses(self) -> list[InterruptResponseContent]:
"""Build interrupt response payloads from the sub-agent's interrupt state.
@staticmethod
def _namespace_prefix(tool_use_id: str) -> str:
"""Build the prefix that namespaces a sub-agent interrupt id to this tool call.

The parent agent's ``_interrupt_state.resume()`` sets ``.response`` on the shared
``Interrupt`` objects (registered by the executor), so we re-package them in the
format expected by ``Agent.stream_async``.
The tool use ID is percent-encoded so the prefix cannot contain the separator. Tool use IDs and
interrupt IDs are both model-derived strings: with a raw prefix, a tool use ID ending in the
separator plus the start of another call's interrupt IDs would match that call's answers and
route them to the wrong sub-agent.

Args:
tool_use_id: Tool use ID of this agent-as-tool call.

Returns:
List of interrupt response content blocks for resuming the sub-agent.
Prefix, separator included, for interrupt IDs belonging to this call.
"""
return f"{quote(tool_use_id, safe='')}:"

@staticmethod
def _namespace_interrupts(tool_use_id: str, interrupts: list[Interrupt]) -> list[Interrupt]:
"""Copy sub-agent interrupts with their ids namespaced by this tool call.

A sub-agent derives an interrupt id from its own toolUseId, so two sub-agents invoked in the
same turn can raise the same id. Namespacing keeps them distinct at the orchestrator level and
keeps the sub-agent-local id recoverable by stripping the prefix.

Args:
tool_use_id: Tool use ID of this agent-as-tool call.
interrupts: Interrupts raised inside the sub-agent.

Returns:
Orchestrator-visible copies carrying namespaced ids.
"""
prefix = _AgentAsTool._namespace_prefix(tool_use_id)
return [
{"interruptResponse": {"interruptId": interrupt.id, "response": interrupt.response}}
for interrupt in self._agent._interrupt_state.interrupts.values()
if interrupt.response is not None
Interrupt(id=f"{prefix}{interrupt.id}", name=interrupt.name, reason=interrupt.reason)
for interrupt in interrupts
]

@staticmethod
def _parent_agent(invocation_state: dict[str, Any]) -> Agent | None:
"""Get the orchestrator running this tool call, if the invocation state carries one."""
parent: Agent | None = invocation_state.get("agent")
return parent

@staticmethod
def _parent_awaiting_resume(invocation_state: dict[str, Any], tool_use_id: str) -> bool:
"""Check whether the orchestrator is waiting on an interrupt raised by this tool call.

Keyed on the orchestrator rather than on the sub-agent so a sub-agent that shares a session
with another caller cannot adopt a pending turn that belongs to someone else.

Args:
invocation_state: Context for the tool invocation.
tool_use_id: Tool use ID of this agent-as-tool call.

Returns:
True if the orchestrator holds an interrupt raised by this call.
"""
parent = _AgentAsTool._parent_agent(invocation_state)
if parent is None or not parent._interrupt_state.activated:
return False

prefix = _AgentAsTool._namespace_prefix(tool_use_id)
return any(interrupt_id.startswith(prefix) for interrupt_id in parent._interrupt_state.interrupts)

@staticmethod
def _interrupt_responses(invocation_state: dict[str, Any], tool_use_id: str) -> list[InterruptResponseContent]:
"""Map the orchestrator's interrupt responses back to sub-agent-local ids.

The orchestrator persists the human's answers as data, so this survives a rehydration
boundary where orchestrator and sub-agent no longer share an in-memory ``Interrupt``. An
empty list means none of the answers belong to this call, and the sub-agent re-raises its
interrupt and stays pending.

Args:
invocation_state: Context for the tool invocation.
tool_use_id: Tool use ID of this agent-as-tool call.

Returns:
Interrupt response content blocks addressed to the sub-agent.
"""
parent = _AgentAsTool._parent_agent(invocation_state)
if parent is None:
return []

prefix = _AgentAsTool._namespace_prefix(tool_use_id)
responses: list[InterruptResponseContent] = []
for response in parent._interrupt_state.context.get("responses") or []:
interrupt_id = response["interruptResponse"]["interruptId"]
if interrupt_id.startswith(prefix):
responses.append(
{
"interruptResponse": {
"interruptId": interrupt_id[len(prefix) :],
"response": response["interruptResponse"]["response"],
}
}
)

return responses

@staticmethod
def _stored_continuation(invocation_state: dict[str, Any], tool_use_id: str) -> dict[str, Any] | None:
"""Get the interrupted turn the orchestrator holds for this tool call, if there is one."""
parent = _AgentAsTool._parent_agent(invocation_state)
if parent is None:
return None

continuations: dict[str, Any] = parent._interrupt_state.context.get(_CONTINUATIONS_KEY) or {}
continuation: dict[str, Any] | None = continuations.get(tool_use_id)
return continuation

def _unresumable_message(self, invocation_state: dict[str, Any], tool_use_id: str) -> str:
"""Explain why the interrupted turn could not be reinstated, for the failed tool result."""
if self._stored_continuation(invocation_state, tool_use_id) is not None:
return (
f"Agent '{self._tool_name}' could not resume its interrupted turn: the stored turn failed to "
"load, so the interrupt response was not applied. See the logged error for the cause."
)

return (
f"Agent '{self._tool_name}' could not resume its interrupted turn. A sub-agent used with "
"preserve_context=True keeps its own state, so it needs a session manager for that state to "
"survive rehydration."
)

def _stash_continuation(self, invocation_state: dict[str, Any], tool_use_id: str) -> None:
"""Store the sub-agent's interrupted turn in the orchestrator's interrupt context.

Only for ``preserve_context=False`` sub-agents: they are ephemeral by contract and are rejected
at construction if they have a session manager, so the orchestrator holds the turn for them and
Strands persists it
with the orchestrator's own interrupt record. A sub-agent that preserves context owns its
state and keeps it in its own session.

Args:
invocation_state: Context for the tool invocation.
tool_use_id: Tool use ID of this agent-as-tool call.
"""
if self._preserve_context:
return

parent = self._parent_agent(invocation_state)
if parent is None:
return

continuations: dict[str, Any] = parent._interrupt_state.context.setdefault(_CONTINUATIONS_KEY, {})
continuations[tool_use_id] = self._agent.take_snapshot(preset="session").to_dict()
logger.debug(
"tool_name=<%s>, tool_use_id=<%s> | stored interrupted sub-agent turn for resume",
self._tool_name,
tool_use_id,
)

def _restore_continuation(self, invocation_state: dict[str, Any], tool_use_id: str) -> bool:
"""Rebuild the sub-agent's interrupted turn from the orchestrator's interrupt context.

The turn is consumed: a sub-agent that interrupts again stores a fresh one.

Args:
invocation_state: Context for the tool invocation.
tool_use_id: Tool use ID of this agent-as-tool call.

Returns:
True if the interrupted turn was restored onto the sub-agent.
"""
parent = self._parent_agent(invocation_state)
if parent is None:
return False

continuation = self._stored_continuation(invocation_state, tool_use_id)
if continuation is None:
return False

try:
self._agent.load_snapshot(Snapshot.from_dict(continuation))
except Exception as error:
Comment thread
mkmeral marked this conversation as resolved.
Resolved
# Leave the stored turn in place: a load can fail for a reason a later attempt survives,
# such as a schema version the running SDK does not accept yet, and dropping it here would
# destroy the only copy of the turn the human already answered. A failure after the first
# field has been applied leaves the sub-agent itself mismatched; the caller reports the
# error without invoking it, and an ephemeral sub-agent is reset on its next fresh call.
logger.error(
"tool_name=<%s>, tool_use_id=<%s> | failed to restore interrupted sub-agent turn: %s",
self._tool_name,
tool_use_id,
error,
)
return False

parent._interrupt_state.context[_CONTINUATIONS_KEY].pop(tool_use_id, None)
return True

@override
def get_display_properties(self) -> dict[str, str]:
"""Get properties for UI display."""
Expand Down
25 changes: 23 additions & 2 deletions strands-py/src/strands/event_loop/event_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,27 @@ async def terminal(ctx: InvokeModelContext) -> AsyncGenerator[Any, None]:
return terminal


def _park_interrupt_context(agent: "Agent", message: Message, tool_results: list[ToolResult]) -> None:
"""Rebuild an agent's interrupt context for a parked turn, keeping keys the event loop does not own.

``tool_use_message`` and ``tool_results`` describe this park, and ``responses`` belongs to the
resume that has just been consumed, so all three are refreshed here. Any other key belongs to
whoever put it there — an agent-as-tool stores the interrupted turn of an ephemeral sub-agent this
way — and has to survive so it is still there on the next resume.

Args:
agent: Agent whose turn is being parked.
message: Tool use message that triggered the interrupt.
tool_results: Results of the tools that did complete.
"""
carried = {
key: value
for key, value in agent._interrupt_state.context.items()
if key not in ("tool_use_message", "tool_results", "responses")
}
agent._interrupt_state.context = {**carried, "tool_use_message": message, "tool_results": tool_results}
Comment thread
mkmeral marked this conversation as resolved.
Resolved


async def _stop_for_interrupts(
agent: "Agent",
message: Message,
Expand All @@ -719,7 +740,7 @@ async def _stop_for_interrupts(
so interrupt persistence logic lives in one place.
"""
# Session state stored on AfterInvocationEvent.
agent._interrupt_state.context = {"tool_use_message": message, "tool_results": tool_results}
_park_interrupt_context(agent, message, tool_results)
agent._interrupt_state.activate()

agent.event_loop_metrics.end_cycle(cycle_start_time, cycle_trace)
Expand Down Expand Up @@ -860,7 +881,7 @@ async def _handle_tool_execution(
except Exception:
# Persist pending interrupts before re-raising so they aren't lost.
if interrupts:
agent._interrupt_state.context = {"tool_use_message": message, "tool_results": tool_results}
_park_interrupt_context(agent, message, tool_results)
agent._interrupt_state.activate()
raise

Expand Down
Loading
Loading