Skip to main content

agent86_core/
limits.rs

1//! Turn limits changed while agent86 runs: a deliberate addition, since Python
2//! reads `[limits] max_steps`, `[limits] max_output_tokens`, the provider's
3//! `max_tokens`, and `[agents] max_steps` only from config.
4//!
5//! Three limits can be overridden for the rest of the process, by `/limits`, by
6//! `run`'s `--max-steps`, `--max-output-tokens`, and `--max-agent-steps`, or by
7//! answering the interface's offer when a turn reaches one:
8//!
9//! - `steps`: the turn's step budget (`[limits] max_steps`)
10//! - `agent_steps`: each sub-agent's step budget (`[agents] max_steps`), never
11//!   above `steps`, as Python's `CircuitBreaker` clamps it
12//! - `output`: the output cap of every model call, the main loop's and the
13//!   sub-agents'. It replaces whichever setting Python's `max_output_tokens_for`
14//!   would pick (the provider's `max_tokens`, else `[limits] max_output_tokens`),
15//!   so a raised cap always takes effect.
16//!
17//! An override outlives `/model`, `/clear`, and `/resume`. The offer is a hook,
18//! like the approval prompt: the interface installs it, and without it (`run`, the
19//! plain loop) a limit reached ends the turn or the sub-agent as before.
20
21use crate::agent::Harness;
22use crate::config::Config;
23use crate::config_writer::Change;
24use serde_json::json;
25use std::sync::{Mutex, PoisonError};
26
27/// One limit `/limits` can change.
28#[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    /// The name `/limits` takes.
39    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    /// What the limit counts.
52    pub fn unit(self) -> &'static str {
53        match self {
54            Self::Steps | Self::AgentSteps => "steps",
55            Self::Output => "tokens",
56        }
57    }
58}
59
60/// The overridden limits; `None` leaves a limit to the config.
61#[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/// A limit a running turn reached, put to the user.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct LimitHit {
93    pub kind: LimitKind,
94    /// The sub-agent's role, or `None` for the main loop.
95    pub agent: Option<String>,
96    /// The limit that was reached.
97    pub current: u32,
98    /// The values offered, ascending.
99    pub offers: Vec<u32>,
100    /// Beyond Python's settings: the raise lasts for this run of a specialist
101    /// sub-agent only, not the session, since it is that specialty's own budget or
102    /// model.
103    pub run_only: bool,
104}
105
106impl LimitHit {
107    /// What happened, in one line.
108    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    /// What accepting does.
127    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
139/// Asks whether to raise a limit that was reached: the new value, or `None` to stop.
140pub type LimitPrompt = Box<dyn Fn(&LimitHit) -> Option<u32> + Send + Sync>;
141
142/// The overrides, behind a lock so a turn holding the harness can raise one, and
143/// the hook that offers to.
144#[derive(Default)]
145pub struct SessionLimits {
146    overrides: Mutex<LimitOverrides>,
147    pub prompt: Option<LimitPrompt>,
148    /// The `[table] key` the configured output cap comes from, for messages.
149    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    /// What to raise for a larger output cap: the session's override when there is
180    /// one, else the setting the configured cap comes from.
181    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
192/// What to offer for a limit at `current`: double and quadruple it, kept at or
193/// under `ceiling` and above `current`.
194pub 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
204/// The setting the output cap comes from in `config`, as Python's
205/// `max_output_tokens_for` chooses it, for the provider section `provider`.
206pub 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
225/// The config key path and its `[table] key` label for `kind`.
226pub 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
240/// What `config` sets `kind` to for the provider section `provider`.
241pub 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
249/// The config changes that keep `overrides`: each one written to the setting it
250/// replaces, so the saved value is the one that takes effect. The output cap goes
251/// to the provider's `max_tokens` when that section sets one, else to
252/// `[limits] max_output_tokens`.
253pub 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    /// The turn's step budget.
266    pub fn max_steps(&self) -> u32 {
267        self.session_limits
268            .get(LimitKind::Steps)
269            .unwrap_or(self.limits.max_steps)
270    }
271
272    /// A sub-agent's step budget, never above the turn's.
273    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    /// The output cap sent with every model call.
281    ///
282    /// Beyond Python, with `[limits] context_sizing` on, the built-in default cap
283    /// is held to a share of the active window
284    /// (`crate::memory::sizing::sized_output_cap`); a cap the user set (a
285    /// provider's `max_tokens`, `[limits] max_output_tokens` changed, or a
286    /// session override) is taken as given.
287    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    /// `cap`, which comes from `setting`, for a model with `window`: held to its
300    /// share when sizing is on and the cap is the built-in default.
301    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    /// What to raise for a larger output cap, for messages: the session's override,
315    /// else the setting the active model's cap comes from.
316    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    /// The effective value of `kind`.
324    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    /// Take the configured output cap for the provider section `provider`, as
333    /// Python's `max_output_tokens_for`: at start and on every model switch.
334    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    /// Take the limits from a freshly loaded `config` for the provider section
340    /// `provider`, dropping the overrides it now agrees with (after a save).
341    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    /// Offer to raise `kind`, reached at `current`, and keep the new value for the
353    /// session, or with `run_only` hand it back for the caller's run alone (a
354    /// specialist sub-agent's own budget or model). `None` when there is no hook,
355    /// nothing to offer, or the user stops.
356    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        // A sub-agent's budget stays under the turn's.
366        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        // One question at a time, and none once the turn was cancelled.
378        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        // The provider's own cap wins over `[limits]`, so that is the one to change.
465        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}