ironflow-core 5.0.0

Rust workflow engine with Claude Code native agent support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Identity and cost cap of an agent role.
//!
//! An agent role (see `ironflow_engine::config::AgentRole`) has a name and
//! may declare a [`RoleCostCap`]. The role's tasks carry an [`AgentRoleBinding`]
//! on their [`AgentConfig`](crate::provider::AgentConfig), which the engine
//! reads to charge every agent step of the role to one shared counter over a
//! calendar [`CostPeriod`] (UTC).
//!
//! # Examples
//!
//! ```
//! use chrono::{TimeZone, Utc};
//! use ironflow_core::agent_role::{AgentRoleBinding, CostPeriod, RoleCostCap};
//! use rust_decimal::Decimal;
//!
//! let binding = AgentRoleBinding::new("reviewer", Some(RoleCostCap::per_month(Decimal::TEN)));
//! assert_eq!(binding.period, CostPeriod::Month);
//!
//! let now = Utc.with_ymd_and_hms(2026, 7, 26, 15, 30, 0).unwrap();
//! assert_eq!(CostPeriod::Month.start(now), Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap());
//! ```

use chrono::{DateTime, Datelike, Days, Months, TimeZone, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumString, IntoStaticStr};

/// Longest name an agent role may have, in bytes.
///
/// # Examples
///
/// ```
/// use ironflow_core::agent_role::MAX_ROLE_NAME_LEN;
///
/// assert_eq!(MAX_ROLE_NAME_LEN, 128);
/// ```
pub const MAX_ROLE_NAME_LEN: usize = 128;

/// Whether `name` is a valid agent role name.
///
/// A name is not blank, has no leading or trailing whitespace, and has at
/// most [`MAX_ROLE_NAME_LEN`] bytes. The default name of a role, its type
/// name (`Reviewer`), is valid.
///
/// # Examples
///
/// ```
/// use ironflow_core::agent_role::is_valid_role_name;
///
/// assert!(is_valid_role_name("code-reviewer.v2"));
/// assert!(is_valid_role_name("Reviewer"));
/// assert!(!is_valid_role_name(" reviewer"));
/// assert!(!is_valid_role_name(""));
/// ```
pub fn is_valid_role_name(name: &str) -> bool {
    !name.trim().is_empty() && name.trim() == name && name.len() <= MAX_ROLE_NAME_LEN
}

/// Calendar period, in UTC, over which the cost of a role is counted.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use ironflow_core::agent_role::CostPeriod;
///
/// assert_eq!(CostPeriod::from_str("day").ok(), Some(CostPeriod::Day));
/// assert_eq!(CostPeriod::Month.to_string(), "month");
/// ```
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    Display,
    EnumString,
    IntoStaticStr,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CostPeriod {
    /// From midnight UTC to the next midnight UTC.
    Day,
    /// From the 1st of the month at 00:00 UTC to the 1st of the next month.
    Month,
}

impl CostPeriod {
    /// Stable name of the period, as stored and sent over the API.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::CostPeriod;
    ///
    /// assert_eq!(CostPeriod::Day.as_str(), "day");
    /// ```
    pub fn as_str(self) -> &'static str {
        self.into()
    }

    /// Start of the period containing `now`.
    ///
    /// # Examples
    ///
    /// ```
    /// use chrono::{TimeZone, Utc};
    /// use ironflow_core::agent_role::CostPeriod;
    ///
    /// let now = Utc.with_ymd_and_hms(2026, 7, 26, 15, 30, 0).unwrap();
    /// assert_eq!(CostPeriod::Day.start(now), Utc.with_ymd_and_hms(2026, 7, 26, 0, 0, 0).unwrap());
    /// ```
    ///
    /// # Panics
    ///
    /// Never panics for a valid [`DateTime<Utc>`]: midnight of an existing day
    /// is always unambiguous in UTC.
    pub fn start(self, now: DateTime<Utc>) -> DateTime<Utc> {
        let day = match self {
            Self::Day => now.day(),
            Self::Month => 1,
        };
        Utc.with_ymd_and_hms(now.year(), now.month(), day, 0, 0, 0)
            .single()
            .expect("midnight UTC of an existing day is always unambiguous")
    }

    /// Start of the period following the one containing `now`: when the
    /// counter resets.
    ///
    /// # Examples
    ///
    /// ```
    /// use chrono::{TimeZone, Utc};
    /// use ironflow_core::agent_role::CostPeriod;
    ///
    /// let now = Utc.with_ymd_and_hms(2026, 12, 26, 15, 30, 0).unwrap();
    /// assert_eq!(
    ///     CostPeriod::Month.next_start(now),
    ///     Utc.with_ymd_and_hms(2027, 1, 1, 0, 0, 0).unwrap()
    /// );
    /// ```
    ///
    /// # Panics
    ///
    /// Panics only past the last date chrono represents (year 262143).
    pub fn next_start(self, now: DateTime<Utc>) -> DateTime<Utc> {
        let start = self.start(now);
        match self {
            Self::Day => start
                .checked_add_days(Days::new(1))
                .expect("the day after a representable date is representable"),
            Self::Month => start
                .checked_add_months(Months::new(1))
                .expect("the month after a representable date is representable"),
        }
    }
}

