Skip to content

Commit 5e135e3

Browse files
authored
fix(compaction): record omitted images instead of dropping them silently (#131977)
* fix(compaction): record omitted images instead of dropping them silently Record bounded image and non-text omission markers in text-only summarization input, including image-only user messages and tool results. Reuse the history-pruning image vocabulary without changing token estimates, retention, original transcript rows, or private reasoning handling. * test(compaction): enforce exact omission marker bounds Prove that image and non-text markers add exactly 103 characters without changing visible text or tool-result truncation. Exercise misleading metadata, long unknown type names, and non-text-only messages interspersed with empty messages to protect per-message omission tracking. * test(compaction): use synthetic model naming in image fixtures * fix(compaction): bound and account for summary omission records Cap omission details across each summarizer request and preserve one aggregate overflow fact. Count the records in token estimates while preserving image pressure, and describe omission without claiming prior model processing. Repair findings 1 and 3 for PR #131977.
1 parent 304128a commit 5e135e3

6 files changed

Lines changed: 392 additions & 46 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1472,7 +1472,7 @@ packages/acp-core/src/runtime/session-identity.ts 2
14721472
packages/acp-core/src/types.ts 2
14731473
packages/agent-core/src/agent-loop.ts 3
14741474
packages/agent-core/src/harness/compaction/branch-summarization.ts 1
1475-
packages/agent-core/src/harness/compaction/compaction.ts 3
1475+
packages/agent-core/src/harness/compaction/compaction.ts 2
14761476
packages/agent-core/src/harness/messages.ts 3
14771477
packages/agent-core/src/harness/session/session.ts 1
14781478
packages/agent-core/src/harness/session/tool-result-pairing.ts 17

‎docs/concepts/compaction.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ The built-in summarizer accounts for Chinese, Japanese, and Korean (CJK) charact
2020

2121
The full conversation history stays on disk. Compaction only changes what the model sees on the next turn.
2222

23+
Built-in summarization receives text, not image pixels. Omitted images and other non-text input receive markers such as `[image data omitted from summary input]`, without claiming that a model processed the data. The first eight affected messages receive at most two fixed markers each; further omissions receive one aggregate statement. These additions, including newly retained role labels and separators, total at most 847 UTF-8 bytes per summarizer request and count toward token estimates. Existing text is not capped by this omission budget. Custom compaction providers still receive the original message content.
24+
2325
<Note>
2426
New configs default `agents.defaults.compaction.mode` to `"safeguard"` (stricter guardrails, summary quality audits). Set `mode: "default"` explicitly to opt out.
2527
</Note>

‎packages/agent-core/src/harness/compaction/compaction-image-tokens.test.ts‎

Lines changed: 226 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { describe, expect, it } from "vitest";
2-
import type { ImageContent } from "../../llm.js";
2+
import type { AssistantMessage, ImageContent, Model } from "../../llm.js";
3+
import type { AgentCoreCompletionRuntimeDeps } from "../../runtime-deps.js";
34
import type { AgentMessage } from "../../types.js";
5+
import { buildSessionContext } from "../session/session.js";
46
import type { SessionTreeEntry } from "../types.js";
5-
import { estimateTokens, findCutPoint } from "./compaction.js";
7+
import { generateBranchSummary } from "./branch-summarization.js";
8+
import { compact, estimateTokens, findCutPoint, prepareCompaction } from "./compaction.js";
69

710
const IMAGE_PAYLOAD = "a".repeat(1_500_000);
811

@@ -29,7 +32,7 @@ function toolResultImage(timestamp: number): AgentMessage {
2932
};
3033
}
3134

