Skip to content

Commit 62b418d

Browse files
authored
fix(agents): retain images within tool-result context limits (#120808)
1 parent e14b36c commit 62b418d

2 files changed

Lines changed: 313 additions & 10 deletions

File tree

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
// Real native image results must retain a bounded, truthful visual context.
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { expectDefined } from "@openclaw/normalization-core";
5+
import { describe, expect, it } from "vitest";
6+
import type { OpenClawConfig } from "../../config/types.openclaw.js";
7+
import { encodePngRgba, fillPixel } from "../../media/png-encode.js";
8+
import type { AgentMessage } from "../runtime/index.js";
9+
import { castAgentMessage } from "../test-helpers/agent-message-fixtures.js";
10+
import { createImageTool } from "../tools/image-tool.js";
11+
import {
12+
createMessageCharEstimateCache,
13+
estimateMessageCharsCached,
14+
TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE,
15+
} from "./tool-result-char-estimator.js";
16+
import { installToolResultContextGuard } from "./tool-result-context-guard.js";
17+
18+
type ContentBlock = { type: string; text?: string; data?: string; mimeType?: string };
19+
20+
function createRequiredImageTool() {
21+
const config: OpenClawConfig = {
22+
agents: { defaults: { imageMaxDimensionPx: 32 } },
23+
};
24+
return expectDefined(
25+
createImageTool({
26+
config,
27+
agentDir: join(tmpdir(), "openclaw-native-image-context-test"),
28+
modelHasVision: true,
29+
}),
30+
"native-vision image tool is available",
31+
);
32+
}
33+
34+
function makeDistinctImageRef(index: number): string {
35+
const width = 64;
36+
const pixels = Buffer.alloc(width * width * 4);
37+
for (let y = 0; y < width; y += 1) {
38+
for (let x = 0; x < width; x += 1) {
39+
fillPixel(pixels, x, y, width, (index + 1) * 17, x * 3, y * 3);
40+
}
41+
}
42+
return `data:image/png;base64,${encodePngRgba(pixels, width, width).toString("base64")}`;
43+
}
44+
45+
async function executeNativeImageTool(imageCount: number): Promise<AgentMessage> {
46+
const result = await createRequiredImageTool().execute("native-image-context", {
47+
images: Array.from({ length: imageCount }, (_, index) => makeDistinctImageRef(index)),
48+
});
49+
const content = result.content as ContentBlock[];
50+
expect(content[0]?.text).toBe(
51+
`Loaded ${imageCount} image${imageCount === 1 ? "" : "s"} for direct visual inspection.`,
52+
);
53+
expect(content.filter((block) => block.type === "image")).toHaveLength(imageCount);
54+
expect(content.filter((block) => block.type === "image")).toEqual(
55+
expect.arrayContaining([expect.objectContaining({ mimeType: "image/jpeg" })]),
56+
);
57+
expect(result.details).toMatchObject({ transport: "native", media: { outbound: false } });
58+
return castAgentMessage({
59+
role: "toolResult",
60+
toolCallId: "native-image-context",
61+
toolName: "image",
62+
isError: false,
63+
timestamp: 0,
64+
...result,
65+
});
66+
}
67+
68+
async function projectForContext(
69+
source: AgentMessage,
70+
contextWindowTokens: number,
71+
): Promise<AgentMessage> {
72+
const agent: {
73+
transformContext?: (messages: AgentMessage[], signal: AbortSignal) => Promise<AgentMessage[]>;
74+
} = {};
75+
installToolResultContextGuard({ agent, contextWindowTokens });
76+
const transformed = await expectDefined(agent.transformContext, "installed context guard")(
77+
[source],
78+
new AbortController().signal,
79+
);
80+
return expectDefined(transformed[0], "guarded native image result");
81+
}
82+
83+
function blocksOf(message: AgentMessage): ContentBlock[] {
84+
return (message as { content: ContentBlock[] }).content;
85+
}
86+
87+
function expectWithinExistingCap(message: AgentMessage, contextWindowTokens: number): void {
88+
const existingCap = Math.max(
89+
1_024,
90+
Math.floor(contextWindowTokens * TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE * 0.5),
91+
);
92+
expect(estimateMessageCharsCached(message, createMessageCharEstimateCache())).toBeLessThanOrEqual(
93+
existingCap,
94+
);
95+
}
96+
97+
describe("native image tool result context projection", () => {
98+
it.each([
99+
{ contextWindowTokens: 8_000, loadedImages: 1, visibleImages: 0 },
100+
{ contextWindowTokens: 32_000, loadedImages: 3, visibleImages: 1 },
101+
{ contextWindowTokens: 128_000, loadedImages: 9, visibleImages: 7 },
102+
])(
103+
"preserves a fitting sanitized image prefix in a $contextWindowTokens-token window",
104+
async ({ contextWindowTokens, loadedImages, visibleImages }) => {
105+
const source = await executeNativeImageTool(loadedImages);
106+
const originalSnapshot = structuredClone(source);
107+
const projected = await projectForContext(source, contextWindowTokens);
108+
const sourceImages = blocksOf(source).filter((block) => block.type === "image");
109+
const projectedImages = blocksOf(projected).filter((block) => block.type === "image");
110+
const projectedText = blocksOf(projected)
111+
.filter((block) => block.type === "text")
112+
.map((block) => block.text)
113+
.join("\n");
114+
115+
expect(projectedImages).toEqual(sourceImages.slice(0, visibleImages));
116+
expect(projectedText).toMatch(
117+
new RegExp(
118+
`${loadedImages - visibleImages} images? .*omitted|omitted.*${loadedImages - visibleImages} images?`,
119+
"i",
120+
),
121+
);
122+
expect(projectedText).toMatch(/context/i);
123+
if (visibleImages === 0) {
124+
expect(projectedText).toMatch(
125+
/no images? (?:fit|included|available)|images? (?:could not|cannot) (?:fit|be included)/i,
126+
);
127+
}
128+
expectWithinExistingCap(projected, contextWindowTokens);
129+
expect(source).toEqual(originalSnapshot);
130+
expect((source as { details?: unknown }).details).toMatchObject({
131+
media: { outbound: false },
132+
});
133+
expect(projected).not.toHaveProperty("details");
134+
},
135+
);
136+
137+
it("leaves sanitized native images and private details untouched when all blocks fit", async () => {
138+
const source = await executeNativeImageTool(2);
139+
const projected = await projectForContext(source, 32_768);
140+
141+
expect(projected).toBe(source);
142+
expect(blocksOf(projected).filter((block) => block.type === "image")).toHaveLength(2);
143+
expect((projected as { details?: unknown }).details).toEqual(
144+
(source as { details?: unknown }).details,
145+
);
146+
expectWithinExistingCap(projected, 32_768);
147+
});
148+
149+
it("preserves mixed text, unknown blocks, CJK content, image order, and original privacy", async () => {
150+
const native = await executeNativeImageTool(3);
151+
const nativeBlocks = blocksOf(native);
152+
const unknown = { type: "custom", value: { label: "bounded metadata" } };
153+
const cjk = { type: "text", text: "画像の順序を維持する 🖼️" };
154+
const source = castAgentMessage({
155+
...native,
156+
toolName: "read",
157+
content: [nativeBlocks[0], nativeBlocks[1], unknown, cjk, nativeBlocks[2], nativeBlocks[3]],
158+
details: { media: { outbound: false }, privateReference: "private-fixture-reference" },
159+
});
160+
const projected = await projectForContext(source, 32_000);
161+
const content = blocksOf(projected);
162+
163+
expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]);
164+
expect(content.map((block) => block.type)).toEqual(["text", "image", "custom", "text", "text"]);
165+
expect(content).toContain(unknown);
166+
expect(content).toContain(cjk);
167+
expect(content.at(-1)?.text).toMatch(/2 images? .*omitted|omitted.*2 images?/i);
168+
expectWithinExistingCap(projected, 32_000);
169+
expect(projected).not.toHaveProperty("details");
170+
expect(JSON.stringify(blocksOf(projected))).not.toContain("private-fixture-reference");
171+
expect(
172+
(source as { details?: { media?: { outbound?: boolean } } }).details?.media?.outbound,
173+
).toBe(false);
174+
});
175+
176+
it.each([1, 2])(
177+
"retains a fitting image when oversized CJK text accompanies %i sanitized images",
178+
async (loadedImages) => {
179+
const native = await executeNativeImageTool(loadedImages);
180+
const nativeBlocks = blocksOf(native);
181+
const source = castAgentMessage({
182+
...native,
183+
content: [{ type: "text", text: "画像🖼️".repeat(8_000) }, ...nativeBlocks.slice(1)],
184+
});
185+
const projected = await projectForContext(source, 32_000);
186+
const content = blocksOf(projected);
187+
188+
expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]);
189+
expect(content[0]?.text).toContain("画像");
190+
const boundedText = expectDefined(content[0]?.text, "bounded image context text");
191+
expect(Buffer.from(boundedText, "utf8").toString("utf8")).toBe(boundedText);
192+
expectWithinExistingCap(projected, 32_000);
193+
if (loadedImages === 1) {
194+
expect(content.some((block) => block.text?.includes("0 images"))).toBe(false);
195+
} else {
196+
expect(content.some((block) => block.text?.includes("1 image omitted"))).toBe(true);
197+
}
198+
expect(blocksOf(source).filter((block) => block.type === "image")).toHaveLength(loadedImages);
199+
},
200+
);
201+
202+
it("keeps a fitting image without letting oversized text starve a later text block", async () => {
203+
const native = await executeNativeImageTool(2);
204+
const nativeBlocks = blocksOf(native);
205+
const trailingText = { type: "text", text: "retain the image description" };
206+
const source = castAgentMessage({
207+
...native,
208+
content: [
209+
{ type: "text", text: "画像🖼️".repeat(8_000) },
210+
nativeBlocks[1],
211+
trailingText,
212+
nativeBlocks[2],
213+
],
214+
});
215+
const projected = await projectForContext(source, 32_000);
216+
const content = blocksOf(projected);
217+
218+
expect(content.filter((block) => block.type === "image")).toEqual([nativeBlocks[1]]);
219+
const boundedText = expectDefined(content[0]?.text, "bounded multi-block image context text");
220+
expect(Buffer.from(boundedText, "utf8").toString("utf8")).toBe(boundedText);
221+
expect(content).toContainEqual(trailingText);
222+
expect(content.at(-1)?.text).toContain("1 image omitted");
223+
expectWithinExistingCap(projected, 32_000);
224+
});
225+
});

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