/// Cost cap of an agent role over a calendar period.
///
/// # Examples
///
/// ```
/// use ironflow_core::agent_role::{CostPeriod, RoleCostCap};
/// use rust_decimal::Decimal;
///
/// let cap = RoleCostCap::per_month(Decimal::new(50, 0));
/// assert_eq!(cap.limit_usd(), Decimal::new(50, 0));
/// assert_eq!(cap.period(), CostPeriod::Month);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RoleCostCap {
    limit_usd: Decimal,
    period: CostPeriod,
}

impl RoleCostCap {
    /// Cap of `limit_usd` per calendar day (UTC). Zero disables the role.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::{CostPeriod, RoleCostCap};
    /// use rust_decimal::Decimal;
    ///
    /// assert_eq!(RoleCostCap::per_day(Decimal::ONE).period(), CostPeriod::Day);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `limit_usd` is negative.
    pub fn per_day(limit_usd: Decimal) -> Self {
        Self::new(limit_usd, CostPeriod::Day)
    }

    /// Cap of `limit_usd` per calendar month (UTC). Zero disables the role.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::{CostPeriod, RoleCostCap};
    /// use rust_decimal::Decimal;
    ///
    /// assert_eq!(RoleCostCap::per_month(Decimal::ONE).period(), CostPeriod::Month);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `limit_usd` is negative.
    pub fn per_month(limit_usd: Decimal) -> Self {
        Self::new(limit_usd, CostPeriod::Month)
    }

    fn new(limit_usd: Decimal, period: CostPeriod) -> Self {
        assert!(
            limit_usd >= Decimal::ZERO,
            "the cost cap of an agent role must not be negative, got {limit_usd}"
        );
        Self { limit_usd, period }
    }

    /// The cap, in USD.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::RoleCostCap;
    /// use rust_decimal::Decimal;
    ///
    /// assert_eq!(RoleCostCap::per_day(Decimal::TWO).limit_usd(), Decimal::TWO);
    /// ```
    pub fn limit_usd(&self) -> Decimal {
        self.limit_usd
    }

    /// The period the cap applies to.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::{CostPeriod, RoleCostCap};
    /// use rust_decimal::Decimal;
    ///
    /// assert_eq!(RoleCostCap::per_day(Decimal::TWO).period(), CostPeriod::Day);
    /// ```
    pub fn period(&self) -> CostPeriod {
        self.period
    }
}

/// Agent role an invocation is charged to, attached to its
/// [`AgentConfig`](crate::provider::AgentConfig).
///
/// # Examples
///
/// ```
/// use ironflow_core::agent_role::{AgentRoleBinding, CostPeriod};
///
/// let binding = AgentRoleBinding::new("reviewer", None);
/// assert_eq!(binding.name, "reviewer");
/// assert_eq!(binding.cost_cap_usd, None);
/// assert_eq!(binding.period, CostPeriod::Month);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentRoleBinding {
    /// Name of the role, valid per [`is_valid_role_name`].
    pub name: String,
    /// Cap declared in code, `None` when the role only counts its cost.
    pub cost_cap_usd: Option<Decimal>,
    /// Period of the counter; [`CostPeriod::Month`] when no cap is declared.
    pub period: CostPeriod,
}