32-
function assistantText(text: string, timestamp: number): AgentMessage {
35+
function assistantText(text: string, timestamp: number): AssistantMessage {
3336
return {
3437
role: "assistant",
3538
content: [{ type: "text", text }],
@@ -49,6 +52,21 @@ function assistantText(text: string, timestamp: number): AgentMessage {
4952
};
5053
}
5154

55+
function summaryModel(contextWindow = 100_000): Model {
56+
return {
57+
id: "summary-model",
58+
name: "Summary Model",
59+
api: "test-api",
60+
provider: "test-provider",
61+
baseUrl: "https://example.test",
62+
reasoning: false,
63+
input: ["text"],
64+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
65+
contextWindow,
66+
maxTokens: 2048,
67+
};
68+
}
69+
5270
function messageEntry(message: AgentMessage, index: number): SessionTreeEntry {
5371
return {
5472
type: "message",
@@ -75,7 +93,17 @@ describe("estimateTokens image accounting", () => {
7593
const toolTokens = estimateTokens(toolResultImage(1));
7694

7795
expect(userTokens).toBe(toolTokens);
78-
expect(userTokens).toBe(2_000);
96+
// The 2,000-token image pressure is separate from the summary omission record.
97+
expect(userTokens).toBe(2_000 + 14);
98+
expect(
99+
estimateTokens({
100+
role: "custom",
101+
content: [imageBlock()],
102+
timestamp: 1,
103+
customType: "image",
104+
display: true,
105+
}),
106+
).toBe(userTokens);
79107
});
80108
});
81109

@@ -89,7 +117,7 @@ describe("findCutPoint with image-heavy recent turns", () => {
89117
});
90118

91119
it("matches the cut point of an equivalent text-cost control", () => {
92-
const equivalentText = "x".repeat(8_000);
120+
const equivalentText = "x".repeat(8_056);
93121
const imageEntries = buildTranscript([userImage(10), userImage(20), userImage(30)]);
94122
const textEntries = buildTranscript([
95123
userText(equivalentText, 10),
@@ -104,3 +132,196 @@ describe("findCutPoint with image-heavy recent turns", () => {
104132
expect(imageResult.firstKeptEntryIndex).toBe(textResult.firstKeptEntryIndex);
105133
});
106134
});
135+
136+
describe.each([
137+
{ splitTurn: false, completed: false },
138+
{ splitTurn: false, completed: true },
139+
{ splitTurn: true, completed: true },
140+
])(
141+
"image omission through compaction (split: $splitTurn, completed: $completed)",
142+
({ splitTurn, completed }) => {
143+
it.each(["user", "toolResult"] as const)(
144+
"records an image-only %s message in summary input and rebuilt context",
145+
async (role) => {
146+
const messages: AgentMessage[] =
147+
role === "user"
148+
? [userImage(1)]
149+
: [
150+
userText("Inspect the screenshot", 1),
151+
{
152+
...assistantText("", 2),
153+
content: [{ type: "toolCall", id: "call-1", name: "screenshot", arguments: {} }],
154+
stopReason: "toolUse",
155+
},
156+
toolResultImage(3),
157+
];
158+
if (completed) {
159+
messages.push(assistantText("The screenshot was inspected", 4));
160+
}
161+
if (!splitTurn) {
162+
messages.push(userText("Continue with the next task", 5));
163+
}
164+
const entries = messages.map(messageEntry);
165+
const originalEntries = structuredClone(entries);
166+
const lastEntry = entries.at(-1);
167+
const preparation = prepareCompaction(entries, {
168+
enabled: true,
169+
reserveTokens: 1_000,
170+
keepRecentTokens: 1,
171+
});
172+
if (!preparation.ok || !preparation.value || !lastEntry) {
173+
throw new Error("expected image history to be compactable");
174+
}
175+
expect(preparation.value.isSplitTurn).toBe(splitTurn);
176+
expect(preparation.value.firstKeptEntryId).toBe(lastEntry.id);
177+
178+
const model = summaryModel();
179+
const prompts: string[] = [];
180+
const result = await compact(
181+
preparation.value,
182+
model,
183+
undefined,
184+
undefined,
185+
undefined,
186+
undefined,
187+
undefined,
188+
undefined,
189+
{
190+
completeSimple: async (_model, context) => {
191+
const content = context.messages[0]?.content;
192+
if (!Array.isArray(content) || content.length !== 1 || content[0]?.type !== "text") {
193+
throw new Error("expected one text-only summarization input");
194+
}
195+
prompts.push(content[0].text);
196+
// Echo only the supplied conversation: the callback cannot invent an omission fact.
197+
const conversation = content[0].text
198+
.split("<conversation>\n")[1]
199+
?.split("\n</conversation>")[0];
200+
return assistantText(conversation || "No conversation content", 6);
201+
},
202+
},
203+
);
204+
if (!result.ok) {
205+
throw result.error;
206+
}
207+
const marker = "[image data omitted from summary input]";
208+
expect(prompts).toHaveLength(1);
209+
expect
210+
.soft(prompts[0])
211+
.toContain(`${role === "user" ? "[User]" : "[Tool result]"}: ${marker}`);
212+
expect(prompts[0]).not.toContain(IMAGE_PAYLOAD);
213+
expect(prompts[0]).not.toContain("already processed by model");
214+
215+
const context = buildSessionContext([
216+
...entries,
217+
{
218+
type: "compaction",
219+
id: "compaction-1",
220+
parentId: lastEntry.id,
221+
timestamp: new Date(7).toISOString(),
222+
...result.value,
223+
},
224+
]);
225+
expect.soft(context.messages[0]).toMatchObject({
226+
role: "compactionSummary",
227+
summary: expect.stringContaining(marker),
228+
});
229+
expect(context.messages.at(-1)).toEqual(messages.at(-1));
230+
expect(JSON.stringify(context.messages)).not.toContain(IMAGE_PAYLOAD);
231+
expect(entries).toEqual(originalEntries);
232+
},
233+
);
234+
},
235+
);
236+
237+
describe.each(["ordinary", "split", "branch"] as const)("%s summary omission budget", (mode) => {
238+
it.each(["image", "audio"])(
239+
"bounds many %s messages at the completion boundary",
240+
async (type) => {
241+
const model = summaryModel(type === "image" ? 1_000_000 : 8192);
242+
const messages: AgentMessage[] = [
243+
userText("Inspect attachments", 0),
244+
...Array.from(
245+
{ length: 200 },
246+
(_, i) =>
247+
({
248+
role: "toolResult",
249+
toolCallId: `call-${i}`,
250+
toolName: "inspect",
251+
isError: false,
252+
timestamp: i + 1,
253+
content: [{ type, data: "PAYLOAD_SENTINEL", mimeType: "image/png" }],
254+
}) as AgentMessage,
255+
),
256+
];
257+
const entries = messages.map(messageEntry);
258+
const conversations: string[] = [];
259+
const runtime: AgentCoreCompletionRuntimeDeps = {
260+
completeSimple: async (_model, context) => {
261+
const content = context.messages[0]?.content;
262+
if (!Array.isArray(content) || content[0]?.type !== "text") {
263+
throw new Error("expected summary prompt");
264+
}
265+
const conversation = content[0].text
266+
.split("<conversation>\n")[1]
267+
?.split("\n</conversation>")[0];
268+
if (!conversation) {
269+
throw new Error("expected conversation");
270+
}
271+
conversations.push(conversation);
272+
return assistantText("Summary", 202);
273+
},
274+
};
275+
let result;
276+
if (mode === "branch") {
277+
result = await generateBranchSummary(entries, {
278+
model,
279+
apiKey: "test-key",
280+
signal: new AbortController().signal,
281+
runtime,
282+
});
283+
} else {
284+
entries.push(
285+
messageEntry(
286+
mode === "split" ? assistantText("Retained answer", 201) : userText("Next task", 201),
287+
entries.length,
288+
),
289+
);
290+
const preparation = prepareCompaction(entries, {
291+
enabled: true,
292+
reserveTokens: 1000,
293+
keepRecentTokens: 1,
294+
});
295+
if (!preparation.ok || !preparation.value) {
296+
throw new Error("expected compactable history");
297+
}
298+
expect(preparation.value.isSplitTurn).toBe(mode === "split");
299+
result = await compact(
300+
preparation.value,
301+
model,
302+
undefined,
303+
undefined,
304+
undefined,
305+
undefined,
306+
undefined,
307+
undefined,
308+
runtime,
309+
);
310+
}
311+
expect(result.ok).toBe(true);
312+
expect(conversations).toHaveLength(1);
313+
const conversation = conversations[0];
314+
if (!conversation) {
315+
throw new Error("expected captured conversation");
316+
}
317+
expect(
318+
Buffer.byteLength(conversation) - Buffer.byteLength("[User]: Inspect attachments"),
319+
).toBeLessThanOrEqual(847);
320+
expect(conversation.match(/\[Tool result\]:/g)).toHaveLength(8);
321+
expect(
322+
conversation.split("[More image/non-text data omitted from summary input]"),
323+
).toHaveLength(2);
324+
expect(conversation).not.toMatch(/PAYLOAD_SENTINEL|already processed by model/);
325+
},
326+
);
327+
});

‎packages/agent-core/src/harness/compaction/compaction.ts‎

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import {
3737
extractSummaryText,
3838
type FileOperations,
3939
formatFileOperations,
40-
getCompactionContentBlockText,
40+
getCompactionContent,
4141
mergeSummaryFileOperations,
4242
serializeConversation,
4343
stringifyCompactionValue,
@@ -278,18 +278,16 @@ export function shouldCompact(
278278
export const IMAGE_BLOCK_TOKENS = 2_000;
279279
const IMAGE_BLOCK_CHARS = IMAGE_BLOCK_TOKENS * CHARS_PER_TOKEN_ESTIMATE;
280280

281-
function countContentBlockChars(
282-
content: Array<{ type: string; content?: unknown; text?: string }>,
281+
function countContentChars(
282+
content: string | Array<{ type: string; content?: unknown; text?: string }>,
283283
): number {
284-
let chars = 0;
285-
for (const block of content) {
286-
if (block.type === "image") {
287-
chars += IMAGE_BLOCK_CHARS;
288-
} else {
289-
chars += estimateStringChars(getCompactionContentBlockText(block));
290-
}
291-
}
292-
return chars;
284+
const { text, omissionText } = getCompactionContent(content);
285+
const images =
286+
typeof content === "string" ? 0 : content.filter((block) => block.type === "image").length;
287+
// Charge the largest role/separator even for mixed text. Any suppressed message's
288+
// minimum 56-character charge also covers the serializer's single 55-character overflow.
289+
const omissionChars = omissionText ? omissionText.length + "\n\n[Tool result]: ".length : 0;
290+
return estimateStringChars(text) + images * IMAGE_BLOCK_CHARS + omissionChars;
293291
}
294292

295293
/** Estimate token count for one message using a conservative character heuristic. */
@@ -301,17 +299,6 @@ export function estimateTokens(message: AgentMessage): number {
301299
const harnessMessage = message as HarnessMessage;
302300

303301
switch (harnessMessage.role) {
304-
case "user": {
305-
const content = (
306-
harnessMessage as { content: string | Array<{ type: string; text?: string }> }
307-
).content;
308-
if (typeof content === "string") {
309-
chars = estimateStringChars(content);
310-
} else if (Array.isArray(content)) {
311-
chars = countContentBlockChars(content);
312-
}
313-
return Math.ceil(chars / CHARS_PER_TOKEN_ESTIMATE);
314-
}
315302
case "assistant": {
316303
const assistant = harnessMessage;
317304
for (const block of assistant.content) {
@@ -327,13 +314,10 @@ export function estimateTokens(message: AgentMessage): number {
327314
}
328315
return Math.ceil(chars / CHARS_PER_TOKEN_ESTIMATE);
329316
}
317+
case "user":
330318
case "custom":
331319
case "toolResult": {
332-
if (typeof harnessMessage.content === "string") {
333-
chars = estimateStringChars(harnessMessage.content);
334-
} else {
335-
chars = countContentBlockChars(harnessMessage.content);
336-
}
320+
chars = countContentChars(harnessMessage.content);
337321
return Math.ceil(chars / CHARS_PER_TOKEN_ESTIMATE);
338322
}
339323
case "bashExecution": {

0 commit comments

Comments
 (0)