Repository navigation
fix(agents): scale aggregate tool-result budget by context window - #246
Conversation
Backport of upstream d45b8be and 168a489, plus a notice-text fix. The aggregate tool-result budget was perResultCap * 4 with no reference to the context window: 256,000 chars on a 500k window, roughly 13% of it. Once the summed tool-result text crossed that, older results were flattened to a bare notice carrying zero content bytes, and the model was shown its own successful tool calls as: [... 39610 more characters truncated; rerun with narrower args if needed] which it cannot distinguish from a tool failure. The same truncated array is what the compaction trigger measures (attempt.ts assigns it to promptHistoryMessages, which reaches both estimateLlmBoundaryTokenPressure and shouldPreemptivelyCompactBeforePrompt), so the measured prompt size stayed pinned while real session content grew and compaction never fired on tool-result pressure at all. Changes: - Aggregate budget is now max(perResultCap * 4, window * 4 * 0.5), so a 500k window allows 1,000,000 chars instead of 256,000. - calculateRecoveryAggregateToolResultChars no longer falls back to maxCharsOverride, which had silently made the aggregate equal the per-result cap (64,000) on the two persisted precheck routes. Those routes rewrite the transcript, so that fallback was destructive. - The second truncation pass writes a marker instead of clearing text to the empty string, and its accounting now uses the post-first-pass length rather than the original, which had over-credited each cleared result. - Fresh trailing tool results are protected from aggregate elision. - attempt.ts resolves the aggregate budget via resolveLiveToolResultAggregateMaxChars at both prompt-assembly sites; the local PROMPT_TOOL_RESULT_AGGREGATE_CAP_MULTIPLIER is removed. - Aggregate elision gets its own notice text stating the call succeeded. DEFAULT_SUFFIX keeps "rerun with narrower args" for the single oversized fresh result, where that advice is correct. Tests: tool-result-truncation and preemptive-compaction suites pass 132/132. Upstream test updates applied via three-way merge. Claude-Session: https://claude.ai/code/session_01DE9xpUY96ZgRsL9khtAVYS
There was a problem hiding this comment.
All reported issues were addressed across 4 files
Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
…iew notes Address review on #246: - The warn-once set of session keys now evicts the oldest entry past 1000 sessions, so a long-lived gateway no longer retains every key; covered by a red-first test through truncateOversizedToolResultsInSessionManager. - The aggregate-suffix comment is cut to the invariant it protects. - The mixed oversized-plus-medium routing test no longer asserts aggregate savings at a synthetic 20k window the route never uses; at the routing window the aggregate budget cannot bind, so the test now pins the per-result savings the route actually relies on (the 20k estimator claims stay covered in tool-result-truncation.test.ts). Claude-Session: https://claude.ai/code/session_01FSeHegCidN6qEU1sTf2KzG
There was a problem hiding this comment.
Review: APPROVE
Verified at head 847f769e92576c8aa808f9f1b833d02dcadb4008 (base boon).
Backport authenticity. Upstream commits d45b8be939a1 ("preserve fresh tool result text under aggregate cap") and 168a4890bb4b ("scale aggregate tool-result budget by context") both exist in openclaw/openclaw and are ancestors of the v2026.7.1 tag commit (compare: ahead=0) — released as claimed. The upstream patches carry the same mechanisms this PR lands: trailing-result protection (protectTrailingToolResults: Boolean(projectionState)), marker-instead-of-empty with post-first-pass accounting (clearToolResultText(baseMessage, targetTextChars)), the max(perResultMaxChars * 4, window * 4 * 0.5) formula, and the "if this drifts, truncation can hide pressure that compaction routing should see" comment. The fork's notice-text change is disclosed in the body and is stricter about the failure mode ("call succeeded … not an error") than upstream's marker.
Diff vs claims.
resolveLiveToolResultAggregateMaxCharsimplements the window-scaled budget and is wired into bothattempt.tscall sites; the oldPROMPT_TOOL_RESULT_AGGREGATE_CAP_MULTIPLIERusage is gone fromattempt.ts.calculateRecoveryAggregateToolResultCharsno longer falls back tomaxCharsOverride, so the persisted precheck routes get the real aggregate budget instead of the 64k per-result cap.- Second aggregate pass writes
AGGREGATE_ELISION_MARKERinstead of clearing to"", and accounts from the post-first-pass length — the over-credit fix checks out. - Warn-once aggregate-recovery warning is bounded (
AGGREGATE_RECOVERY_WARNING_MAX_SESSIONS = 1000, oldest evicted; Set iterates in insertion order) with a red-first test driving it throughtruncateOversizedToolResultsInSessionManager.
Cubic threads (3/3). All resolved with replies citing 847f769e925 (= current head). Re-adjudicated each against head code: the resolved-but-not-outdated unbounded-Set finding is genuinely fixed at head (bounded with eviction + test); the misleading-test-assertions finding is fixed (renamed test asserting toolResultReducibleChars === 45_000 - 16_000 and overflowTokens === 2_000 exactly); the over-long-comment nit is fixed (trimmed to two lines).
CI. At head, every job is green except security-fast, whose failure log is the brace-expansion advisory GHSA-qhr7-859c-m2p7 — unrelated to this diff and addressed by #257. checks-node-agentic-agents-embedded (which owns the touched suites) is green at head.
Caveats. Suites not run locally (no installed deps in the shared clone); the local runtime A/B numbers (69 chars → 60k intact) are the author's measurement — the mechanism is consistent with the code but I did not reproduce the live session. Agree with the rollout note: canary first and watch compaction/summarizer behavior, since compaction will now fire on sessions that previously coasted.
…263) Root version, 135 plugin manifests synced via scripts/sync-plugin-versions.ts (pnpm plugins:sync), root + 68 extension npm-shrinkwrap.json version fields and openclaw peerDependency ranges bumped, CHANGELOG section for boon.49. Shipping: #246 (tool-result aggregate budget scales with context window instead of a fixed 256k-char cap, so long tool-heavy sessions stop reading their own successful calls as failures and compaction actually fires on real pressure), #253/ENG-20866 (Chrome MCP handshake/navigate timeouts raised for real npx cold-start cost, unblocking browser-handoff live attach), #256/ ENG-20876 (session_id promoted to a real Sentry tag for the per-session reliability dashboard), #260/ENG-20968 (msteams SharePoint/OneDrive download failures surfaced through MediaFailures instead of silently dropped), #261/ ENG-21009 (Sentry node 8.49 -> 10.75.3, clearing ~12 medium Vanta/Inspector findings from its pinned otel/Prisma instrumentation chain), plus undici/ brace-expansion/axios security bumps and markdown-it/dompurify/golang.org/x/net dependency bumps. Base = 2026.6.11-boon.48. Gateway plus @openclaw/slack, @openclaw/msteams and @openclaw/diagnostics-prometheus bumped in lockstep; only @openclaw/msteams source changed in this train (#260), so a fleet-msteams.sh pass is needed on Teams hosts alongside the gateway roll. Co-authored-by: Claude Sonnet 5 <[email protected]>
Problem
The aggregate tool-result budget is
perResultCap * 4, computed with no reference to the context window. On a 500k-token window that is 256,000 chars, about 13% of the window.Once summed tool-result text crosses it, older results are flattened to a bare notice with zero content bytes, and the model is shown its own successful tool calls as:
An agent cannot distinguish that from a tool failure. In a long-lived session this reproduces as the agent reporting that its tooling is broken while every tool call in the transcript actually succeeded.
Worse, the truncated array is also what the compaction trigger measures.
attempt.tsassigns it topromptHistoryMessages, which flows into bothestimateLlmBoundaryTokenPressureandshouldPreemptivelyCompactBeforePrompt. So the measured prompt size stays pinned while real session content grows, and compaction never fires on tool-result pressure at all. Measured: the trigger's estimate held at roughly 157,850 tokens across a 3.4x growth in real content, against a bar of 483,616.Fix
Backport of upstream
d45b8be939aand168a4890bb4(both released inv2026.7.1), which apply cleanly to this file, plus a notice-text change.max(perResultCap * 4, window * 4 * 0.5)— 1,000,000 chars on a 500k window.calculateRecoveryAggregateToolResultCharsno longer falls back tomaxCharsOverride. That fallback silently made the aggregate equal the per-result cap (64,000) on the two persisted precheck routes, which rewrite the transcript, so it was destructive rather than merely lossy."", and its accounting uses the post-first-pass length instead of the original, which had over-credited every cleared result and stopped the pass early.DEFAULT_SUFFIXkeeps "rerun with narrower args" on the single-oversized-fresh-result path, where that advice is correct.Upstream's comment on the new resolver names this exact failure: "If this drifts, truncation can hide pressure that compaction routing should see."
Why not a floor instead
Raising
minKeepCharson the prompt path was considered and rejected. It activates the second pass at ~124 results, and befored45b8be939athat pass emitted empty text, which reaches the model as(no output)— strictly worse than the notice for this symptom. It also leaves the prompt over budget because of the accounting bug. The budget is the root cause; the floor is not.Risk
[tool-result-truncation] Truncated N tool result(s) for prompt historylines, and a new warning when aggregate pressure is detected. Anything keyed on the old line needs updating.Testing
tool-result-truncation.test.tsandrun/preemptive-compaction.test.ts: 132/132 pass. Upstream's test updates applied via three-way merge, no conflicts.embedded-agent-runnersuite is order-flaky independent of this change: baseline showed 38 failures, this branch 37, and the failing file sets are disjoint between consecutive runs of the same tree. Every file implicated in any single run passes in isolation on this branch.Local runtime A/B (2026-09-30)
Same scripted session on a baseline build (merge-base
cc005593361) and this branch, through the real embedded runtime:openclaw agent --local, realexectool, real prompt assembly, truncation and precheck. The model was a scripted anthropic-messages mock on a 500k window (contextTokenBudget=500000in the precheck logs); the local LLM gateway could not authenticate without boon-core running. Sixcatcalls of 60,000 chars each (360k total), then a new turn asking for the first line of the FIRST result.[... 60000 more characters truncated; rerun with narrower args if neeRESULT_1_MARKER ZEBRA-4417-KESTREL(no output)Truncated 2 tool result(s) for prompt history (maxChars=64000 aggregateBudgetChars=256000)Cost: the request body grew from 359KB to 467KB at six results. The new "call succeeded" notice and the fresh-trailing protection were not reached live: on a 500k window the mid-turn overflow guard fires first, so they rest on unit tests.
Review follow-up
boonmerged in; focused suites 67/67, both tsgo lanes, oxlint and oxfmt clean.Local end-to-end test, real stack (2026-09-30)
This change ran through the full local Boon stack before merge.
1becdc4a1e5.dist/.claude-opus-4-8-anthropicmodel (500k context window).The agent was driven from the Boon Web chat UI in a browser.
Scenario: in one turn, the agent ran
caton six files one at a time. Each file held 60,000 characters with a random marker on its first line, for 360k characters of tool output in total. That is aboveboon's old 256k aggregate budget and below the new 1M budget for a 500k window. After the sixth call, the agent had to repeat each file's first line from the tool output it had received, without re-reading.FILE1_MARKER 16D91E7F-OMEGA…FILE6_MARKER 792E055A-OMEGA)Truncated N tool result(s), aggregate notice)outcome=completed, 64sOn
boon, the local A/B above shows the same shape of session cutting the first result down to a 69-character "rerun" notice.https://claude.ai/code/session_01DE9xpUY96ZgRsL9khtAVYS
Summary by cubic
Fixes aggregate tool-result truncation so successful tool calls are no longer elided into empty notices that read as failures, and no longer hidden from compaction routing.
The aggregate budget was a fixed
perResultCap * 4(256k chars on a 500k-token window); crossing it flattened older results to zero-content notices the model interpreted as tool failures. That truncated array also fed the compaction trigger's pressure estimate, so real session growth never fired compaction. The budget now scales with the context window (max(perResultCap * 4, window * 4 * 0.5), 1M chars on 500k), aggregate elision writes a notice stating the call succeeded, fresh trailing results are protected, persisted precheck routes no longer fall back to the per-result cap, and the aggregate-recovery warning is warn-once per session against a bounded set that evicts the oldest past 1,000 sessions.Rollout notes
Written for commit 1becdc4. Summary will update on new commits.