@@ -165,12 +165,35 @@ def initialize(self, agent: "Agent", **kwargs: Any) -> None:
165165 agent .messages = self ._fix_broken_tool_use (agent .messages )
166166
167167 def _fix_broken_tool_use (self , messages : list [Message ]) -> list [Message ]:
168- """Add tool_result after orphaned tool_use messages .
168+ """Fix broken tool use/result pairs in message history .
169169
170- Before 1.15.0, strands had a bug where they persisted sessions with a potentially broken messages array.
171- This method retroactively fixes that issue by adding a tool_result outside of session management. After 1.15.0,
172- this bug is no longer present.
170+ This method handles two issues:
171+ 1. Orphaned toolUse messages without corresponding toolResult.
172+ Before 1.15.0, strands had a bug where they persisted sessions with a potentially broken messages array.
173+ This method retroactively fixes that issue by adding a tool_result outside of session management.
174+ After 1.15.0, this bug is no longer present.
175+ 2. Orphaned toolResult messages without corresponding toolUse (e.g., when pagination truncates messages)
176+
177+ Args:
178+ messages: The list of messages to fix
179+ agent_id: The agent ID for fetching previous messages
180+ removed_message_count: Number of messages removed by the conversation manager
181+
182+ Returns:
183+ Fixed list of messages with proper tool use/result pairs
173184 """
185+ # First, check if the oldest message has orphaned toolResult (no preceding toolUse) and remove it.
186+ if messages :
187+ first_message = messages [0 ]
188+ if first_message ["role" ] == "user" and any ("toolResult" in content for content in first_message ["content" ]):
189+ logger .warning (
190+ "Session message history starts with orphaned toolResult with no preceding toolUse. "
191+ "This typically happens when messages are truncated due to pagination limits. "
192+ "Removing orphaned toolResult message to maintain valid conversation structure."
193+ )
194+ messages .pop (0 )
195+
196+ # Then check for orphaned toolUse messages
174197 for index , message in enumerate (messages ):
175198 # Check all but the latest message in the messages array
176199 # The latest message being orphaned is handled in the agent class
@@ -188,7 +211,7 @@ def _fix_broken_tool_use(self, messages: list[Message]) -> list[Message]:
188211 ]
189212
190213 missing_tool_use_ids = list (set (tool_use_ids ) - set (tool_result_ids ))
191- # If there area missing tool use ids, that means the messages history is broken
214+ # If there are missing tool use ids, that means the messages history is broken
192215 if missing_tool_use_ids :
193216 logger .warning (
194217 "Session message history has an orphaned toolUse with no toolResult. "
0 commit comments