Fix #475: Implement sanitizeToolPairs for tool call/result integrity

This commit addresses the issue where history compression was creating orphaned

tool_call/tool_result pairs that cause Anthropic API errors. Changes include:

- Added sanitizeToolPairs() helper function to validate tool call/result pairs

- Applied sanitization in forceCompression() to ensure message integrity after cutting

- Applied sanitization in summarizeSession() to remove orphaned results during truncation

- Ensures tool calls and their results remain paired after compression operations
This commit is contained in:
liugangjian 2026-03-05 10:01:19 +08:00
parent daf94a30f3
commit 0b8052ceb8

View file

@ -1157,7 +1157,7 @@ func (al *AgentLoop) forceCompression(agent *AgentInstance, sessionKey string) {
newHistory = append(newHistory, history[len(history)-1]) // Last message newHistory = append(newHistory, history[len(history)-1]) // Last message
// Update session // Update session
agent.Sessions.SetHistory(sessionKey, newHistory) agent.Sessions.SetHistory(sessionKey, sanitizeToolPairs(newHistory))
agent.Sessions.Save(sessionKey) agent.Sessions.Save(sessionKey)
logger.WarnCF("agent", "Forced compression executed", map[string]any{ logger.WarnCF("agent", "Forced compression executed", map[string]any{