Skip to content

Commit 1584642

Browse files
committed
feat: calculate context usage from history and add a final pre-request safety check after trimming.
1 parent 6eb56b1 commit 1584642

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/agent/runloop/unified/context_manager.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff 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

src/agent/runloop/unified/turn/guards.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)