feat(server): prune stale thinking and oversized tool outputs on context overflow
DU
1h ago+703+703+012345678901234567890123456789-12-12-01234567890123456789
Summary
Prevents long tool-calling agent sessions (e.g. mini-swe-agent 2.2.4 on Terminal-Bench 4.0) from failing with HTTP 400 ContextWindowExceededError or starving into tiny finish=length turns when stale <think> reasoning or large tool dumps push a multi-turn conversation past max_ctx.
Root cause
Models like Qwen3.8-Flash-Next default to preserve_thinking=true so normal turns keep interleaved reasoning and 99%+ prefix-cache hit rates. Clients that run long single-user assistant+tool loops without compaction accumulate hundreds of thousands of tokens of old reasoning_content (e.g. photonic-waveguide-routing hit 262,158 tokens with ~88% stale <think> and only ~30K tokens of actual task/tool content).
What changed (4 files, zero new flags/env vars)
server/src/server/context_prune.h: pure header-only helperprune_messages_to_fit(...)invoked only whenraw_tokens > max_ctx - min_reply(normal turns are 100% untouched):- Stage 1A (cache-stable): strips
reasoning_contentand<think>...</think>(including open-think...</think>intool_calls_replayedturns) strictly before a deterministic 32-message cut (floor((n - 4) / 32) * 32), keeping the recent 4..35 messages' thinking intact and keeping[0, cut)byte-identical across up to 16 consecutive turns so prefix caching immediately re-locks. - Stage 1B: if recent thinking alone still overflows, strips remaining historical assistant thinking.
- Stage 2A/2B/2C: if still over budget, middle-truncates oversized
tooloutputs (UTF-8 boundary safe) at the same deterministic 32-message cut while preservingsystemandusermessages verbatim. - Unprunable single-turn/user overflows still return the exact normal HTTP 400
ContextWindowExceededError.
- Stage 1A (cache-stable): strips
server/src/server/http_server.cpp: hooksprune_messages_to_fitright afterrender_and_tokenize_requestfor non-routed, non-multimodal, non-PFlash requests and logs one[server] context-prune ...line when triggered.server/test/unit/test_context_prune.cpp&server/CMakeLists.txt: standalone CPU unit test covering all stages, prefix invariance across consecutive turns, replayed<think>/...</think>, UTF-8 boundary safety, and untouched giant user prompts.
Verification
test_context_prune: PASS (-Wall -Wextra -Werror)ctest -R 'test_context_prune|ServerUnitFixture': 573/573 PASS (0 failed).github/ci/check_commit_messages.py: 1/1 OK