Skip to content

Commit 50069fd

Browse files
committed
fix(agents): preserve fresh tool result text under aggregate cap
1 parent 2913d3a commit 50069fd

2 files changed

Lines changed: 201 additions & 23 deletions

File tree

‎src/agents/embedded-agent-runner/tool-result-truncation.test.ts‎

Lines changed: 130 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,7 @@ describe("truncateOversizedToolResultsInMessages", () => {
493493
);
494494
});
495495

496-
it("keeps prompt projections byte-stable as history grows", () => {
496+
it("keeps prompt projections stable while enforcing aggregate recovery as history grows", () => {
497497
const prefix = [
498498
makeToolResult("p".repeat(15_000), "prefix_1"),
499499
makeToolResult("q".repeat(15_000), "prefix_2"),
@@ -521,8 +521,14 @@ describe("truncateOversizedToolResultsInMessages", () => {
521521
);
522522

523523
expect(first.truncatedCount).toBe(4);
524-
expect(second.truncatedCount).toBe(1);
525-
expect(second.messages.slice(0, messages.length)).toEqual(first.messages);
524+
expect(second.truncatedCount).toBe(2);
525+
expect(
526+
second.messages.reduce(
527+
(sum, message) =>
528+
sum + (message.role === "toolResult" ? getToolResultTextLength(message) : 0),
529+
0,
530+
),
531+
).toBeLessThanOrEqual(12_000);
526532
expect(second.messages.every((message) => getToolResultTextLength(message) <= 12_000)).toBe(
527533
true,
528534
);
@@ -541,7 +547,7 @@ describe("truncateOversizedToolResultsInMessages", () => {
541547
stableState,
542548
);
543549
const stableSecond = truncateOversizedToolResultsInMessages(
544-
[...stableHistory, makeToolResult("c".repeat(15_000), "stable_3")],
550+
[...stableHistory, makeToolResult("c".repeat(3_000), "stable_3")],
545551
128_000,
546552
12_000,
547553
12_000,
@@ -552,7 +558,7 @@ describe("truncateOversizedToolResultsInMessages", () => {
552558
const stableThird = truncateOversizedToolResultsInMessages(
553559
[
554560
...stableHistory,
555-
makeToolResult("c".repeat(15_000), "stable_3"),
561+
makeToolResult("c".repeat(3_000), "stable_3"),
556562
makeToolResult("d".repeat(15_000), "stable_4"),
557563
],
558564
128_000,
@@ -564,7 +570,7 @@ describe("truncateOversizedToolResultsInMessages", () => {
564570
const stableFourth = truncateOversizedToolResultsInMessages(
565571
[
566572
...stableHistory,
567-
makeToolResult("c".repeat(15_000), "stable_3"),
573+
makeToolResult("c".repeat(3_000), "stable_3"),
568574
makeToolResult("d".repeat(15_000), "stable_4"),
569575
makeToolResult("e".repeat(15_000), "stable_5"),
570576
],
@@ -577,6 +583,124 @@ describe("truncateOversizedToolResultsInMessages", () => {
577583
expect(lastText && getToolResultTextLength(lastText)).toBeLessThanOrEqual(12_000);
578584
});
579585

586+
it("preserves fresh trailing tool results when aggregate history is already saturated", () => {
587+
const projectionState = createToolResultPromptProjectionState();
588+
const history: AgentMessage[] = [];
589+
for (let index = 0; index < 50; index++) {
590+
history.push(makeAssistantMessage(`call ${index}`));
591+
history.push(makeToolResult("x".repeat(4_000), `history_${index}`));
592+
}
593+
history.push(makeUserMessage("run echo"));
594+
595+
const first = truncateOversizedToolResultsInMessages(
596+
history,
597+
1_000_000,
598+
8_000,
599+
32_000,
600+
projectionState,
601+
);
602+
expect(first.truncatedCount).toBeGreaterThan(0);
603+
604+
const freshOutput = "ABC";
605+
const second = truncateOversizedToolResultsInMessages(
606+
[...history, makeAssistantMessage("running exec"), makeToolResult(freshOutput, "fresh_exec")],
607+
1_000_000,
608+
8_000,
609+
32_000,
610+
projectionState,
611+
);
612+
613+
const freshResult = second.messages.at(-1);
614+
const totalChars = second.messages.reduce(
615+
(sum, message) =>
616+
sum + (message.role === "toolResult" ? getToolResultTextLength(message) : 0),
617+
0,
618+
);
619+
expect(freshResult?.role).toBe("toolResult");
620+
expect(freshResult && getFirstToolResultText(freshResult)).toBe(freshOutput);
621+
expect(totalChars).toBeLessThanOrEqual(32_000);
622+
});
623+
624+
it("caps oversized fresh trailing tool results without clearing them for aggregate recovery", () => {
625+
const projectionState = createToolResultPromptProjectionState();
626+
const history: AgentMessage[] = [];
627+
for (let index = 0; index < 50; index++) {
628+
history.push(makeAssistantMessage(`call ${index}`));
629+
history.push(makeToolResult("x".repeat(4_000), `history_${index}`));
630+
}
631+
history.push(makeUserMessage("run large command"));
632+
633+
truncateOversizedToolResultsInMessages(history, 1_000_000, 8_000, 32_000, projectionState);
634+
635+
const second = truncateOversizedToolResultsInMessages(
636+
[
637+
...history,
638+
makeAssistantMessage("running exec"),
639+
makeToolResult("z".repeat(20_000), "fresh_large_exec"),
640+
],
641+
1_000_000,
642+
8_000,
643+
32_000,
644+
projectionState,
645+
);
646+
647+
const freshResult = second.messages.at(-1);
648+
const freshText = freshResult ? getFirstToolResultText(freshResult) : "";
649+
const totalChars = second.messages.reduce(
650+
(sum, message) =>
651+
sum + (message.role === "toolResult" ? getToolResultTextLength(message) : 0),
652+
0,
653+
);
654+
expect(freshResult?.role).toBe("toolResult");
655+
expect(freshText.length).toBeGreaterThan(0);
656+
expect(freshText.length).toBeLessThanOrEqual(8_000);
657+
expect(freshText).toContain("truncated");
658+
expect(totalChars).toBeLessThanOrEqual(32_000);
659+
});
660+
661+
it("falls back to trimming fresh trailing batches that exceed the aggregate budget", () => {
662+
const projectionState = createToolResultPromptProjectionState();
663+
const messages: AgentMessage[] = [makeUserMessage("run several tools")];
664+
for (let index = 0; index < 5; index++) {
665+
messages.push(makeToolResult(String(index).repeat(8_000), `fresh_${index}`));
666+
}
667+
668+
const result = truncateOversizedToolResultsInMessages(
669+
messages,
670+
1_000_000,
671+
8_000,
672+
32_000,
673+
projectionState,
674+
);
675+
const toolResults = result.messages.filter((message) => message.role === "toolResult");
676+
const totalChars = toolResults.reduce(
677+
(sum, message) => sum + getToolResultTextLength(message),
678+
0,
679+
);
680+
681+
expect(result.truncatedCount).toBeGreaterThan(0);
682+
expect(totalChars).toBeLessThanOrEqual(32_000);
683+
expect(toolResults.every((message) => getFirstToolResultText(message).length > 0)).toBe(true);
684+
});
685+
686+
it("keeps aggregate elision markers inside tiny explicit budgets", () => {
687+
const messages: AgentMessage[] = [
688+
makeToolResult("a".repeat(100), "tiny_1"),
689+
makeToolResult("b".repeat(100), "tiny_2"),
690+
makeToolResult("c".repeat(100), "tiny_3"),
691+
];
692+
693+
const result = truncateOversizedToolResultsInMessages(messages, 128_000, 100, 8);
694+
const totalChars = result.messages.reduce(
695+
(sum, message) =>
696+
sum + (message.role === "toolResult" ? getToolResultTextLength(message) : 0),
697+
0,
698+
);
699+
700+
expect(result.truncatedCount).toBeGreaterThan(0);
701+
expect(totalChars).toBeLessThanOrEqual(8);
702+
});
703+
580704
it("does not restore filtered image blocks when reusing a projection", () => {
581705
const projectionState = createToolResultPromptProjectionState();
582706
const source = makeToolResult("x".repeat(15_000), "image_call");

‎src/agents/embedded-agent-runner/tool-result-truncation.ts‎

Lines changed: 71 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ const DEFAULT_SUFFIX = (truncatedChars: number) =>
6363
formatContextLimitTruncationNotice(truncatedChars);
6464
const COMPACT_RECOVERY_SUFFIX = (truncatedChars: number) =>
6565
`[... ${Math.max(1, Math.floor(truncatedChars))} chars truncated; narrow args]`;
66+
const AGGREGATE_ELISION_MARKER =
67+
"[tool result elided: aggregate tool-result budget exceeded; rerun the command if the output is needed]";
6668

6769
function resolveSuffixFactory(
6870
suffix: ToolResultTruncationOptions["suffix"],
@@ -399,6 +401,7 @@ export function truncateOversizedToolResultsInMessages(
399401
maxChars,
400402
aggregateBudgetChars,
401403
minKeepChars: RECOVERY_MIN_KEEP_CHARS,
404+
protectTrailingToolResults: Boolean(projectionState),
402405
});
403406
if (projectionState) {
404407
for (const [index] of messages.entries()) {
@@ -596,8 +599,12 @@ function buildAggregateToolResultReplacements(params: {
596599
branch: ToolResultBranchEntry[];
597600
aggregateBudgetChars: number;
598601
minKeepChars?: number;
602+
protectTrailingToolResults?: boolean;
599603
}): ToolResultReplacement[] {
600604
const minKeepChars = params.minKeepChars ?? MIN_KEEP_CHARS;
605+
const protectedEntryIds = params.protectTrailingToolResults
606+
? getTrailingToolResultEntryIds(params.branch)
607+
: new Set<string>();
601608
const candidates = params.branch
602609
.map((entry, index) => ({ entry, index }))
603610
.filter(
@@ -617,6 +624,7 @@ function buildAggregateToolResultReplacements(params: {
617624
message: item.entry.message,
618625
textLength: getToolResultTextLength(item.entry.message),
619626
aggregateEligible: item.entry.aggregateEligible !== false,
627+
protectedFromAggregateRecovery: protectedEntryIds.has(item.entry.id),
620628
}))
621629
.filter((item) => item.textLength > 0);
622630

@@ -638,16 +646,33 @@ function buildAggregateToolResultReplacements(params: {
638646

639647
let remainingReduction = totalChars - params.aggregateBudgetChars;
640648
const replacements: Array<{ entryId: string; message: AgentMessage }> = [];
641-
642-
// Spend aggregate reduction on older entries first so fresh tool output stays intact.
643-
for (const candidate of candidates
644-
.filter((item) => item.aggregateEligible)
649+
const aggregateRecoveryCandidates = candidates
650+
.filter((item) => !item.protectedFromAggregateRecovery)
645651
.toSorted((a, b) => {
646652
if (a.index !== b.index) {
647653
return a.index - b.index;
648654
}
649655
return b.textLength - a.textLength;
650-
})) {
656+
});
657+
const recoveryCandidates = [
658+
...aggregateRecoveryCandidates.filter((item) => item.aggregateEligible),
659+
...(protectedEntryIds.size > 0
660+
? aggregateRecoveryCandidates.filter((item) => !item.aggregateEligible)
661+
: []),
662+
...(protectedEntryIds.size > 0
663+
? candidates
664+
.filter((item) => item.protectedFromAggregateRecovery)
665+
.toSorted((a, b) => {
666+
if (a.index !== b.index) {
667+
return a.index - b.index;
668+
}
669+
return b.textLength - a.textLength;
670+
})
671+
: []),
672+
];
673+
674+
// Spend aggregate reduction on older entries first so fresh tool output stays intact.
675+
for (const candidate of recoveryCandidates) {
651676
if (remainingReduction <= 0) {
652677
break;
653678
}
@@ -673,18 +698,18 @@ function buildAggregateToolResultReplacements(params: {
673698
}
674699

675700
if (remainingReduction > 0) {
676-
for (const candidate of candidates.filter((item) => item.aggregateEligible)) {
701+
for (const candidate of recoveryCandidates) {
677702
if (remainingReduction <= 0) {
678703
break;
679704
}
680705
const existingReplacement = replacements.find(
681706
(replacement) => replacement.entryId === candidate.entryId,
682707
);
683-
const emptyMessage = clearToolResultText(existingReplacement?.message ?? candidate.message);
684-
const actualReduction = Math.max(
685-
0,
686-
candidate.textLength - getToolResultTextLength(emptyMessage),
687-
);
708+
const baseMessage = existingReplacement?.message ?? candidate.message;
709+
const baseTextLength = getToolResultTextLength(baseMessage);
710+
const targetTextChars = Math.max(0, baseTextLength - remainingReduction);
711+
const emptyMessage = clearToolResultText(baseMessage, targetTextChars);
712+
const actualReduction = Math.max(0, baseTextLength - getToolResultTextLength(emptyMessage));
688713
if (actualReduction <= 0) {
689714
continue;
690715
}
@@ -704,18 +729,45 @@ function buildAggregateToolResultReplacements(params: {
704729
return replacements;
705730
}
706731

707-
function clearToolResultText(message: AgentMessage): AgentMessage {
732+
function getTrailingToolResultEntryIds(branch: ToolResultBranchEntry[]): Set<string> {
733+
const ids = new Set<string>();
734+
for (let index = branch.length - 1; index >= 0; index--) {
735+
const entry = branch[index];
736+
if (
737+
entry?.type !== "message" ||
738+
!entry.message ||
739+
(entry.message as { role?: string }).role !== "toolResult"
740+
) {
741+
break;
742+
}
743+
ids.add(entry.id);
744+
}
745+
return ids;
746+
}
747+
748+
function clearToolResultText(
749+
message: AgentMessage,
750+
maxTextChars = Number.POSITIVE_INFINITY,
751+
): AgentMessage {
708752
const content = (message as { content?: unknown }).content;
709753
if (!Array.isArray(content)) {
710754
return message;
711755
}
756+
let remainingTextBudget = Math.max(0, Math.floor(maxTextChars));
712757
return {
713758
...message,
714-
content: content.map((block) =>
715-
block && typeof block === "object" && (block as { type?: unknown }).type === "text"
716-
? Object.assign({}, block, { text: "" })
717-
: block,
718-
),
759+
content: content.map((block) => {
760+
if (!isToolResultTextBlock(block)) {
761+
return block;
762+
}
763+
const replacementText =
764+
remainingTextBudget > 0 ? AGGREGATE_ELISION_MARKER.slice(0, remainingTextBudget) : "";
765+
remainingTextBudget = Math.max(0, remainingTextBudget - replacementText.length);
766+
return Object.assign({}, block, {
767+
text: replacementText,
768+
...(typeof block.content === "string" ? { content: replacementText } : {}),
769+
});
770+
}),
719771
} as AgentMessage;
720772
}
721773

@@ -800,6 +852,7 @@ function buildToolResultReplacementPlan(params: {
800852
maxChars: number;
801853
aggregateBudgetChars: number;
802854
minKeepChars?: number;
855+
protectTrailingToolResults?: boolean;
803856
}): {
804857
replacements: ToolResultReplacement[];
805858
oversizedReplacementCount: number;
@@ -825,6 +878,7 @@ function buildToolResultReplacementPlan(params: {
825878
branch: oversizedTrimmedBranch,
826879
aggregateBudgetChars: params.aggregateBudgetChars,
827880
minKeepChars,
881+
protectTrailingToolResults: params.protectTrailingToolResults,
828882
});
829883
const aggregateReducibleChars = calculateReplacementReduction(
830884
oversizedTrimmedBranch,

0 commit comments

Comments
 (0)