use crate::memory::working::{conversation_budget, count_tokens, MIN_CONVERSATION_TOKENS};
use crate::types::{Message, Role};
use std::collections::HashMap;
use std::sync::Mutex;
pub const RESULT_SHARE: u64 = 3;
pub const MIN_RESULT_CHARS: usize = 8_000;
pub const AGE_START_SHARE: u64 = 2;
pub const RECENT_SHARE: u64 = 3;
pub const STUB_THRESHOLD_CHARS: usize = 1_200;
pub const STUB_HEAD_CHARS: usize = 400;
pub const OUTPUT_SHARE: u64 = 4;
pub const DEFAULT_OUTPUT_CAP: u32 = 8_192;
pub const RESERVE_SHARE: u64 = 16;
pub const MAX_RATIO: f64 = 2.0;
pub fn sized_output_cap(cap: u32, window: u64) -> u32 {
if window <= crate::provider::capabilities::DEFAULT_CONTEXT_WINDOW {
return cap;
}
let share = u32::try_from(window / OUTPUT_SHARE).unwrap_or(u32::MAX);
cap.min(share)
}
pub fn sized_reserve(reserve: u64, window: u64) -> u64 {
if window == 0 {
return reserve;
}
reserve.min(window / RESERVE_SHARE)
}
pub fn result_cap(budget: u64, ceiling: usize) -> usize {
let share = usize::try_from(budget.saturating_mul(4) / RESULT_SHARE).unwrap_or(usize::MAX);
share.max(MIN_RESULT_CHARS).min(ceiling)
}
pub fn middle_note(left_out: usize) -> String {
format!(
"\n[... {left_out} characters left out of the middle of this result to fit the context \
window; search_files, or a narrower command (grep, sed -n, head, tail), shows the \
part you need ...]\n"
)
}
pub fn shorten_middle(text: &str, max_chars: usize) -> String {
let count = text.chars().count();
if count <= max_chars {
return text.to_owned();
}
let head = max_chars * 2 / 5;
let tail = max_chars - head;
let start: String = text.chars().take(head).collect();
let end: String = text.chars().skip(count - tail).collect();
format!("{start}{}{end}", middle_note(count - head - tail))
}
pub fn stub(content: &str) -> String {
let count = content.chars().count();
let head: String = content.chars().take(STUB_HEAD_CHARS).collect();
format!(
"{head}\n[older result shortened from {count} characters to save context; \
call the tool again if you need the rest]"
)
}
#[derive(Debug, Clone, PartialEq)]
pub struct Aged {
pub messages: Vec<Message>,
pub aged: usize,
}
pub fn aged_view(messages: &[Message], budget: u64) -> Aged {
let unchanged = || Aged {
messages: messages.to_vec(),
aged: 0,
};
if count_tokens(messages) <= budget / AGE_START_SHARE {
return unchanged();
}
let latest = messages
.iter()
.rposition(|message| message.role == Role::Assistant)
.map_or(0, |index| index + 1);
let recent = budget / RECENT_SHARE;
let mut seen = 0;
let mut out = messages.to_vec();
let mut aged = 0;
for index in (0..messages.len()).rev() {
let message = &messages[index];
if message.role != Role::Tool {
continue;
}
seen += count_tokens(std::slice::from_ref(message));
if index >= latest || seen <= recent {
continue;
}
if message.content.chars().count() > STUB_THRESHOLD_CHARS {
out[index].content = stub(&message.content);
aged += 1;
}
}
if aged == 0 {
return unchanged();
}
Aged {
messages: out,
aged,
}
}
#[derive(Debug, Default)]
pub struct Calibration {
ratios: Mutex<HashMap<String, f64>>,
}
impl Calibration {
pub fn observe(&self, model: &str, estimated: u64, reported: u64) {
if estimated == 0 || reported == 0 {
return;
}
let sample = (reported as f64 / estimated as f64).clamp(1.0, MAX_RATIO);
if let Ok(mut ratios) = self.ratios.lock() {
let ratio = ratios.entry(model.to_owned()).or_insert(sample);
*ratio = (*ratio + sample) / 2.0;
}
}
pub fn ratio(&self, model: &str) -> f64 {
self.ratios
.lock()
.ok()
.and_then(|ratios| ratios.get(model).copied())
.unwrap_or(1.0)
}
}
pub fn calibrated_budget(
window: u64,
overhead_tokens: u64,
reserve_tokens: u64,
output_tokens: u64,
hard_cap: u64,
ratio: f64,
) -> u64 {
if ratio <= 1.0 {
return conversation_budget(
window,
overhead_tokens,
reserve_tokens,
output_tokens,
hard_cap,
);
}
let reserve = (reserve_tokens + output_tokens).min(window / 2);
let sendable = (window.saturating_sub(reserve) as f64 / ratio) as u64;
let budget = sendable
.saturating_sub(overhead_tokens)
.max(MIN_CONVERSATION_TOKENS);
if hard_cap > 0 {
budget.min(hard_cap)
} else {
budget
}
}
#[cfg(test)]
mod tests {
use super::*;
fn message(role: Role, content: &str) -> Message {
Message {
role,
content: content.to_owned(),
tool_calls: Vec::new(),
tool_call_id: None,
name: None,
}
}
#[test]
fn the_result_cap_follows_the_budget_between_its_floor_and_ceiling() {
assert_eq!(result_cap(16_500, 100_000), 22_000);
assert_eq!(result_cap(1_024, 100_000), MIN_RESULT_CHARS);
assert_eq!(result_cap(115_000, 100_000), 100_000);
assert_eq!(result_cap(1_024, 5_000), 5_000);
}
#[test]
fn the_sized_default_is_the_configs_default() {
assert_eq!(
crate::config::builtin_config().limits.max_output_tokens,
DEFAULT_OUTPUT_CAP
);
}
#[test]
fn the_response_keeps_a_share_of_a_small_window_only() {
assert_eq!(sized_output_cap(8_192, 20_480), 5_120);
assert_eq!(sized_reserve(4_096, 20_480), 1_280);
assert_eq!(sized_output_cap(8_192, 32_768), 8_192);
assert_eq!(sized_reserve(4_096, 32_768), 2_048);
assert_eq!(sized_output_cap(8_192, 200_000), 8_192);
assert_eq!(sized_reserve(4_096, 200_000), 4_096);
assert_eq!(sized_output_cap(8_192, 8_192), 8_192);
assert_eq!(sized_output_cap(8_192, 4_096), 8_192);
assert_eq!(sized_output_cap(8_192, 0), 8_192);
assert_eq!(sized_output_cap(8_192, 12_288), 3_072);
assert_eq!(sized_reserve(4_096, 0), 4_096);
}
#[test]
fn shortening_keeps_the_start_and_more_of_the_end() {
let text = format!(
"{}{}{}",
"a".repeat(100),
"m".repeat(1_000),
"z".repeat(100)
);
let short = shorten_middle(&text, 100);
assert!(short.starts_with(&"a".repeat(40)));
assert!(short.ends_with(&"z".repeat(60)));
assert!(short.contains("[... 1100 characters left out of the middle"));
assert!(!short.contains("mmm"));
assert_eq!(shorten_middle("short", 100), "short");
}
#[test]
fn old_large_results_age_once_the_budget_is_half_spent() {
let big = "x".repeat(4_000); let messages = vec![
message(Role::User, "goal"),
message(Role::Assistant, ""),
message(Role::Tool, &big),
message(Role::Tool, "small"),
message(Role::Assistant, ""),
message(Role::Tool, &big),
message(Role::Assistant, ""),
message(Role::Tool, &big),
];
let aged = aged_view(&messages, 5_000);
assert_eq!(aged.aged, 2);
assert!(aged.messages[2]
.content
.contains("older result shortened from 4000"));
assert_eq!(aged.messages[3].content, "small");
assert!(aged.messages[5].content.starts_with(&"x".repeat(400)));
assert_eq!(aged.messages[7].content, big);
assert_eq!(aged.messages.len(), messages.len());
assert_eq!(aged_view(&messages, 6_000).aged, 1);
assert_eq!(aged_view(&messages, 7_000).aged, 0);
}
#[test]
fn the_latest_steps_results_are_never_aged() {
let big = "x".repeat(8_000);
let messages = vec![
message(Role::User, "goal"),
message(Role::Assistant, ""),
message(Role::Tool, &big),
message(Role::Tool, &big),
];
assert_eq!(aged_view(&messages, 1_500).aged, 0);
}
#[test]
fn calibration_only_ever_shrinks_the_budget() {
let calibration = Calibration::default();
assert_eq!(calibration.ratio("m"), 1.0);
calibration.observe("m", 1_000, 1_400);
assert!((calibration.ratio("m") - 1.4).abs() < 1e-9);
calibration.observe("m", 1_000, 1_000);
assert!((calibration.ratio("m") - 1.2).abs() < 1e-9);
calibration.observe("other", 10_000, 200);
assert_eq!(calibration.ratio("other"), 1.0);
calibration.observe("wild", 100, 10_000);
assert_eq!(calibration.ratio("wild"), MAX_RATIO);
}
#[test]
fn calibration_counts_the_overhead_at_the_ratio_too() {
assert_eq!(
calibrated_budget(32_768, 3_000, 4_096, 8_192, 0, 2.0),
7_240
);
assert_eq!(
conversation_budget(32_768, 3_000, 4_096, 8_192, 0) / 2,
8_740
);
assert_eq!(
calibrated_budget(32_768, 3_000, 4_096, 8_192, 0, 1.0),
conversation_budget(32_768, 3_000, 4_096, 8_192, 0)
);
assert_eq!(
calibrated_budget(20_480, 1_000, 4_096, 8_192, 0, 2.0),
4_120
);
assert_eq!(
calibrated_budget(8_192, 6_000, 4_096, 8_192, 0, 2.0),
MIN_CONVERSATION_TOKENS
);
assert_eq!(
calibrated_budget(32_768, 3_000, 4_096, 8_192, 5_000, 2.0),
5_000
);
}
}