Skip to content

Commit b134543

Browse files
committed
fix: tighten midturn projection precheck scope
1 parent 270c148 commit b134543

3 files changed

Lines changed: 37 additions & 20 deletions

File tree

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

Lines changed: 9 additions & 8 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(40_000);
269+
expect(estimatedPromptTokens).toBeGreaterThan(80_000);
270270

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

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

303-
it("does not precheck a regression-sized synthetic tool-heavy transcript as over budget", () => {
303+
it("prechecks 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).toBeLessThan(168_000);
328+
expect(result.estimatedPromptTokens).toBeGreaterThan(200_000);
329329
expect(result.promptBudgetBeforeReserve).toBe(168_000);
330-
expect(result.route).toBe("fits");
331-
expect(result.overflowTokens).toBe(0);
330+
expect(result.route).not.toBe("fits");
331+
expect(result.overflowTokens).toBeGreaterThan(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("uses the normal text ratio for non-CJK tool results", () => {
520+
it("keeps the conservative 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,7 +530,8 @@ describe("preemptive-compaction", () => {
530530
prompt: "continue",
531531
});
532532

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

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

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ 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;
2728
const JSON_PAYLOAD_CHARS_PER_TOKEN = 3;
2829
const MESSAGE_BOUNDARY_OVERHEAD_TOKENS = 12;
2930
const CONTENT_BLOCK_OVERHEAD_TOKENS = 6;
@@ -112,7 +113,9 @@ function estimateContentBlockTokenPressure(
112113
}
113114

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

118121
function estimateToolResultJsonTokenPressure(value: unknown): number {

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

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -356,22 +356,35 @@ describe("installToolResultContextGuard", () => {
356356
}
357357
});
358358

359-
it("does not fire mid-turn precheck for tool-heavy history that fits after boundary projection", async () => {
359+
it("projects aggregate-over-cap tool history before mid-turn route selection", async () => {
360360
const agent = makeGuardableAgent();
361361
const contextForNextCall = [makeUser("prompt already in history")];
362-
for (let index = 0; index < 20; index += 1) {
362+
for (let index = 0; index < 40; index += 1) {
363+
contextForNextCall.push(makeAssistant(`calling tool ${index}`));
363364
contextForNextCall.push(makeToolResult(`call_${index}`, "x".repeat(12_500)));
364365
}
366+
const rawToolResultChars = contextForNextCall.reduce(
367+
(sum, message) => sum + getToolResultText(message).length,
368+
0,
369+
);
370+
expect(rawToolResultChars).toBeGreaterThan(400_000);
365371

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);
372+
try {
373+
await applyMidTurnPrecheckGuardToContext(agent, contextForNextCall, {
374+
contextWindowTokens: 200_000,
375+
contextTokenBudget: 200_000,
376+
reserveTokens: 50_000,
377+
toolResultMaxChars: 16_000,
378+
prePromptMessageCount: 1,
379+
});
380+
throw new Error("expected mid-turn precheck signal");
381+
} catch (err) {
382+
expect(err).toBeInstanceOf(MidTurnPrecheckSignal);
383+
const signal = err as MidTurnPrecheckSignal;
384+
expect(signal.request.route).toBe("compact_only");
385+
expect(signal.request.toolResultReducibleChars).toBe(0);
386+
expect(signal.request.estimatedPromptTokens).toBeLessThan(250_000);
387+
}
375388
});
376389

377390
it("uses the context window, not the pre-reserve budget, for mid-turn projection", async () => {

0 commit comments

Comments
 (0)