Q16: compact older tool results inside a run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-08 04:26:09 -04:00
1 parent 469f2f2c35
commit f42ab62dbd
3 files changed
+119

No files matched your search

@@ -0,0 +1,27 @@
import type { AgentTurnMessage } from "./provider-tool-turn";
const KEEP_RECENT_TOOL_TURNS = 3;
const ELIDE_ABOVE_CHARS = 600;
const PREVIEW_CHARS = 300;
/** Older tool results shrink to a preview; the latest turns stay verbatim. */
export function compactToolHistory(messages: AgentTurnMessage[]): { messages: AgentTurnMessage[]; elided: number } {
const toolTurnIndexes = messages.flatMap((message, index) => (message.role === "tool" ? [index] : []));
const compactBefore = toolTurnIndexes.length > KEEP_RECENT_TOOL_TURNS
? toolTurnIndexes[toolTurnIndexes.length - KEEP_RECENT_TOOL_TURNS]
: 0;
let elided = 0;
const compacted = messages.map((message, index) => {
if (message.role !== "tool" || index >= compactBefore) return message;
const results = message.results.map((result) => {
if (result.output.length <= ELIDE_ABOVE_CHARS || result.output.startsWith("[Earlier result of ")) return result;
elided += 1;
return {
...result,
output: `[Earlier result of ${result.toolName} elided to save context (${result.output.length} chars). It began: ${result.output.slice(0, PREVIEW_CHARS)}… Call ${result.toolName} again if you need the full result.]`,
};
});
return { ...message, results };
});
return { messages: compacted, elided };
}