Compaction is the recovery path for a chat near its context window, but
its summary request was larger than the turn that overflowed: the whole
history plus the tool definitions. Its only fallback, a retry without
tools, also missed context-window errors that arrive inside an HTTP 200
stream (OpenAI Responses API, Bedrock Mantle). In the incident behind
this PR, one MCP tool result of about 1 MB moved a 1M-token chat from
67% to 92% of its window in one step. After that, every turn and every
`/compact` failed with "Your input exceeds the context window of this
model."
This PR does not try to predict whether the summary request fits. Each
time the model rejects it for its size, the next request is thinner:
1. The full request: tool definitions and the whole history.
2. The same history without tool definitions (as before).
3. Tool results longer than 32 KiB cut to 32 KiB, keeping their head and
tail.
4. Tool results longer than 4 KiB cut to 4 KiB.
A step that would cut nothing is skipped. Only locally executed text and
error tool results are cut. User messages, attachments,
provider-executed results, and media stay whole. The cuts apply only to
the summary request, not to the stored history.
Other changes:
- **In-stream rejections match.** Fantasy stream errors without a status
code and Responses `error` and `response.failed` events now count as
size rejections. A Responses error code other than
`context_length_exceeded` never matches, so a rate limit stays
retryable. Anthropic's "input length and `max_tokens` exceed context
limit" also matches.
- **A conversation that still does not fit** fails as a non-retryable
config error that tells the user how to recover.
- **Each rejected summary request is logged at Warn** with its tool
count, tool result cap, and the bytes it cut.
Not in this PR: counting tool results that arrive after the measured
step in the compaction trigger, estimating the summary request before
sending it, and a tighter per-result cap for large-window models.
Earlier revisions of this branch did these and were dropped for the
simpler path above.
## Testing
- `go test ./coderd/x/chatd/...` (20 packages), `golangci-lint` on
`chatd` and `chatloop`, and the pre-commit hook pass.
- The real OpenAI Responses client runs against `httptest` for each
in-stream error shape and must retry without tools.
- Each of these breaks a test: removing the cut steps, sending a cut
that cuts nothing, turning error results into text, cutting
provider-executed results, and dropping the in-stream match.
> Xum opened this PR on behalf of @ibetitsmike.