Anthropic: preserve visible output when thinking consumes a tiny remaining budget
Problem
For Anthropic /v1/messages requests on reasoning models, ds4 clamps max_tokens to the remaining context room. When only a small budget remains (for example 180 tokens), the model can spend the whole budget inside <think> and return no visible text. Claude CLI automatic compaction then reports an empty summary instead of recovering.
The current Anthropic overflow error also does not use the wording Anthropic clients recognise for a truncated-history retry.
Proposed behavior
Add --anthropic-thinking-min-budget N with default 1024; 0 disables it.
On the first decode pass only, when all of these hold:
- endpoint is Anthropic
- reasoning mode is active
- real decode budget is
<= N - no recovery completion or DSML recovery is active
- the stream is untouched
append the model syntax's think-close suffix tokens to the live KV state, update thinking and Anthropic stream state, then decode visible text. Derive the suffix from the model syntax's thinking and non-thinking generation prompts; do not hand-write model-specific token ids.
Also return Anthropic overflow text exactly as:
prompt is too long: N tokens > M maximum
OpenAI-compatible endpoints must remain byte-identical.
Safety constraints
- Do not re-render, re-tokenise, re-parse, or cold-prefill the prompt.
- Use the decoder's real position, not rendered prompt length.
- Append pre-resolved suffix ids through the existing batched decode path under the model lock; do not call the session evaluator directly.
- Run only once and never after tool/recovery re-entry or after any stream output.
- Re-derive thinking and stream state after the suffix.
- If suffix evaluation fails partway, invalidate the session and clear live slot state before returning the existing error.
- A syntax without a pure close suffix is a no-op.
- Do not expose hidden reasoning as visible text.
Acceptance
- Unit tests cover threshold values
180,1024,1025, disabled0, reasoning off, recovery paths, already-streamed output, partial suffix failure, and unchanged OpenAI output. - Qwen's derived suffix detokenises to exactly
\n</think>\n\n. - A near-limit Anthropic request with
max_tokens=180returns a non-empty text block and no thinking block. - Repeating a long prompt preserves KV reuse; continuation after a tail-closed answer does not cold-prefill.
- A normal high-budget reasoning request still emits thinking normally.
./ds4_test --serverpasses.
This change is intentionally limited to the server.
Source: antirez/ds4