Skip to content

Commit dd74b4a

Browse files
committed
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 5f80527 commit dd74b4a

6 files changed

Lines changed: 323 additions & 152 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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ 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. Image-only user messages and tool results remain visible in its input as `[image data removed - already processed by model]`. Other omitted non-text input receives a similar marker, with at most two fixed markers per message. Custom compaction providers still receive the original message content.
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.
2424

2525
<Note>
2626
New configs default `agents.defaults.compaction.mode` to `"safeguard"` (stricter guardrails, summary quality audits). Set `mode: "default"` explicitly to opt out.
Lines changed: 215 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { describe, expect, it } from "vitest";
22
import type { AssistantMessage, ImageContent, Model } from "../../llm.js";
3+
import type { AgentCoreCompletionRuntimeDeps } from "../../runtime-deps.js";
34
import type { AgentMessage } from "../../types.js";
45
import { buildSessionContext } from "../session/session.js";
56
import type { SessionTreeEntry } from "../types.js";
7+
import { generateBranchSummary } from "./branch-summarization.js";
68
import { compact, estimateTokens, findCutPoint, prepareCompaction } from "./compaction.js";
79

810
const IMAGE_PAYLOAD = "a".repeat(1_500_000);
@@ -50,6 +52,21 @@ function assistantText(text: string, timestamp: number): AssistantMessage {
5052
};
5153
}
5254

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+
5370
function messageEntry(message: AgentMessage, index: number): SessionTreeEntry {
5471
return {
5572
type: "message",
@@ -76,7 +93,17 @@ describe("estimateTokens image accounting", () => {
7693
const toolTokens = estimateTokens(toolResultImage(1));
7794

7895
expect(userTokens).toBe(toolTokens);
79-
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);
80107
});
81108
});
82109

@@ -90,7 +117,7 @@ describe("findCutPoint with image-heavy recent turns", () => {
90117
});
91118

92119
it("matches the cut point of an equivalent text-cost control", () => {
93-
const equivalentText = "x".repeat(8_000);
120+
const equivalentText = "x".repeat(8_056);
94121
const imageEntries = buildTranscript([userImage(10), userImage(20), userImage(30)]);
95122
const textEntries = buildTranscript([
96123
userText(equivalentText, 10),
@@ -106,104 +133,195 @@ describe("findCutPoint with image-heavy recent turns", () => {
106133
});
107134
});
108135

109-
describe.each([false, true])("image omission through compaction (split turn: %s)", (splitTurn) => {
110-
it.each(["user", "toolResult"] as const)(
111-
"records an image-only %s message in summary input and rebuilt context",
112-
async (role) => {
113-
const messages: AgentMessage[] =
114-
role === "user"
115-
? [userImage(1)]
116-
: [
117-
userText("Inspect the screenshot", 1),
118-
{
119-
...assistantText("", 2),
120-
content: [{ type: "toolCall", id: "call-1", name: "screenshot", arguments: {} }],
121-
stopReason: "toolUse",
122-
},
123-
toolResultImage(3),
124-
];
125-
messages.push(assistantText("The screenshot was inspected", 4));
126-
if (!splitTurn) {
127-
messages.push(userText("Continue with the next task", 5));
128-
}
129-
const entries = messages.map(messageEntry);
130-
const originalEntries = structuredClone(entries);
131-
const lastEntry = entries.at(-1);
132-
const preparation = prepareCompaction(entries, {
133-
enabled: true,
134-
reserveTokens: 1_000,
135-
keepRecentTokens: 1,
136-
});
137-
if (!preparation.ok || !preparation.value || !lastEntry) {
138-
throw new Error("expected image history to be compactable");
139-
}
140-
expect(preparation.value.isSplitTurn).toBe(splitTurn);
141-
expect(preparation.value.firstKeptEntryId).toBe(lastEntry.id);
142-
143-
const model: Model = {
144-
id: "umbreon-latest",
145-
name: "Umbreon Latest",
146-
api: "test-api",
147-
provider: "test-provider",
148-
baseUrl: "https://example.test",
149-
reasoning: false,
150-
input: ["text"],
151-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
152-
contextWindow: 100_000,
153-
maxTokens: 8_000,
154-
};
155-
const prompts: string[] = [];
156-
const result = await compact(
157-
preparation.value,
158-
model,
159-
undefined,
160-
undefined,
161-
undefined,
162-
undefined,
163-
undefined,
164-
undefined,
165-
{
166-
completeSimple: async (_model, context) => {
167-
const content = context.messages[0]?.content;
168-
if (!Array.isArray(content) || content.length !== 1 || content[0]?.type !== "text") {
169-
throw new Error("expected one text-only summarization input");
170-
}
171-
prompts.push(content[0].text);
172-
// Echo only the supplied conversation: the callback cannot invent an omission fact.
173-
const conversation = content[0].text
174-
.split("<conversation>\n")[1]
175-
?.split("\n</conversation>")[0];
176-
return assistantText(conversation || "No conversation content", 6);
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,
177223
},
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);
178273
},
179-
);
180-
if (!result.ok) {
181-
throw result.error;
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+
);
182310
}
183-
const marker = "[image data removed - already processed by model]";
184-
expect(prompts).toHaveLength(1);
185-
expect
186-
.soft(prompts[0])
187-
.toContain(`${role === "user" ? "[User]" : "[Tool result]"}: ${marker}`);
188-
expect(prompts[0]).not.toContain(IMAGE_PAYLOAD);
189-
190-
const context = buildSessionContext([
191-
...entries,
192-
{
193-
type: "compaction",
194-
id: "compaction-1",
195-
parentId: lastEntry.id,
196-
timestamp: new Date(7).toISOString(),
197-
...result.value,
198-
},
199-
]);
200-
expect.soft(context.messages[0]).toMatchObject({
201-
role: "compactionSummary",
202-
summary: expect.stringContaining(marker),
203-
});
204-
expect(context.messages.at(-1)).toEqual(messages.at(-1));
205-
expect(JSON.stringify(context.messages)).not.toContain(IMAGE_PAYLOAD);
206-
expect(entries).toEqual(originalEntries);
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/);
207325
},
208326
);
209327
});

0 commit comments

Comments
 (0)