Skip to content

Commit 270c148

Browse files
committed
fix: align mid-turn tool-result precheck estimate
1 parent 81d0f3f commit 270c148

4 files changed

Lines changed: 88 additions & 18 deletions

File tree

‎src/agents/embedded-agent-runner/run/preemptive-compaction.test.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -266,13 +266,13 @@ describe("preemptive-compaction", () => {
266266
prompt: "continue",
267267
});
268268

269-
expect(estimatedPromptTokens).toBeGreaterThan(80_000);
269+
expect(estimatedPromptTokens).toBeGreaterThan(40_000);
270270

271271
const result = shouldPreemptivelyCompactBeforePrompt({
272272
messages,
273273
systemPrompt: "sys",
274274
prompt: "continue",
275-
contextTokenBudget: 96_000,
275+
contextTokenBudget: 60_000,
276276
reserveTokens: 20_000,
277277
});
278278

@@ -300,7 +300,7 @@ describe("preemptive-compaction", () => {
300300
expect(estimatedPromptTokens).toBeGreaterThan(30_000);
301301
});
302302

303-
it("prechecks a regression-sized synthetic tool-heavy transcript as over budget", () => {
303+
it("does not precheck a regression-sized synthetic tool-heavy transcript as over budget", () => {
304304
const toolResultCharsPerMessage = Math.ceil(427_000 / 120);
305305
const generalCharsPerMessage = Math.ceil((503_000 - 427_000) / 121);
306306
const messages: AgentMessage[] = [];
@@ -325,10 +325,10 @@ describe("preemptive-compaction", () => {
325325
reserveTokens: 32_000,
326326
});
327327

328-
expect(result.estimatedPromptTokens).toBeGreaterThan(200_000);
328+
expect(result.estimatedPromptTokens).toBeLessThan(168_000);
329329
expect(result.promptBudgetBeforeReserve).toBe(168_000);
330-
expect(result.route).not.toBe("fits");
331-
expect(result.overflowTokens).toBeGreaterThan(0);
330+
expect(result.route).toBe("fits");
331+
expect(result.overflowTokens).toBe(0);
332332
});
333333

334334
it("caps reserve tokens so small context models keep usable prompt budget", () => {
@@ -517,7 +517,7 @@ describe("preemptive-compaction", () => {
517517
expect(aboveCutoff - belowCutoff).toBeLessThanOrEqual(2);
518518
});
519519

520-
it("keeps the conservative ratio for non-CJK tool results", () => {
520+
it("uses the normal text ratio for non-CJK tool results", () => {
521521
const latinText = "alpha beta gamma delta epsilon ".repeat(1000);
522522
const toolResultTokens = estimateLlmBoundaryTokenPressure({
523523
messages: [makeToolResultMessage(latinText)],
@@ -530,8 +530,7 @@ describe("preemptive-compaction", () => {
530530
prompt: "continue",
531531
});
532532

533-
expect(toolResultTokens).toBeGreaterThan(assistantTokens * 1.5);
534-
expect(toolResultTokens).toBeLessThan(assistantTokens * 2.5);
533+
expect(Math.abs(toolResultTokens - assistantTokens)).toBeLessThanOrEqual(5);
535534
});
536535

537536
it("applies the CJK-aware ratio to JSON tool-result payloads", () => {

‎src/agents/embedded-agent-runner/run/preemptive-compaction.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ export const PREEMPTIVE_OVERFLOW_ERROR_TEXT =
2424
"Context overflow: prompt too large for the model (precheck).";
2525

2626
const ESTIMATED_CHARS_PER_TOKEN = 4;
27-
const TOOL_RESULT_CHARS_PER_TOKEN = 2;
2827
const JSON_PAYLOAD_CHARS_PER_TOKEN = 3;
2928
const MESSAGE_BOUNDARY_OVERHEAD_TOKENS = 12;
3029
const CONTENT_BLOCK_OVERHEAD_TOKENS = 6;
@@ -113,9 +112,7 @@ function estimateContentBlockTokenPressure(
113112
}
114113

115114
function estimateToolResultStringTokenPressure(text: string): number {
116-
const conservativeToolResultEstimate = Math.ceil(text.length / TOOL_RESULT_CHARS_PER_TOKEN);
117-
const cjkAwareEstimate = estimateStringTokenPressure(text);
118-
return Math.max(conservativeToolResultEstimate, cjkAwareEstimate);
115+
return estimateStringTokenPressure(text);
119116
}
120117

121118
function estimateToolResultJsonTokenPressure(value: unknown): number {

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

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,13 +327,14 @@ describe("installToolResultContextGuard", () => {
327327
expectOpenClawTruncation(getToolResultText(transformed[0]));
328328
});
329329

330-
it("raises a structured mid-turn precheck signal after a new tool result overflows", async () => {
330+
it("raises a structured mid-turn precheck signal after projected tool results overflow", async () => {
331331
// The signal carries route metadata so the run loop can compact/truncate
332332
// without guessing from a generic overflow error.
333333
const agent = makeGuardableAgent();
334334
const contextForNextCall = [
335335
makeUser("prompt already in history"),
336336
makeToolResult("call_big", "x".repeat(80_000)),
337+
makeToolResult("call_big_2", "y".repeat(80_000)),
337338
];
338339

339340
try {
@@ -349,12 +350,48 @@ describe("installToolResultContextGuard", () => {
349350
expect(err).toBeInstanceOf(MidTurnPrecheckSignal);
350351
const signal = err as MidTurnPrecheckSignal;
351352
expect(signal.name).toBe("MidTurnPrecheckSignal");
352-
expect(signal.request.route).toBe("compact_then_truncate");
353+
expect(signal.request.route).toBe("compact_only");
353354
expect(typeof signal.request.overflowTokens).toBe("number");
354355
expect(typeof signal.request.toolResultReducibleChars).toBe("number");
355356
}
356357
});
357358

359+
it("does not fire mid-turn precheck for tool-heavy history that fits after boundary projection", async () => {
360+
const agent = makeGuardableAgent();
361+
const contextForNextCall = [makeUser("prompt already in history")];
362+
for (let index = 0; index < 20; index += 1) {
363+
contextForNextCall.push(makeToolResult(`call_${index}`, "x".repeat(12_500)));
364+
}
365+
366+
const transformed = await applyMidTurnPrecheckGuardToContext(agent, contextForNextCall, {
367+
contextWindowTokens: 200_000,
368+
contextTokenBudget: 200_000,
369+
reserveTokens: 50_000,
370+
toolResultMaxChars: 16_000,
371+
prePromptMessageCount: 1,
372+
});
373+
374+
expect(transformed).toBe(contextForNextCall);
375+
});
376+
377+
it("uses the context window, not the pre-reserve budget, for mid-turn projection", async () => {
378+
const agent = makeGuardableAgent();
379+
const contextForNextCall = [makeUser("prompt already in history")];
380+
for (let index = 0; index < 40; index += 1) {
381+
contextForNextCall.push(makeToolResult(`call_${index}`, "x".repeat(22_500)));
382+
}
383+
384+
await expect(
385+
applyMidTurnPrecheckGuardToContext(agent, contextForNextCall, {
386+
contextWindowTokens: 200_000,
387+
contextTokenBudget: 120_000,
388+
reserveTokens: 20_000,
389+
toolResultMaxChars: 16_000,
390+
prePromptMessageCount: 1,
391+
}),
392+
).rejects.toBeInstanceOf(MidTurnPrecheckSignal);
393+
});
394+
358395
it("does not run mid-turn precheck when no new tool result was appended", async () => {
359396
const agent = makeGuardableAgent();
360397
const contextForNextCall = [makeUser("u".repeat(80_000))];
@@ -604,7 +641,11 @@ describe("installContextEngineLoopHook", () => {
604641
toolResultMaxChars: 16_000,
605642
});
606643

607-
const messages = [makeUser("first"), makeToolResult("call_1", "x".repeat(80_000))];
644+
const messages = [
645+
makeUser("first"),
646+
makeToolResult("call_1", "x".repeat(80_000)),
647+
makeToolResult("call_2", "y".repeat(80_000)),
648+
];
608649

609650
await expect(callTransform(agent, messages)).rejects.toBeInstanceOf(MidTurnPrecheckSignal);
610651
expect(engine.afterTurn).toHaveBeenCalledTimes(1);
@@ -625,7 +666,11 @@ describe("installContextEngineLoopHook", () => {
625666
toolResultMaxChars: 16_000,
626667
});
627668

628-
const messages = [makeUser("first"), makeToolResult("call_1", "x".repeat(80_000))];
669+
const messages = [
670+
makeUser("first"),
671+
makeToolResult("call_1", "x".repeat(80_000)),
672+
makeToolResult("call_2", "y".repeat(80_000)),
673+
];
629674
const transformed = await callTransform(agent, messages);
630675

631676
expect(transformed).toBe(compactedView);

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ import {
2222
invalidateMessageCharsCacheEntry,
2323
isToolResultMessage,
2424
} from "./tool-result-char-estimator.js";
25+
import {
26+
createToolResultPromptProjectionState,
27+
resolveLiveToolResultAggregateMaxChars,
28+
truncateOversizedToolResultsInMessages,
29+
} from "./tool-result-truncation.js";
2530

2631
const SINGLE_TOOL_RESULT_CONTEXT_SHARE = 0.5;
2732
const PREEMPTIVE_OVERFLOW_RATIO = 0.9;
@@ -318,6 +323,25 @@ function toMidTurnPrecheckRequest(
318323
};
319324
}
320325

326+
function projectMessagesForMidTurnPrecheck(params: {
327+
messages: AgentMessage[];
328+
contextWindowTokens: number;
329+
toolResultMaxChars?: number;
330+
}): AgentMessage[] {
331+
const toolResultAggregateMaxChars = resolveLiveToolResultAggregateMaxChars({
332+
contextWindowTokens: params.contextWindowTokens,
333+
perResultMaxChars: params.toolResultMaxChars,
334+
});
335+
const projection = truncateOversizedToolResultsInMessages(
336+
params.messages,
337+
params.contextWindowTokens,
338+
params.toolResultMaxChars,
339+
toolResultAggregateMaxChars,
340+
createToolResultPromptProjectionState(),
341+
);
342+
return projection.messages;
343+
}
344+
321345
/**
322346
* Per-iteration `afterTurn` + `assemble` wrapper for sessions where
323347
* the context engine owns compaction. Lets the engine compact inside
@@ -527,8 +551,13 @@ export function installToolResultContextGuard(params: {
527551
// Use the same post-truncation view the runtime will send to the next model call.
528552
// Recovery re-applies truncation to the persisted session manager, so
529553
// this precheck is only a routing signal, not the source of truth.
530-
const precheck = shouldPreemptivelyCompactBeforePrompt({
554+
const precheckMessages = projectMessagesForMidTurnPrecheck({
531555
messages: contextMessages,
556+
contextWindowTokens,
557+
toolResultMaxChars: params.midTurnPrecheck.toolResultMaxChars,
558+
});
559+
const precheck = shouldPreemptivelyCompactBeforePrompt({
560+
messages: precheckMessages,
532561
systemPrompt: params.midTurnPrecheck.getSystemPrompt?.(),
533562
// During a tool loop, the active user prompt is already part of messages.
534563
prompt: "",

0 commit comments

Comments
 (0)