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    /// What the verification gate did (beyond Python; `crate::verify`), only when
48    /// `[verify] command` is set. Before `final`, which stays last.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub verification: Option<crate::verify::Verification>,
51    /// The turn's answer alone: its last assistant message, without the `[tool] ...`
52    /// lines, notices, or the text of earlier steps that `output` holds. Empty when the
53    /// turn ended without one (cancelled, out of steps). Beyond Python, and appended
54    /// last so readers of Python's fields are unaffected.
55    #[serde(rename = "final")]
56    pub final_answer: String,
57}
58
59/// The answer a finished turn left in `messages`: the last message, when it is the
60/// assistant's and asks for no tools. A turn that returns `Ok` always pushed its user
61/// message first, so an earlier turn's answer is never mistaken for this one's.
62pub fn final_answer(messages: &[Message]) -> &str {
63    match messages.last() {
64        Some(last) if last.role == Role::Assistant && last.tool_calls.is_empty() => &last.content,
65        _ => "",
66    }
67}
68
69/// A new ephemeral session id: 12 lowercase hex characters, like Python's `uuid4().hex[:12]`.
70pub fn new_session_id() -> String {
71    let mut hasher = RandomState::new().build_hasher();
72    hasher.write_u128(
73        std::time::SystemTime::now()
74            .duration_since(std::time::UNIX_EPOCH)
75            .map_or(0, |elapsed| elapsed.as_nanos()),
76    );
77    format!("{:012x}", hasher.finish() & 0xffff_ffff_ffff)
78}
79
80/// Compact token count: 512 -> `512`, 1234 -> `1.2k`, 32768 -> `33k`.
81pub fn human_tokens(count: u64) -> String {
82    if count < 1000 {
83        count.to_string()
84    } else if count < 10_000 {
85        format!("{:.1}k", count as f64 / 1000.0)
86    } else {
87        // Python's round() rounds half to even.
88        format!("{}k", (count as f64 / 1000.0).round_ties_even())
89    }
90}
91
92/// One line summarising a finished turn, matching the Python `format_turn_summary`.
93///
94/// `priced` says whether a price is known for the turn's model; without one the
95/// cost reads "n/a" rather than a misleading `$0.0000`.
96pub fn format_turn_summary(summary: &TurnSummary, priced: bool) -> String {
97    let cached = summary.cache_read_tokens + summary.cache_creation_tokens;
98    let mut tokens = format!(
99        "{} in / {} out",
100        human_tokens(summary.input_tokens),
101        human_tokens(summary.output_tokens)
102    );
103    if cached > 0 {
104        tokens.push_str(&format!(" ({} cached)", human_tokens(cached)));
105    }
106    let mut parts = vec![
107        plural(summary.steps, "step"),
108        plural(summary.tool_calls, "tool"),
109        tokens,
110        format_cost(summary.cost_usd, priced),
111        format!("{:.1}s", summary.duration_s),
112    ];
113    if summary.compactions > 0 {
114        parts.push(plural(summary.compactions, "compaction"));
115    }
116    if summary.continuations > 0 {
117        parts.push(plural(summary.continuations, "continuation"));
118    }
119    format!("— {}", parts.join(" · "))
120}
121
122fn plural(count: u64, noun: &str) -> String {
123    if count == 1 {
124        format!("{count} {noun}")
125    } else {
126        format!("{count} {noun}s")
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn token_counts_are_compacted_like_python() {
136        assert_eq!(human_tokens(512), "512");
137        assert_eq!(human_tokens(1234), "1.2k");
138        assert_eq!(human_tokens(32768), "33k");
139        assert_eq!(human_tokens(12500), "12k");
140        assert_eq!(human_tokens(1250), "1.2k");
141    }
142
143    #[test]
144    fn summaries_drop_empty_cache_and_counters() {
145        let summary = TurnSummary {
146            input_tokens: 4100,
147            output_tokens: 612,
148            steps: 1,
149            duration_s: 8.24,
150            ..TurnSummary::default()
151        };
152        assert_eq!(
153            format_turn_summary(&summary, false),
154            "— 1 step · 0 tools · 4.1k in / 612 out · cost n/a (unpriced model) · 8.2s"
155        );
156
157        let cached = TurnSummary {
158            cache_read_tokens: 1900,
159            steps: 3,
160            tool_calls: 1,
161            continuations: 2,
162            ..summary
163        };
164        assert_eq!(
165            format_turn_summary(&TurnSummary { cost_usd: 0.01234, ..cached }, true),
166            "— 3 steps · 1 tool · 4.1k in / 612 out (1.9k cached) · $0.0123 · 8.2s · 2 continuations"
167        );
168    }
169
170    #[test]
171    fn session_ids_are_twelve_hex_characters() {
172        let id = new_session_id();
173        assert_eq!(id.len(), 12);
174        assert!(id
175            .chars()
176            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
177    }
178}