File tree Expand file tree Collapse file tree 2 files changed +18
-1
lines changed
src/agent/runloop/unified Expand file tree Collapse file tree 2 files changed +18
-1
lines changed Original file line number Diff line number Diff line change @@ -366,7 +366,18 @@ impl ContextManager {
366366 }
367367
368368 let mut pruning_ledger = pruning_ledger;
369- let usage = self . token_budget . usage_ratio ( ) . await ;
369+
370+ // Use live calculation from history to ensure consistency with pre_request_check
371+ // stored token_budget might be lagging if history was just modified
372+ let estimated = self . estimate_request_tokens ( history) ;
373+ let max_tokens = self . trim_config . max_tokens ;
374+
375+ let usage = if max_tokens > 0 {
376+ estimated as f64 / max_tokens as f64
377+ } else {
378+ 0.0
379+ } ;
380+
370381 let mut outcome = ContextTrimOutcome :: default ( ) ;
371382
372383 // Alert/compact: semantic prune first, then enforce window
Original file line number Diff line number Diff line change @@ -118,6 +118,12 @@ pub(crate) async fn run_proactive_guards(
118118 }
119119 }
120120
121+ // Final safety check: ensure we didn't exit the loop (e.g. max checks) while still in a dangerous state
122+ let final_check = ctx. context_manager . pre_request_check ( ctx. working_history ) ;
123+ if matches ! ( final_check, PreRequestAction :: Block ) {
124+ anyhow:: bail!( "Context budget critical/overflow after trimming attempts. Conversation unsafe to proceed." ) ;
125+ }
126+
121127 Ok ( ( ) )
122128}
123129
You can’t perform that action at this time.
0 commit comments