1use crate::agent::Harness;
22use crate::config::Config;
23use crate::config_writer::Change;
24use serde_json::json;
25use std::sync::{Mutex, PoisonError};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum LimitKind {
30 Steps,
31 AgentSteps,
32 Output,
33}
34
35impl LimitKind {
36 pub const ALL: [Self; 3] = [Self::Steps, Self::AgentSteps, Self::Output];
37
38 pub fn name(self) -> &'static str {
40 match self {
41 Self::Steps => "steps",
42 Self::AgentSteps => "agent_steps",
43 Self::Output => "output",
44 }
45 }
46
47 pub fn parse(name: &str) -> Option<Self> {
48 Self::ALL.into_iter().find(|kind| kind.name() == name)
49 }
50
51 pub fn unit(self) -> &'static str {
53 match self {
54 Self::Steps | Self::AgentSteps => "steps",
55 Self::Output => "tokens",
56 }
57 }
58}
59
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
62pub struct LimitOverrides {
63 pub steps: Option<u32>,
64 pub agent_steps: Option<u32>,
65 pub output: Option<u32>,
66}
67
68impl LimitOverrides {
69 pub fn get(&self, kind: LimitKind) -> Option<u32> {
70 match kind {
71 LimitKind::Steps => self.steps,
72 LimitKind::AgentSteps => self.agent_steps,
73 LimitKind::Output => self.output,
74 }
75 }
76
77 fn slot(&mut self, kind: LimitKind) -> &mut Option<u32> {
78 match kind {
79 LimitKind::Steps => &mut self.steps,
80 LimitKind::AgentSteps => &mut self.agent_steps,
81 LimitKind::Output => &mut self.output,
82 }
83 }
84
85 pub fn is_empty(&self) -> bool {
86 *self == Self::default()
87 }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct LimitHit {
93 pub kind: LimitKind,
94 pub agent: Option<String>,
96 pub current: u32,
98 pub offers: Vec<u32>,
100 pub run_only: bool,
104}
105
106impl LimitHit {
107 pub fn headline(&self) -> String {
109 let current = self.current;
110 match (self.kind, &self.agent) {
111 (LimitKind::Steps | LimitKind::AgentSteps, None) => {
112 format!("Step budget reached ({current} steps)")
113 }
114 (LimitKind::Steps | LimitKind::AgentSteps, Some(role)) => {
115 format!("Sub-agent '{role}' reached its step budget ({current} steps)")
116 }
117 (LimitKind::Output, None) => {
118 format!("The reply reached the output limit ({current} tokens) before any text")
119 }
120 (LimitKind::Output, Some(role)) => format!(
121 "Sub-agent '{role}' reached the output limit ({current} tokens) before any text"
122 ),
123 }
124 }
125
126 pub fn question(&self) -> &'static str {
128 match (self.kind, self.run_only) {
129 (LimitKind::Steps | LimitKind::AgentSteps, false) => {
130 "Raise it for this session and go on?"
131 }
132 (LimitKind::Output, false) => "Raise it for this session and ask again?",
133 (LimitKind::Steps | LimitKind::AgentSteps, true) => "Raise it for this run and go on?",
134 (LimitKind::Output, true) => "Raise it for this run and ask again?",
135 }
136 }
137}
138
139pub type LimitPrompt = Box<dyn Fn(&LimitHit) -> Option<u32> + Send + Sync>;
141
142#[derive(Default)]
145pub struct SessionLimits {
146 overrides: Mutex<LimitOverrides>,
147 pub prompt: Option<LimitPrompt>,
148 configured_output: String,
150}
151
152impl SessionLimits {
153 pub fn overrides(&self) -> LimitOverrides {
154 *self
155 .overrides
156 .lock()
157 .unwrap_or_else(PoisonError::into_inner)
158 }
159
160 pub fn get(&self, kind: LimitKind) -> Option<u32> {
161 self.overrides().get(kind)
162 }
163
164 pub fn set(&self, kind: LimitKind, value: Option<u32>) {
165 let mut overrides = self
166 .overrides
167 .lock()
168 .unwrap_or_else(PoisonError::into_inner);
169 *overrides.slot(kind) = value;
170 }
171
172 pub fn clear(&self) {
173 *self
174 .overrides
175 .lock()
176 .unwrap_or_else(PoisonError::into_inner) = LimitOverrides::default();
177 }
178
179 pub fn output_setting(&self) -> String {
182 if self.get(LimitKind::Output).is_some() {
183 "the session's output limit (/limits output)".to_owned()
184 } else if self.configured_output.is_empty() {
185 "[limits] max_output_tokens".to_owned()
186 } else {
187 self.configured_output.clone()
188 }
189 }
190}
191
192pub fn offers(current: u32, ceiling: Option<u32>) -> Vec<u32> {
195 let mut values: Vec<u32> = [current.saturating_mul(2), current.saturating_mul(4)]
196 .into_iter()
197 .map(|value| ceiling.map_or(value, |ceiling| value.min(ceiling)))
198 .filter(|&value| value > current)
199 .collect();
200 values.dedup();
201 values
202}
203
204pub fn output_setting(config: &Config, provider: &str) -> (Vec<String>, String) {
207 let per_provider = config
208 .providers
209 .get(provider)
210 .and_then(|section| section.max_tokens)
211 .is_some_and(|cap| cap > 0);
212 if per_provider {
213 (
214 vec!["providers".into(), provider.into(), "max_tokens".into()],
215 format!("[providers.{provider}] max_tokens"),
216 )
217 } else {
218 (
219 vec!["limits".into(), "max_output_tokens".into()],
220 "[limits] max_output_tokens".into(),
221 )
222 }
223}
224
225pub fn setting(kind: LimitKind, config: &Config, provider: &str) -> (Vec<String>, String) {
227 match kind {
228 LimitKind::Steps => (
229 vec!["limits".into(), "max_steps".into()],
230 "[limits] max_steps".into(),
231 ),
232 LimitKind::AgentSteps => (
233 vec!["agents".into(), "max_steps".into()],
234 "[agents] max_steps".into(),
235 ),
236 LimitKind::Output => output_setting(config, provider),
237 }
238}
239
240pub fn configured(kind: LimitKind, config: &Config, provider: &str) -> u32 {
242 match kind {
243 LimitKind::Steps => config.limits.max_steps,
244 LimitKind::AgentSteps => config.agents.max_steps,
245 LimitKind::Output => config.max_output_tokens_for(provider),
246 }
247}
248
249pub fn save_changes(overrides: LimitOverrides, config: &Config, provider: &str) -> Vec<Change> {
254 LimitKind::ALL
255 .into_iter()
256 .filter_map(|kind| {
257 let value = overrides.get(kind)?;
258 let value = toml_edit::Value::from(i64::from(value));
259 Some((setting(kind, config, provider).0, Some(value)))
260 })
261 .collect()
262}
263
264impl Harness {
265 pub fn max_steps(&self) -> u32 {
267 self.session_limits
268 .get(LimitKind::Steps)
269 .unwrap_or(self.limits.max_steps)
270 }
271
272 pub fn agent_max_steps(&self) -> u32 {
274 self.session_limits
275 .get(LimitKind::AgentSteps)
276 .unwrap_or(self.agents.max_steps)
277 .min(self.max_steps())
278 }
279
280 pub fn output_cap(&self) -> u32 {
282 self.session_limits
283 .get(LimitKind::Output)
284 .unwrap_or(self.configured_output())
285 }
286
287 pub fn output_setting(&self) -> String {
290 match self.configured_output_setting() {
291 Some(setting) if self.session_limits.get(LimitKind::Output).is_none() => setting,
292 _ => self.session_limits.output_setting(),
293 }
294 }
295
296 pub fn limit(&self, kind: LimitKind) -> u32 {
298 match kind {
299 LimitKind::Steps => self.max_steps(),
300 LimitKind::AgentSteps => self.agent_max_steps(),
301 LimitKind::Output => self.output_cap(),
302 }
303 }
304
305 pub fn configure_output(&mut self, config: &Config, provider: &str) {
308 self.max_tokens = config.max_output_tokens_for(provider);
309 self.session_limits.configured_output = output_setting(config, provider).1;
310 }
311
312 pub fn reload_limits(&mut self, config: &Config, provider: &str) {
315 self.limits = config.limits.clone();
316 self.agents = config.agents.clone();
317 self.configure_output(config, provider);
318 for kind in LimitKind::ALL {
319 if self.session_limits.get(kind) == Some(configured(kind, config, provider)) {
320 self.session_limits.set(kind, None);
321 }
322 }
323 }
324
325 pub(crate) fn raise_limit(
330 &self,
331 kind: LimitKind,
332 agent: Option<&str>,
333 sid: &str,
334 current: u32,
335 run_only: bool,
336 ) -> Option<u32> {
337 let prompt = self.session_limits.prompt.as_ref()?;
338 let ceiling = (kind == LimitKind::AgentSteps).then(|| self.max_steps());
340 let hit = LimitHit {
341 kind,
342 agent: agent.map(str::to_owned),
343 current,
344 offers: offers(current, ceiling),
345 run_only,
346 };
347 if hit.offers.is_empty() {
348 return None;
349 }
350 let raised = self
352 .gate
353 .queue
354 .ask(
355 crate::approval::Question {
356 agent: hit.agent.clone(),
357 subject: Some(kind.name().to_owned()),
358 ..crate::approval::Question::new(crate::approval::QuestionKind::Limit)
359 },
360 || prompt(&hit),
361 )
362 .flatten()
363 .filter(|value| hit.offers.contains(value))?;
364 if !run_only {
365 self.session_limits.set(kind, Some(raised));
366 }
367 let mut fields = vec![("limit", json!(kind.name()))];
368 if let Some(agent) = agent {
369 fields.push(("agent", json!(agent)));
370 }
371 fields.push(("from", json!(current)));
372 fields.push(("to", json!(raised)));
373 self.recorder.event(sid, "limit_raised", fields);
374 Some(raised)
375 }
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381 use crate::config::{load_config, ConfigPaths, Overrides};
382
383 fn config(name: &str, text: &str) -> Config {
384 let root =
385 std::env::temp_dir().join(format!("agent86-limits-{name}-{}", std::process::id()));
386 std::fs::create_dir_all(&root).unwrap();
387 std::fs::write(root.join("config.toml"), text).unwrap();
388 let paths = ConfigPaths {
389 user: None,
390 project: root.join("config.toml"),
391 project_trust: crate::config::ProjectTrust::Trusted,
392 };
393 let config = load_config(&paths, &Overrides::default()).unwrap();
394 let _ = std::fs::remove_dir_all(&root);
395 config
396 }
397
398 #[test]
399 fn offers_double_and_quadruple_under_the_ceiling() {
400 assert_eq!(offers(40, None), vec![80, 160]);
401 assert_eq!(offers(8192, None), vec![16384, 32768]);
402 assert_eq!(offers(8, Some(20)), vec![16, 20]);
403 assert_eq!(offers(8, Some(10)), vec![10]);
404 assert_eq!(offers(40, Some(40)), Vec::<u32>::new());
405 assert_eq!(offers(u32::MAX, None), Vec::<u32>::new());
406 }
407
408 #[test]
409 fn names_parse_back() {
410 for kind in LimitKind::ALL {
411 assert_eq!(LimitKind::parse(kind.name()), Some(kind));
412 }
413 assert_eq!(LimitKind::parse("max_steps"), None);
414 }
415
416 #[test]
417 fn the_output_cap_is_saved_where_it_takes_effect() {
418 let overrides = LimitOverrides {
419 steps: Some(80),
420 agent_steps: None,
421 output: Some(32000),
422 };
423 let written = |changes: Vec<Change>| -> Vec<(String, Option<i64>)> {
424 changes
425 .into_iter()
426 .map(|(path, value)| (path.join("."), value.and_then(|value| value.as_integer())))
427 .collect()
428 };
429 let plain = config("plain", "[model]\ndefault = \"openrouter:a\"\n");
430 assert_eq!(
431 written(save_changes(overrides, &plain, "openrouter")),
432 vec![
433 ("limits.max_steps".to_owned(), Some(80)),
434 ("limits.max_output_tokens".to_owned(), Some(32000)),
435 ]
436 );
437 let per_provider = config(
439 "provider",
440 "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 4096\n",
441 );
442 assert_eq!(
443 written(save_changes(overrides, &per_provider, "openrouter"))[1],
444 ("providers.openrouter.max_tokens".to_owned(), Some(32000))
445 );
446 assert_eq!(
447 setting(LimitKind::Output, &per_provider, "openrouter").1,
448 "[providers.openrouter] max_tokens"
449 );
450 }
451
452 #[test]
453 fn the_notice_names_the_setting_to_raise() {
454 let mut limits = SessionLimits::default();
455 assert_eq!(limits.output_setting(), "[limits] max_output_tokens");
456 limits.configured_output = "[providers.anthropic] max_tokens".into();
457 assert_eq!(limits.output_setting(), "[providers.anthropic] max_tokens");
458 limits.set(LimitKind::Output, Some(32000));
459 assert_eq!(
460 limits.output_setting(),
461 "the session's output limit (/limits output)"
462 );
463 }
464
465 #[test]
466 fn hits_say_what_was_reached() {
467 let hit = |kind, agent: Option<&str>, current| LimitHit {
468 kind,
469 agent: agent.map(str::to_owned),
470 current,
471 offers: Vec::new(),
472 run_only: false,
473 };
474 assert_eq!(
475 hit(LimitKind::Steps, None, 40).headline(),
476 "Step budget reached (40 steps)"
477 );
478 assert_eq!(
479 hit(LimitKind::AgentSteps, Some("reviewer"), 8).headline(),
480 "Sub-agent 'reviewer' reached its step budget (8 steps)"
481 );
482 assert_eq!(
483 hit(LimitKind::Output, Some("reviewer"), 8192).headline(),
484 "Sub-agent 'reviewer' reached the output limit (8192 tokens) before any text"
485 );
486 }
487}