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

+6
View File
@@ -6,6 +6,7 @@ import { executeWorkspaceTool, isWorkspaceTool, WORKSPACE_TOOLS } from "./agent-
import { canonicalMentionHandle } from "../../shared/mention-handles";
import type { AgentTurnMessage, ToolDefinition } from "./provider-tool-turn";
import { isComposioTool, executeComposioTool } from "./composio/composio-tool-bridge";
import { compactToolHistory } from "./run-context-compaction";
const MAX_ITERATIONS = 12;
@@ -50,6 +51,11 @@ export async function runAgentLoop(deps: AgentRunLoopDeps, input: AgentRunLoopIn
let lastRequestId = "";
for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration += 1) {
const compaction = compactToolHistory(messages);
if (compaction.elided > 0) {
messages.splice(0, messages.length, ...compaction.messages);
console.info(`[run-loop] iteration ${iteration}: elided ${compaction.elided} earlier tool result(s)`);
}
const turn = await deps.providers.runToolTurn({
orgId: input.orgId,
providerId: input.providerId,
@@ -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 };
}