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 {
288 self.session_limits
289 .get(LimitKind::Output)
290 .unwrap_or_else(|| {
291 self.sized_output(
292 self.configured_output(),
293 self.active_context_window(),
294 &self.output_setting(),
295 )
296 })
297 }
298
299 pub(crate) fn sized_output(&self, cap: u32, window: u64, setting: &str) -> u32 {
302 let default = !setting.starts_with("[providers.")
303 && matches!(
304 self.limits.max_output_tokens,
305 0 | crate::memory::sizing::DEFAULT_OUTPUT_CAP
306 );
307 if self.limits.context_sizing && default {
308 crate::memory::sizing::sized_output_cap(cap, window)
309 } else {
310 cap
311 }
312 }
313
314 pub fn output_setting(&self) -> String {
317 match self.configured_output_setting() {
318 Some(setting) if self.session_limits.get(LimitKind::Output).is_none() => setting,
319 _ => self.session_limits.output_setting(),
320 }
321 }
322
323 pub fn limit(&self, kind: LimitKind) -> u32 {
325 match kind {
326 LimitKind::Steps => self.max_steps(),
327 LimitKind::AgentSteps => self.agent_max_steps(),
328 LimitKind::Output => self.output_cap(),
329 }
330 }
331
332 pub fn configure_output(&mut self, config: &Config, provider: &str) {
335 self.max_tokens = config.max_output_tokens_for(provider);
336 self.session_limits.configured_output = output_setting(config, provider).1;
337 }
338
339 pub fn reload_limits(&mut self, config: &Config, provider: &str) {
342 self.limits = config.limits.clone();
343 self.agents = config.agents.clone();
344 self.configure_output(config, provider);
345 for kind in LimitKind::ALL {
346 if self.session_limits.get(kind) == Some(configured(kind, config, provider)) {
347 self.session_limits.set(kind, None);
348 }
349 }
350 }
351
352 pub(crate) fn raise_limit(
357 &self,
358 kind: LimitKind,
359 agent: Option<&str>,
360 sid: &str,
361 current: u32,
362 run_only: bool,
363 ) -> Option<u32> {
364 let prompt = self.session_limits.prompt.as_ref()?;
365 let ceiling = (kind == LimitKind::AgentSteps).then(|| self.max_steps());
367 let hit = LimitHit {
368 kind,
369 agent: agent.map(str::to_owned),
370 current,
371 offers: offers(current, ceiling),
372 run_only,
373 };
374 if hit.offers.is_empty() {
375 return None;
376 }
377 let raised = self
379 .gate
380 .queue
381 .ask(
382 crate::approval::Question {
383 agent: hit.agent.clone(),
384 subject: Some(kind.name().to_owned()),
385 ..crate::approval::Question::new(crate::approval::QuestionKind::Limit)
386 },
387 || prompt(&hit),
388 )
389 .flatten()
390 .filter(|value| hit.offers.contains(value))?;
391 if !run_only {
392 self.session_limits.set(kind, Some(raised));
393 }
394 let mut fields = vec![("limit", json!(kind.name()))];
395 if let Some(agent) = agent {
396 fields.push(("agent", json!(agent)));
397 }
398 fields.push(("from", json!(current)));
399 fields.push(("to", json!(raised)));
400 self.recorder.event(sid, "limit_raised", fields);
401 Some(raised)
402 }
403}
404
405#[cfg(test)]
406mod tests {
407 use super::*;
408 use crate::config::{load_config, ConfigPaths, Overrides};
409
410 fn config(name: &str, text: &str) -> Config {
411 let root =
412 std::env::temp_dir().join(format!("agent86-limits-{name}-{}", std::process::id()));
413 std::fs::create_dir_all(&root).unwrap();
414 std::fs::write(root.join("config.toml"), text).unwrap();
415 let paths = ConfigPaths {
416 user: None,
417 project: root.join("config.toml"),
418 project_trust: crate::config::ProjectTrust::Trusted,
419 };
420 let config = load_config(&paths, &Overrides::default()).unwrap();
421 let _ = std::fs::remove_dir_all(&root);
422 config
423 }
424
425 #[test]
426 fn offers_double_and_quadruple_under_the_ceiling() {
427 assert_eq!(offers(40, None), vec![80, 160]);
428 assert_eq!(offers(8192, None), vec![16384, 32768]);
429 assert_eq!(offers(8, Some(20)), vec![16, 20]);
430 assert_eq!(offers(8, Some(10)), vec![10]);
431 assert_eq!(offers(40, Some(40)), Vec::<u32>::new());
432 assert_eq!(offers(u32::MAX, None), Vec::<u32>::new());
433 }
434
435 #[test]
436 fn names_parse_back() {
437 for kind in LimitKind::ALL {
438 assert_eq!(LimitKind::parse(kind.name()), Some(kind));
439 }
440 assert_eq!(LimitKind::parse("max_steps"), None);
441 }
442
443 #[test]
444 fn the_output_cap_is_saved_where_it_takes_effect() {
445 let overrides = LimitOverrides {
446 steps: Some(80),
447 agent_steps: None,
448 output: Some(32000),
449 };
450 let written = |changes: Vec<Change>| -> Vec<(String, Option<i64>)> {
451 changes
452 .into_iter()
453 .map(|(path, value)| (path.join("."), value.and_then(|value| value.as_integer())))
454 .collect()
455 };
456 let plain = config("plain", "[model]\ndefault = \"openrouter:a\"\n");
457 assert_eq!(
458 written(save_changes(overrides, &plain, "openrouter")),
459 vec![
460 ("limits.max_steps".to_owned(), Some(80)),
461 ("limits.max_output_tokens".to_owned(), Some(32000)),
462 ]
463 );
464 let per_provider = config(
466 "provider",
467 "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 4096\n",
468 );
469 assert_eq!(
470 written(save_changes(overrides, &per_provider, "openrouter"))[1],
471 ("providers.openrouter.max_tokens".to_owned(), Some(32000))
472 );
473 assert_eq!(
474 setting(LimitKind::Output, &per_provider, "openrouter").1,
475 "[providers.openrouter] max_tokens"
476 );
477 }
478
479 #[test]
480 fn the_notice_names_the_setting_to_raise() {
481 let mut limits = SessionLimits::default();
482 assert_eq!(limits.output_setting(), "[limits] max_output_tokens");
483 limits.configured_output = "[providers.anthropic] max_tokens".into();
484 assert_eq!(limits.output_setting(), "[providers.anthropic] max_tokens");
485 limits.set(LimitKind::Output, Some(32000));
486 assert_eq!(
487 limits.output_setting(),
488 "the session's output limit (/limits output)"
489 );
490 }
491
492 #[test]
493 fn hits_say_what_was_reached() {
494 let hit = |kind, agent: Option<&str>, current| LimitHit {
495 kind,
496 agent: agent.map(str::to_owned),
497 current,
498 offers: Vec::new(),
499 run_only: false,
500 };
501 assert_eq!(
502 hit(LimitKind::Steps, None, 40).headline(),
503 "Step budget reached (40 steps)"
504 );
505 assert_eq!(
506 hit(LimitKind::AgentSteps, Some("reviewer"), 8).headline(),
507 "Sub-agent 'reviewer' reached its step budget (8 steps)"
508 );
509 assert_eq!(
510 hit(LimitKind::Output, Some("reviewer"), 8192).headline(),
511 "Sub-agent 'reviewer' reached the output limit (8192 tokens) before any text"
512 );
513 }
514}