Skip to main content

aidaemon_core/
limits.rs

1use std::time::Duration;
2
3use serde::{Deserialize, Serialize};
4
5use crate::provider::Usage;
6
7/// Turn cap that applies even if `Limits::max_turns` is set higher. A run
8/// that needs more than this is a bug, not a task.
9pub const HARD_TURN_CAP: u32 = 1_000;
10
11/// Hard budgets for one run. Turns, tokens and tool calls are checked at the
12/// top of every turn; tool calls and wall-clock time are also checked before
13/// every call in a batch, and the model call and each tool are bounded by the
14/// remaining wall-clock budget. `max_turns` cannot be switched off: it is
15/// clamped to [`HARD_TURN_CAP`].
16#[derive(Debug, Clone, PartialEq)]
17pub struct Limits {
18    pub max_turns: u32,
19    /// Billable tokens for this run (cached input excluded).
20    pub max_tokens: Option<u64>,
21    pub max_tool_calls: Option<u32>,
22    /// Wall-clock budget for the whole run, summed across resumes.
23    pub timeout: Option<Duration>,
24    /// Per-call timeout for tools.
25    pub tool_timeout: Duration,
26    /// Tool output beyond this many characters is cut to head + tail.
27    pub max_tool_output_chars: usize,
28    /// How many times in a row `on_stop` hooks may send the model back with
29    /// no new successful tool call in between. Counting progress rather than
30    /// turns stops a hook and a refusing model from circling forever while
31    /// leaving long, productive runs alone.
32    pub max_idle_continuations: u32,
33    /// How long one hook call may take (see [`crate::Hook::timeout`]).
34    pub hook_timeout: Duration,
35}
36
37impl Default for Limits {
38    fn default() -> Self {
39        Self {
40            max_turns: 50,
41            max_tokens: None,
42            max_tool_calls: None,
43            timeout: None,
44            tool_timeout: Duration::from_secs(120),
45            max_tool_output_chars: 30_000,
46            max_idle_continuations: 8,
47            hook_timeout: Duration::from_secs(300),
48        }
49    }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum LimitKind {
55    Turns,
56    Tokens,
57    ToolCalls,
58    WallClock,
59}
60
61/// How far hooks have raised each limit for this run (see
62/// [`crate::Hook::on_limit`]), on top of the agent's [`Limits`].
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
64pub struct LimitGrants {
65    pub turns: u32,
66    pub tokens: u64,
67    pub tool_calls: u32,
68    pub wall_clock_ms: u64,
69}
70
71impl LimitGrants {
72    pub(crate) fn add(&mut self, limit: LimitKind, amount: u64) {
73        let small = u32::try_from(amount).unwrap_or(u32::MAX);
74        match limit {
75            LimitKind::Turns => self.turns = self.turns.saturating_add(small),
76            LimitKind::Tokens => self.tokens = self.tokens.saturating_add(amount),
77            LimitKind::ToolCalls => self.tool_calls = self.tool_calls.saturating_add(small),
78            LimitKind::WallClock => self.wall_clock_ms = self.wall_clock_ms.saturating_add(amount),
79        }
80    }
81}
82
83/// What a [`StopCondition`] can see.
84#[derive(Debug, Clone, Copy, PartialEq)]
85pub struct RunSnapshot {
86    pub turn: u32,
87    pub tool_calls: u32,
88    /// Usage of the current run.
89    pub usage: Usage,
90    pub elapsed: Duration,
91}
92
93/// A custom stop rule, checked with the built-in limits at the top of each
94/// turn. Return `Some(reason)` to end the run. Closures implement it.
95pub trait StopCondition: Send + Sync {
96    fn check(&self, snapshot: &RunSnapshot) -> Option<String>;
97}
98
99impl<F> StopCondition for F
100where
101    F: Fn(&RunSnapshot) -> Option<String> + Send + Sync,
102{
103    fn check(&self, snapshot: &RunSnapshot) -> Option<String> {
104        self(snapshot)
105    }
106}
107
108impl Limits {
109    /// These limits, raised by a run's grants.
110    pub(crate) fn with_grants(&self, grants: &LimitGrants) -> Limits {
111        Limits {
112            max_turns: self.max_turns.saturating_add(grants.turns),
113            max_tokens: self.max_tokens.map(|m| m.saturating_add(grants.tokens)),
114            max_tool_calls: self
115                .max_tool_calls
116                .map(|m| m.saturating_add(grants.tool_calls)),
117            timeout: self
118                .timeout
119                .map(|t| t.saturating_add(Duration::from_millis(grants.wall_clock_ms))),
120            ..self.clone()
121        }
122    }
123
124    pub(crate) fn exceeded(&self, snapshot: &RunSnapshot) -> Option<LimitKind> {
125        if snapshot.turn >= self.max_turns.min(HARD_TURN_CAP) {
126            return Some(LimitKind::Turns);
127        }
128        if let Some(max) = self.max_tokens
129            && snapshot.usage.billable_tokens() >= max
130        {
131            return Some(LimitKind::Tokens);
132        }
133        if let Some(max) = self.max_tool_calls
134            && snapshot.tool_calls >= max
135        {
136            return Some(LimitKind::ToolCalls);
137        }
138        if let Some(max) = self.timeout
139            && snapshot.elapsed >= max
140        {
141            return Some(LimitKind::WallClock);
142        }
143        None
144    }
145}