Skip to main content

agent86_core/
turn.rs

1//! The record of one turn: the `run --json` document, the per-turn summary,
2//! and the summary line printed on stderr. The loop itself is in `agent`.
3
4use crate::pricing::format_cost;
5use crate::types::{Message, Role, Usage};
6use serde::{Deserialize, Serialize};
7use std::collections::hash_map::RandomState;
8use std::hash::{BuildHasher, Hasher};
9
10/// What one user turn cost and did, matching the Python `TurnSummary` fields and order.
11#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
12#[serde(default)]
13pub struct TurnSummary {
14    pub input_tokens: u64,
15    pub output_tokens: u64,
16    pub cache_read_tokens: u64,
17    pub cache_creation_tokens: u64,
18    #[serde(serialize_with = "crate::pyjson::python_float")]
19    pub cost_usd: f64,
20    pub steps: u64,
21    pub tool_calls: u64,
22    #[serde(serialize_with = "crate::pyjson::python_float")]
23    pub duration_s: f64,
24    pub compactions: u64,
25    pub continuations: u64,
26}
27
28impl TurnSummary {
29    /// Fold one model call's usage in.
30    pub fn add_usage(&mut self, usage: &Usage) {
31        self.input_tokens += usage.input_tokens;
32        self.output_tokens += usage.output_tokens;
33        self.cost_usd += usage.cost_usd;
34        self.cache_read_tokens += usage.cache_read_tokens;
35        self.cache_creation_tokens += usage.cache_creation_tokens;
36    }
37}
38
39/// The `run --json` document. Field names and order are the scripting contract.
40#[derive(Debug, Clone, PartialEq, Serialize)]
41pub struct RunOutput {
42    pub session_id: String,
43    pub output: String,
44    pub steps: u64,
45    pub usage: Usage,
46    pub turn: Option<TurnSummary>,
47    /// The turn's answer alone: its last assistant message, without the `[tool] ...`
48    /// lines, notices, or the text of earlier steps that `output` holds. Empty when the
49    /// turn ended without one (cancelled, out of steps). Beyond Python, and appended
50    /// last so readers of Python's fields are unaffected.
51    #[serde(rename = "final")]
52    pub final_answer: String,
53}
54
55/// The answer a finished turn left in `messages`: the last message, when it is the
56/// assistant's and asks for no tools. A turn that returns `Ok` always pushed its user
57/// message first, so an earlier turn's answer is never mistaken for this one's.
58pub fn final_answer(messages: &[Message]) -> &str {
59    match messages.last() {
60        Some(last) if last.role == Role::Assistant && last.tool_calls.is_empty() => &last.content,
61        _ => "",
62    }
63}
64
65/// A new ephemeral session id: 12 lowercase hex characters, like Python's `uuid4().hex[:12]`.
66pub fn new_session_id() -> String {
67    let mut hasher = RandomState::new().build_hasher();
68    hasher.write_u128(
69        std::time::SystemTime::now()
70            .duration_since(std::time::UNIX_EPOCH)
71            .map_or(0, |elapsed| elapsed.as_nanos()),
72    );
73    format!("{:012x}", hasher.finish() & 0xffff_ffff_ffff)
74}
75
76/// Compact token count: 512 -> `512`, 1234 -> `1.2k`, 32768 -> `33k`.
77pub fn human_tokens(count: u64) -> String {
78    if count < 1000 {
79        count.to_string()
80    } else if count < 10_000 {
81        format!("{:.1}k", count as f64 / 1000.0)
82    } else {
83        // Python's round() rounds half to even.
84        format!("{}k", (count as f64 / 1000.0).round_ties_even())
85    }
86}
87
88/// One line summarising a finished turn, matching the Python `format_turn_summary`.
89///
90/// `priced` says whether a price is known for the turn's model; without one the
91/// cost reads "n/a" rather than a misleading `$0.0000`.
92pub fn format_turn_summary(summary: &TurnSummary, priced: bool) -> String {
93    let cached = summary.cache_read_tokens + summary.cache_creation_tokens;
94    let mut tokens = format!(
95        "{} in / {} out",
96        human_tokens(summary.input_tokens),
97        human_tokens(summary.output_tokens)
98    );
99    if cached > 0 {
100        tokens.push_str(&format!(" ({} cached)", human_tokens(cached)));
101    }
102    let mut parts = vec![
103        plural(summary.steps, "step"),
104        plural(summary.tool_calls, "tool"),
105        tokens,
106        format_cost(summary.cost_usd, priced),
107        format!("{:.1}s", summary.duration_s),
108    ];
109    if summary.compactions > 0 {
110        parts.push(plural(summary.compactions, "compaction"));
111    }
112    if summary.continuations > 0 {
113        parts.push(plural(summary.continuations, "continuation"));
114    }
115    format!("— {}", parts.join(" · "))
116}
117
118fn plural(count: u64, noun: &str) -> String {
119    if count == 1 {
120        format!("{count} {noun}")
121    } else {
122        format!("{count} {noun}s")
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn token_counts_are_compacted_like_python() {
132        assert_eq!(human_tokens(512), "512");
133        assert_eq!(human_tokens(1234), "1.2k");
134        assert_eq!(human_tokens(32768), "33k");
135        assert_eq!(human_tokens(12500), "12k");
136        assert_eq!(human_tokens(1250), "1.2k");
137    }
138
139    #[test]
140    fn summaries_drop_empty_cache_and_counters() {
141        let summary = TurnSummary {
142            input_tokens: 4100,
143            output_tokens: 612,
144            steps: 1,
145            duration_s: 8.24,
146            ..TurnSummary::default()
147        };
148        assert_eq!(
149            format_turn_summary(&summary, false),
150            "— 1 step · 0 tools · 4.1k in / 612 out · cost n/a (unpriced model) · 8.2s"
151        );
152
153        let cached = TurnSummary {
154            cache_read_tokens: 1900,
155            steps: 3,
156            tool_calls: 1,
157            continuations: 2,
158            ..summary
159        };
160        assert_eq!(
161            format_turn_summary(&TurnSummary { cost_usd: 0.01234, ..cached }, true),
162            "— 3 steps · 1 tool · 4.1k in / 612 out (1.9k cached) · $0.0123 · 8.2s · 2 continuations"
163        );
164    }
165
166    #[test]
167    fn session_ids_are_twelve_hex_characters() {
168        let id = new_session_id();
169        assert_eq!(id.len(), 12);
170        assert!(id
171            .chars()
172            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
173    }
174}