Skip to content

Commit d79c197

Browse files
fix(agents): preserve active tool result batch at boundary
1 parent 7cb3b21 commit d79c197

2 files changed

Lines changed: 110 additions & 3 deletions

File tree

‎src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,66 @@ describe("normalizeMessagesForLlmBoundary", () => {
395395
expect(input.filter((message) => message.role === "toolResult")).toHaveLength(30);
396396
});
397397

398+
it("preserves an oversized latest assistant tool-call batch before pruning older results", () => {
399+
const historicalBatch = Array.from({ length: 10 }, (_, index) => {
400+
const toolCallId = `old_call_${index}`;
401+
return [
402+
{
403+
role: "assistant",
404+
content: [{ type: "toolCall", id: toolCallId, name: "exec", arguments: {} }],
405+
timestamp: index * 2,
406+
},
407+
{
408+
role: "toolResult",
409+
toolCallId,
410+
toolName: "exec",
411+
content: [{ type: "text", text: `old output ${index}` }],
412+
timestamp: index * 2 + 1,
413+
},
414+
];
415+
}).flat();
416+
const latestCallIds = Array.from({ length: 25 }, (_, index) => `latest_call_${index}`);
417+
const latestBatch = [
418+
{
419+
role: "assistant",
420+
content: latestCallIds.map((id) => ({
421+
type: "toolCall",
422+
id,
423+
name: "exec",
424+
arguments: {},
425+
})),
426+
timestamp: 100,
427+
},
428+
...latestCallIds.map((toolCallId, index) => ({
429+
role: "toolResult",
430+
toolCallId,
431+
toolName: "exec",
432+
content: [{ type: "text", text: `latest output ${index}` }],
433+
timestamp: 101 + index,
434+
})),
435+
];
436+
const input = [...historicalBatch, ...latestBatch];
437+
438+
const output = normalizeMessagesForLlmBoundary(
439+
input as Parameters<typeof normalizeMessagesForLlmBoundary>[0],
440+
) as unknown as Array<Record<string, unknown>>;
441+
const keptToolResultIds = output
442+
.filter((message) => message.role === "toolResult")
443+
.map((message) => message.toolCallId);
444+
const keptAssistantToolCallIds = output.flatMap((message) => {
445+
if (message.role !== "assistant" || !Array.isArray(message.content)) {
446+
return [];
447+
}
448+
return message.content.flatMap((block) => {
449+
const record = block as { type?: unknown; id?: unknown };
450+
return record.type === "toolCall" && typeof record.id === "string" ? [record.id] : [];
451+
});
452+
});
453+
454+
expect(keptToolResultIds).toEqual(latestCallIds);
455+
expect(keptAssistantToolCallIds).toEqual(latestCallIds);
456+
});
457+
398458
it("collapses single-text-block user content arrays to plain strings", () => {
399459
// Both current and historical single-text-block user messages must
400460
// serialize identically — this is the form-canonicalization half of the

‎src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,53 @@ export function normalizeMessagesForLlmBoundary(
5757

5858
function pruneExcessToolResultsForProviderBoundary(messages: AgentMessage[]): AgentMessage[] {
5959
const toolResultIndexes: number[] = [];
60+
const toolCallAssistantIndexes = new Map<string, number>();
6061
for (let index = 0; index < messages.length; index += 1) {
61-
if (isBoundaryToolResultMessage(messages[index])) {
62+
const message = messages[index];
63+
if (isBoundaryToolResultMessage(message)) {
6264
toolResultIndexes.push(index);
6365
}
66+
if (message?.role === "assistant") {
67+
for (const toolCallId of extractAssistantToolCallIds(message)) {
68+
toolCallAssistantIndexes.set(toolCallId, index);
69+
}
70+
}
6471
}
6572

6673
if (toolResultIndexes.length <= LLM_BOUNDARY_MAX_TOOL_RESULT_MESSAGES) {
6774
return messages;
6875
}
6976

70-
const keptToolResultIndexes = new Set(
71-
toolResultIndexes.slice(-LLM_BOUNDARY_MAX_TOOL_RESULT_MESSAGES),
77+
let latestToolResultAssistantIndex = -1;
78+
for (const index of toolResultIndexes) {
79+
const id = extractBoundaryToolResultId(messages[index]);
80+
if (!id) {
81+
continue;
82+
}
83+
const assistantIndex = toolCallAssistantIndexes.get(id);
84+
if (assistantIndex !== undefined && assistantIndex > latestToolResultAssistantIndex) {
85+
latestToolResultAssistantIndex = assistantIndex;
86+
}
87+
}
88+
89+
const currentBatchToolResultIndexes =
90+
latestToolResultAssistantIndex >= 0
91+
? toolResultIndexes.filter((index) => {
92+
const id = extractBoundaryToolResultId(messages[index]);
93+
return id ? toolCallAssistantIndexes.get(id) === latestToolResultAssistantIndex : false;
94+
})
95+
: [];
96+
const olderToolResultIndexes = toolResultIndexes.filter(
97+
(index) => !currentBatchToolResultIndexes.includes(index),
7298
);
99+
const olderToolResultBudget = Math.max(
100+
0,
101+
LLM_BOUNDARY_MAX_TOOL_RESULT_MESSAGES - currentBatchToolResultIndexes.length,
102+
);
103+
const keptToolResultIndexes = new Set([
104+
...(olderToolResultBudget > 0 ? olderToolResultIndexes.slice(-olderToolResultBudget) : []),
105+
...currentBatchToolResultIndexes,
106+
]);
73107
const droppedToolResultIndexes = new Set(
74108
toolResultIndexes.filter((index) => !keptToolResultIndexes.has(index)),
75109
);
@@ -172,6 +206,19 @@ function isAssistantToolCallType(type: unknown): boolean {
172206
);
173207
}
174208

209+
function extractAssistantToolCallIds(
210+
message: Extract<AgentMessage, { role: "assistant" }>,
211+
): string[] {
212+
const content = message.content;
213+
if (!Array.isArray(content)) {
214+
return [];
215+
}
216+
return content.flatMap((block) => {
217+
const id = extractAssistantToolCallBlockId(block);
218+
return id ? [id] : [];
219+
});
220+
}
221+
175222
function extractAssistantToolCallBlockId(block: unknown): string | null {
176223
if (!block || typeof block !== "object") {
177224
return null;

0 commit comments

Comments
 (0)