impl AgentRoleBinding {
    /// Bind to the role `name`, with its optional code cap.
    ///
    /// A role without a code cap still counts its cost over a month, so an
    /// operator cap set later applies to what was already spent.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::agent_role::{AgentRoleBinding, CostPeriod, RoleCostCap};
    /// use rust_decimal::Decimal;
    ///
    /// let binding = AgentRoleBinding::new("triage", Some(RoleCostCap::per_day(Decimal::ONE)));
    /// assert_eq!(binding.cost_cap_usd, Some(Decimal::ONE));
    /// assert_eq!(binding.period, CostPeriod::Day);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `name` is not valid per [`is_valid_role_name`].
    pub fn new(name: &str, cap: Option<RoleCostCap>) -> Self {
        assert!(
            is_valid_role_name(name),
            "invalid agent role name {name:?}: not blank, no leading or trailing whitespace, at most {MAX_ROLE_NAME_LEN} bytes"
        );
        Self {
            name: name.to_string(),
            cost_cap_usd: cap.map(|c| c.limit_usd()),
            period: cap.map(|c| c.period()).unwrap_or(CostPeriod::Month),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use serde_json::to_string;

    use super::*;

    fn at(y: i32, m: u32, d: u32, h: u32, min: u32, s: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(y, m, d, h, min, s).unwrap()
    }

    #[test]
    fn role_names_are_validated() {
        assert!(is_valid_role_name("code-reviewer.v2"));
        assert!(is_valid_role_name("a"));
        assert!(is_valid_role_name("Reviewer"));
        assert!(is_valid_role_name("revi\u{e9}wer"));
        assert!(is_valid_role_name("code reviewer"));
        assert!(is_valid_role_name("a/b"));
        assert!(is_valid_role_name(&"a".repeat(MAX_ROLE_NAME_LEN)));
        assert!(!is_valid_role_name(&"a".repeat(MAX_ROLE_NAME_LEN + 1)));
        assert!(!is_valid_role_name(""));
        assert!(!is_valid_role_name("   "));
        assert!(!is_valid_role_name(" reviewer"));
        assert!(!is_valid_role_name("reviewer\n"));
    }

    #[test]
    fn day_period_starts_at_midnight_utc() {
        let day = CostPeriod::Day;
        assert_eq!(
            day.start(at(2026, 7, 26, 15, 30, 0)),
            at(2026, 7, 26, 0, 0, 0)
        );
        assert_eq!(
            day.start(at(2026, 7, 26, 0, 0, 0)),
            at(2026, 7, 26, 0, 0, 0)
        );
        assert_eq!(
            day.next_start(at(2026, 12, 31, 23, 59, 59)),
            at(2027, 1, 1, 0, 0, 0)
        );
        assert_eq!(
            day.next_start(at(2028, 2, 28, 12, 0, 0)),
            at(2028, 2, 29, 0, 0, 0)
        );
    }

    #[test]
    fn month_period_starts_on_the_first_at_midnight_utc() {
        let month = CostPeriod::Month;
        assert_eq!(
            month.start(at(2026, 2, 17, 23, 59, 59)),
            at(2026, 2, 1, 0, 0, 0)
        );
        assert_eq!(
            month.start(at(2026, 3, 1, 0, 0, 0)),
            at(2026, 3, 1, 0, 0, 0)
        );
        assert_eq!(
            month.next_start(at(2026, 12, 15, 0, 0, 0)),
            at(2027, 1, 1, 0, 0, 0)
        );
        assert_eq!(
            month.next_start(at(2028, 2, 29, 10, 0, 0)),
            at(2028, 3, 1, 0, 0, 0)
        );
        assert_eq!(
            month.next_start(at(2026, 1, 31, 10, 0, 0)),
            at(2026, 2, 1, 0, 0, 0)
        );
    }

    #[test]
    fn period_names_round_trip() {
        for period in [CostPeriod::Day, CostPeriod::Month] {
            assert_eq!(CostPeriod::from_str(period.as_str()).ok(), Some(period));
            assert_eq!(period.to_string(), period.as_str());
        }
        assert!(CostPeriod::from_str("week").is_err());
        assert_eq!(to_string(&CostPeriod::Day).unwrap(), "\"day\"");
    }

    #[test]
    fn zero_cap_is_allowed() {
        assert_eq!(
            RoleCostCap::per_day(Decimal::ZERO).limit_usd(),
            Decimal::ZERO
        );
    }

    #[test]
    #[should_panic(expected = "must not be negative")]
    fn negative_cap_panics() {
        let _ = RoleCostCap::per_month(Decimal::NEGATIVE_ONE);
    }

    #[test]
    #[should_panic(expected = "invalid agent role name")]
    fn binding_with_an_invalid_name_panics() {
        let _ = AgentRoleBinding::new(" reviewer", None);
    }

    #[test]
    fn binding_without_cap_counts_over_a_month() {
        let binding = AgentRoleBinding::new("reviewer", None);
        assert_eq!(binding.cost_cap_usd, None);
        assert_eq!(binding.period, CostPeriod::Month);
    }

    #[test]
    fn binding_takes_the_cap_and_period() {
        let binding = AgentRoleBinding::new("reviewer", Some(RoleCostCap::per_day(Decimal::TEN)));
        assert_eq!(binding.cost_cap_usd, Some(Decimal::TEN));
        assert_eq!(binding.period, CostPeriod::Day);
    }
}