fix: prevent merging assistant messages with tool_calls

Adjacent assistant messages where any message contains tool_calls
were being merged by MergeAdjacentMessages, causing tool_calls to
be silently dropped. This led to orphaned tool results that could
not match any toolUse in history, resulting in Kiro API returning
'Improperly formed request.'

Now assistant messages with tool_calls are kept separate during
merge, preserving the tool call chain integrity.
This commit is contained in:
Darley
2026-02-12 01:53:40 +08:00
parent 2334a2b174
commit 5a2cf0d53c

View File

@@ -33,6 +33,13 @@ func MergeAdjacentMessages(messages []gjson.Result) []gjson.Result {
continue
}
// Don't merge assistant messages that have tool_calls - these must stay separate
// so that subsequent tool results can match their tool_call IDs
if currentRole == "assistant" && (msg.Get("tool_calls").Exists() || lastMsg.Get("tool_calls").Exists()) {
merged = append(merged, msg)
continue
}
if currentRole == lastRole {
// Merge content from current message into last message
mergedContent := mergeMessageContent(lastMsg, msg)