Commit 28c9603
committed
fix(agent): use ground-truth prompt_tokens in the compaction trigger
The auto-compaction trigger sized the context with a bytes/4 heuristic
(`estimate_context_tokens`). That under-counts the code/JSON/non-English payloads
this agent generates, so a context that has really blown past the model's window
can read as "under threshold" and the next request overflows — an unrecoverable
failure once the provider rejects it.
The provider already returns the exact input size in `usage.prompt_tokens`, but it
was only emitted as telemetry and discarded. Track the most recent value per turn
and feed it into the trigger via `effective_context_tokens(estimate, last)` =
`max(estimate, last_prompt_tokens)`. At the end-of-turn compaction check,
`last_prompt_tokens` covers nearly the whole current context (only the just-
produced final assistant message is newer), so the max corrects the heuristic's
under-count and compaction fires when it should.
Self-correcting by construction: after any compaction the next request re-counts a
smaller context (overflow recovery `continue`s the loop; the threshold path ends
the turn), and `last_prompt_tokens` resets to `None` per inbound — so a stale large
value can't cause a spurious re-trigger.
Out of scope (follow-up): an OpenAI context-window override for
`provider.context_window_tokens()` so the window-aware threshold tightens there too.
Tests: `effective_context_tokens_prefers_ground_truth` (fallback, ground-truth
wins, estimate wins, zero never lowers).1 parent e99e8b3 commit 28c9603
1 file changed
Lines changed: 39 additions & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
151 | 151 | | |
152 | 152 | | |
153 | 153 | | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
154 | 162 | | |
155 | 163 | | |
156 | 164 | | |
| |||
2212 | 2220 | | |
2213 | 2221 | | |
2214 | 2222 | | |
| 2223 | + | |
| 2224 | + | |
| 2225 | + | |
| 2226 | + | |
| 2227 | + | |
2215 | 2228 | | |
2216 | 2229 | | |
2217 | 2230 | | |
| |||
2620 | 2633 | | |
2621 | 2634 | | |
2622 | 2635 | | |
| 2636 | + | |
| 2637 | + | |
| 2638 | + | |
| 2639 | + | |
2623 | 2640 | | |
2624 | 2641 | | |
2625 | 2642 | | |
| |||
2984 | 3001 | | |
2985 | 3002 | | |
2986 | 3003 | | |
2987 | | - | |
| 3004 | + | |
| 3005 | + | |
| 3006 | + | |
| 3007 | + | |
| 3008 | + | |
| 3009 | + | |
| 3010 | + | |
| 3011 | + | |
| 3012 | + | |
2988 | 3013 | | |
2989 | 3014 | | |
2990 | 3015 | | |
| |||
4056 | 4081 | | |
4057 | 4082 | | |
4058 | 4083 | | |
| 4084 | + | |
| 4085 | + | |
| 4086 | + | |
| 4087 | + | |
| 4088 | + | |
| 4089 | + | |
| 4090 | + | |
| 4091 | + | |
| 4092 | + | |
| 4093 | + | |
| 4094 | + | |
| 4095 | + | |
| 4096 | + | |
4059 | 4097 | | |
4060 | 4098 | | |
4061 | 4099 | | |
| |||
0 commit comments