Lines changed: 88 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
getToolResultText,
2121
isToolResultMessage,
2222
} from "./tool-result-char-estimator.js";
23-
import { truncateToolResultText } from "./tool-result-truncation.js";
23+
import { truncateToolResultMessage, truncateToolResultText } from "./tool-result-truncation.js";
2424

2525
const SINGLE_TOOL_RESULT_CONTEXT_SHARE = 0.5;
2626
const TRANSCRIPT_PROMPT_TEXT_KEY = "__openclawTranscriptPromptText";
@@ -130,16 +130,19 @@ function stripTranscriptPromptMarkers(messages: AgentMessage[]): AgentMessage[]
130130
return changed ? stripped : messages;
131131
}
132132

133-
function replaceToolResultText(msg: AgentMessage, text: string): AgentMessage {
133+
function replaceToolResultContent(
134+
msg: AgentMessage,
135+
replacement: string | unknown[],
136+
): AgentMessage {
134137
const content = (msg as { content?: unknown }).content;
135-
const replacementContent =
136-
typeof content === "string" || content === undefined ? text : [{ type: "text", text }];
137-
138138
const sourceRecord = msg as unknown as Record<string, unknown>;
139139
const { details: _details, ...rest } = sourceRecord;
140140
return {
141141
...rest,
142-
content: replacementContent,
142+
content:
143+
typeof replacement === "string" && !(typeof content === "string" || content === undefined)
144+
? [{ type: "text", text: replacement }]
145+
: replacement,
143146
} as AgentMessage;
144147
}
145148

@@ -160,26 +163,101 @@ function truncateToolResultToChars(
160163
if (estimatedChars <= maxChars) {
161164
return msg;
162165
}
166+
let rawText = getToolResultText(msg);
167+
const content = (msg as { content?: unknown }).content;
168+
if (Array.isArray(content)) {
169+
const isImage = (block: unknown) =>
170+
Boolean(block) && typeof block === "object" && (block as { type?: unknown }).type === "image";
171+
const isText = (block: unknown): block is { type: "text"; text: string } =>
172+
Boolean(block) &&
173+
typeof block === "object" &&
174+
(block as { type?: unknown }).type === "text" &&
175+
typeof (block as { text?: unknown }).text === "string";
176+
const imageCount = content.filter(isImage).length;
177+
if (imageCount > 0) {
178+
const omissionNotice = (retainedImages: number) => {
179+
const omittedImages = imageCount - retainedImages;
180+
return (
181+
`[${omittedImages} image${omittedImages === 1 ? "" : "s"} omitted from context` +
182+
`${retainedImages === 0 ? "; no images fit the context limit" : ""}; rerun with fewer images]`
183+
);
184+
};
185+
186+
// Reserve images first; shared multi-block truncation preserves later text
187+
// while the existing weighted estimator enforces the unchanged hard cap.
188+
for (let retainedImages = imageCount; retainedImages >= 0; retainedImages -= 1) {
189+
let seenImages = 0;
190+
const retainedContent = content.filter(
191+
(block) => !isImage(block) || ++seenImages <= retainedImages,
192+
);
193+
const notice =
194+
retainedImages < imageCount
195+
? [{ type: "text", text: omissionNotice(retainedImages) }]
196+
: [];
197+
const reservedChars = estimateMessageCharsCached(
198+
replaceToolResultContent(msg, [
199+
...retainedContent.filter((block) => !isText(block)),
200+
...notice,
201+
]),
202+
cache,
203+
);
204+
const availableTextChars = maxChars - reservedChars;
205+
if (availableTextChars < 0 || (availableTextChars === 0 && retainedContent.some(isText))) {
206+
continue;
207+
}
208+
let textBudget = availableTextChars;
209+
while (true) {
210+
const bounded = truncateToolResultMessage(
211+
replaceToolResultContent(msg, retainedContent),
212+
textBudget,
213+
);
214+
const projectedContent = (bounded as { content: unknown[] }).content;
215+
if (
216+
retainedContent.some((block, index) => {
217+
const projectedBlock = projectedContent[index];
218+
return (
219+
isText(block) && block.text && (!isText(projectedBlock) || !projectedBlock.text)
220+
);
221+
})
222+
) {
223+
break;
224+
}
225+
const projected = replaceToolResultContent(msg, [...projectedContent, ...notice]);
226+
const projectedChars = estimateMessageCharsCached(projected, cache);
227+
if (projectedChars <= maxChars) {
228+
return projected;
229+
}
230+
const adjustedTextBudget = Math.floor(
231+
(textBudget * availableTextChars) / (projectedChars - reservedChars),
232+
);
233+
if (adjustedTextBudget <= 0 || adjustedTextBudget >= textBudget) {
234+
break;
235+
}
236+
textBudget = adjustedTextBudget;
237+
}
238+
}
239+
rawText = omissionNotice(0) + (rawText ? `\n\n${rawText}` : "");
240+
}
241+
}
163242

164-
const rawText = getToolResultText(msg);
165243
if (!rawText) {
166244
const omittedChars = Math.max(
167245
1,
168246
estimateBudgetToRawChars(Math.max(estimatedChars - maxChars, 1)),
169247
);
170-
return replaceToolResultText(msg, formatContextLimitTruncationNotice(omittedChars));
248+
return replaceToolResultContent(msg, formatContextLimitTruncationNotice(omittedChars));
171249
}
172250

173251
if (maxChars <= 0) {
174-
return replaceToolResultText(msg, formatContextLimitTruncationNotice(rawText.length));
252+
return replaceToolResultContent(msg, formatContextLimitTruncationNotice(rawText.length));
175253
}
176254

177255
const truncatedText = truncateToolResultText(rawText, maxChars, {
178256
minKeepChars: 0,
179257
minimumRawWeight: TOOL_RESULT_CHARS_PER_TOKEN_ESTIMATE,
180258
preserveImportantTail: false,
181259
});
182-
return replaceToolResultText(msg, truncatedText);
260+
return replaceToolResultContent(msg, truncatedText);
183261
}
184262

185263
function enforceToolResultLimit(params: {

0 commit comments

Comments
 (0)