use crate::agent::Harness;
use crate::config::Config;
use crate::config_writer::Change;
use serde_json::json;
use std::sync::{Mutex, PoisonError};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LimitKind {
Steps,
AgentSteps,
Output,
}
impl LimitKind {
pub const ALL: [Self; 3] = [Self::Steps, Self::AgentSteps, Self::Output];
pub fn name(self) -> &'static str {
match self {
Self::Steps => "steps",
Self::AgentSteps => "agent_steps",
Self::Output => "output",
}
}
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|kind| kind.name() == name)
}
pub fn unit(self) -> &'static str {
match self {
Self::Steps | Self::AgentSteps => "steps",
Self::Output => "tokens",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct LimitOverrides {
pub steps: Option<u32>,
pub agent_steps: Option<u32>,
pub output: Option<u32>,
}
impl LimitOverrides {
pub fn get(&self, kind: LimitKind) -> Option<u32> {
match kind {
LimitKind::Steps => self.steps,
LimitKind::AgentSteps => self.agent_steps,
LimitKind::Output => self.output,
}
}
fn slot(&mut self, kind: LimitKind) -> &mut Option<u32> {
match kind {
LimitKind::Steps => &mut self.steps,
LimitKind::AgentSteps => &mut self.agent_steps,
LimitKind::Output => &mut self.output,
}
}
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LimitHit {
pub kind: LimitKind,
pub agent: Option<String>,
pub current: u32,
pub offers: Vec<u32>,
pub run_only: bool,
}
impl LimitHit {
pub fn headline(&self) -> String {
let current = self.current;
match (self.kind, &self.agent) {
(LimitKind::Steps | LimitKind::AgentSteps, None) => {
format!("Step budget reached ({current} steps)")
}
(LimitKind::Steps | LimitKind::AgentSteps, Some(role)) => {
format!("Sub-agent '{role}' reached its step budget ({current} steps)")
}
(LimitKind::Output, None) => {
format!("The reply reached the output limit ({current} tokens) before any text")
}
(LimitKind::Output, Some(role)) => format!(
"Sub-agent '{role}' reached the output limit ({current} tokens) before any text"
),
}
}
pub fn question(&self) -> &'static str {
match (self.kind, self.run_only) {
(LimitKind::Steps | LimitKind::AgentSteps, false) => {
"Raise it for this session and go on?"
}
(LimitKind::Output, false) => "Raise it for this session and ask again?",
(LimitKind::Steps | LimitKind::AgentSteps, true) => "Raise it for this run and go on?",
(LimitKind::Output, true) => "Raise it for this run and ask again?",
}
}
}
pub type LimitPrompt = Box<dyn Fn(&LimitHit) -> Option<u32> + Send + Sync>;
#[derive(Default)]
pub struct SessionLimits {
overrides: Mutex<LimitOverrides>,
pub prompt: Option<LimitPrompt>,
configured_output: String,
}
impl SessionLimits {
pub fn overrides(&self) -> LimitOverrides {
*self
.overrides
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub fn get(&self, kind: LimitKind) -> Option<u32> {
self.overrides().get(kind)
}
pub fn set(&self, kind: LimitKind, value: Option<u32>) {
let mut overrides = self
.overrides
.lock()
.unwrap_or_else(PoisonError::into_inner);
*overrides.slot(kind) = value;
}
pub fn clear(&self) {
*self
.overrides
.lock()
.unwrap_or_else(PoisonError::into_inner) = LimitOverrides::default();
}
pub fn output_setting(&self) -> String {
if self.get(LimitKind::Output).is_some() {
"the session's output limit (/limits output)".to_owned()
} else if self.configured_output.is_empty() {
"[limits] max_output_tokens".to_owned()
} else {
self.configured_output.clone()
}
}
}
pub fn offers(current: u32, ceiling: Option<u32>) -> Vec<u32> {
let mut values: Vec<u32> = [current.saturating_mul(2), current.saturating_mul(4)]
.into_iter()
.map(|value| ceiling.map_or(value, |ceiling| value.min(ceiling)))
.filter(|&value| value > current)
.collect();
values.dedup();
values
}
pub fn output_setting(config: &Config, provider: &str) -> (Vec<String>, String) {
let per_provider = config
.providers
.get(provider)
.and_then(|section| section.max_tokens)
.is_some_and(|cap| cap > 0);
if per_provider {
(
vec!["providers".into(), provider.into(), "max_tokens".into()],
format!("[providers.{provider}] max_tokens"),
)
} else {
(
vec!["limits".into(), "max_output_tokens".into()],
"[limits] max_output_tokens".into(),
)
}
}
pub fn setting(kind: LimitKind, config: &Config, provider: &str) -> (Vec<String>, String) {
match kind {
LimitKind::Steps => (
vec!["limits".into(), "max_steps".into()],
"[limits] max_steps".into(),
),
LimitKind::AgentSteps => (
vec!["agents".into(), "max_steps".into()],
"[agents] max_steps".into(),
),
LimitKind::Output => output_setting(config, provider),
}
}
pub fn configured(kind: LimitKind, config: &Config, provider: &str) -> u32 {
match kind {
LimitKind::Steps => config.limits.max_steps,
LimitKind::AgentSteps => config.agents.max_steps,
LimitKind::Output => config.max_output_tokens_for(provider),
}
}
pub fn save_changes(overrides: LimitOverrides, config: &Config, provider: &str) -> Vec<Change> {
LimitKind::ALL
.into_iter()
.filter_map(|kind| {
let value = overrides.get(kind)?;
let value = toml_edit::Value::from(i64::from(value));
Some((setting(kind, config, provider).0, Some(value)))
})
.collect()
}
impl Harness {
pub fn max_steps(&self) -> u32 {
self.session_limits
.get(LimitKind::Steps)
.unwrap_or(self.limits.max_steps)
}
pub fn agent_max_steps(&self) -> u32 {
self.session_limits
.get(LimitKind::AgentSteps)
.unwrap_or(self.agents.max_steps)
.min(self.max_steps())
}
pub fn output_cap(&self) -> u32 {
self.session_limits
.get(LimitKind::Output)
.unwrap_or(self.configured_output())
}
pub fn output_setting(&self) -> String {
match self.configured_output_setting() {
Some(setting) if self.session_limits.get(LimitKind::Output).is_none() => setting,
_ => self.session_limits.output_setting(),
}
}
pub fn limit(&self, kind: LimitKind) -> u32 {
match kind {
LimitKind::Steps => self.max_steps(),
LimitKind::AgentSteps => self.agent_max_steps(),
LimitKind::Output => self.output_cap(),
}
}
pub fn configure_output(&mut self, config: &Config, provider: &str) {
self.max_tokens = config.max_output_tokens_for(provider);
self.session_limits.configured_output = output_setting(config, provider).1;
}
pub fn reload_limits(&mut self, config: &Config, provider: &str) {
self.limits = config.limits.clone();
self.agents = config.agents.clone();
self.configure_output(config, provider);
for kind in LimitKind::ALL {
if self.session_limits.get(kind) == Some(configured(kind, config, provider)) {
self.session_limits.set(kind, None);
}
}
}
pub(crate) fn raise_limit(
&self,
kind: LimitKind,
agent: Option<&str>,
sid: &str,
current: u32,
run_only: bool,
) -> Option<u32> {
let prompt = self.session_limits.prompt.as_ref()?;
let ceiling = (kind == LimitKind::AgentSteps).then(|| self.max_steps());
let hit = LimitHit {
kind,
agent: agent.map(str::to_owned),
current,
offers: offers(current, ceiling),
run_only,
};
if hit.offers.is_empty() {
return None;
}
let raised = self
.gate
.queue
.ask(
crate::approval::Question {
agent: hit.agent.clone(),
subject: Some(kind.name().to_owned()),
..crate::approval::Question::new(crate::approval::QuestionKind::Limit)
},
|| prompt(&hit),
)
.flatten()
.filter(|value| hit.offers.contains(value))?;
if !run_only {
self.session_limits.set(kind, Some(raised));
}
let mut fields = vec![("limit", json!(kind.name()))];
if let Some(agent) = agent {
fields.push(("agent", json!(agent)));
}
fields.push(("from", json!(current)));
fields.push(("to", json!(raised)));
self.recorder.event(sid, "limit_raised", fields);
Some(raised)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{load_config, ConfigPaths, Overrides};
fn config(name: &str, text: &str) -> Config {
let root =
std::env::temp_dir().join(format!("agent86-limits-{name}-{}", std::process::id()));
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("config.toml"), text).unwrap();
let paths = ConfigPaths {
user: None,
project: root.join("config.toml"),
project_trust: crate::config::ProjectTrust::Trusted,
};
let config = load_config(&paths, &Overrides::default()).unwrap();
let _ = std::fs::remove_dir_all(&root);
config
}
#[test]
fn offers_double_and_quadruple_under_the_ceiling() {
assert_eq!(offers(40, None), vec![80, 160]);
assert_eq!(offers(8192, None), vec![16384, 32768]);
assert_eq!(offers(8, Some(20)), vec![16, 20]);
assert_eq!(offers(8, Some(10)), vec![10]);
assert_eq!(offers(40, Some(40)), Vec::<u32>::new());
assert_eq!(offers(u32::MAX, None), Vec::<u32>::new());
}
#[test]
fn names_parse_back() {
for kind in LimitKind::ALL {
assert_eq!(LimitKind::parse(kind.name()), Some(kind));
}
assert_eq!(LimitKind::parse("max_steps"), None);
}
#[test]
fn the_output_cap_is_saved_where_it_takes_effect() {
let overrides = LimitOverrides {
steps: Some(80),
agent_steps: None,
output: Some(32000),
};
let written = |changes: Vec<Change>| -> Vec<(String, Option<i64>)> {
changes
.into_iter()
.map(|(path, value)| (path.join("."), value.and_then(|value| value.as_integer())))
.collect()
};
let plain = config("plain", "[model]\ndefault = \"openrouter:a\"\n");
assert_eq!(
written(save_changes(overrides, &plain, "openrouter")),
vec![
("limits.max_steps".to_owned(), Some(80)),
("limits.max_output_tokens".to_owned(), Some(32000)),
]
);
let per_provider = config(
"provider",
"[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 4096\n",
);
assert_eq!(
written(save_changes(overrides, &per_provider, "openrouter"))[1],
("providers.openrouter.max_tokens".to_owned(), Some(32000))
);
assert_eq!(
setting(LimitKind::Output, &per_provider, "openrouter").1,
"[providers.openrouter] max_tokens"
);
}
#[test]
fn the_notice_names_the_setting_to_raise() {
let mut limits = SessionLimits::default();
assert_eq!(limits.output_setting(), "[limits] max_output_tokens");
limits.configured_output = "[providers.anthropic] max_tokens".into();
assert_eq!(limits.output_setting(), "[providers.anthropic] max_tokens");
limits.set(LimitKind::Output, Some(32000));
assert_eq!(
limits.output_setting(),
"the session's output limit (/limits output)"
);
}
#[test]
fn hits_say_what_was_reached() {
let hit = |kind, agent: Option<&str>, current| LimitHit {
kind,
agent: agent.map(str::to_owned),
current,
offers: Vec::new(),
run_only: false,
};
assert_eq!(
hit(LimitKind::Steps, None, 40).headline(),
"Step budget reached (40 steps)"
);
assert_eq!(
hit(LimitKind::AgentSteps, Some("reviewer"), 8).headline(),
"Sub-agent 'reviewer' reached its step budget (8 steps)"
);
assert_eq!(
hit(LimitKind::Output, Some("reviewer"), 8192).headline(),
"Sub-agent 'reviewer' reached the output limit (8192 tokens) before any text"
);
}
}