Skip to main content

ag_agent/model/
session.rs

1//! Session execution settings and usage statistics shared by agent transports.
2
3use std::fmt;
4use std::str::FromStr;
5
6/// Preferred amount of detail in user-facing session responses.
7#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
8pub enum ResponseStyle {
9    /// Keep responses compact while retaining essential results and caveats.
10    Concise,
11    /// Balance brevity with enough context to understand and verify the result.
12    #[default]
13    Balanced,
14    /// Explain decisions, trade-offs, effects, and verification thoroughly.
15    Detailed,
16}
17
18impl ResponseStyle {
19    /// Stable selector ordering.
20    pub const ALL: [Self; 3] = [Self::Concise, Self::Balanced, Self::Detailed];
21
22    /// Stable persisted identifier for this response style.
23    pub const fn as_str(self) -> &'static str {
24        match self {
25            Self::Concise => "concise",
26            Self::Balanced => "balanced",
27            Self::Detailed => "detailed",
28        }
29    }
30
31    /// User-visible selector label for this response style.
32    pub const fn name(self) -> &'static str {
33        match self {
34            Self::Concise => "Concise",
35            Self::Balanced => "Balanced",
36            Self::Detailed => "Detailed",
37        }
38    }
39
40    /// User-visible explanation of this response style.
41    pub const fn description(self) -> &'static str {
42        match self {
43            Self::Concise => "Compact answers with essential results, caveats, and verification.",
44            Self::Balanced => "Enough context to understand and verify without exhaustive detail.",
45            Self::Detailed => "Thorough decisions, trade-offs, effects, and verification.",
46        }
47    }
48
49    /// Agent-facing guidance for this response style.
50    pub(crate) const fn prompt_instruction(self) -> &'static str {
51        match self {
52            Self::Concise => {
53                "Lead with the outcome. Keep the final answer compact, omit routine narration, and \
54                 retain essential caveats and verification."
55            }
56            Self::Balanced => {
57                "Lead with the outcome. Provide enough context to understand decisions and verify \
58                 the result without exhaustive detail."
59            }
60            Self::Detailed => {
61                "Lead with the outcome. Explain decisions, trade-offs, affected behavior, and \
62                 verification thoroughly without repetition."
63            }
64        }
65    }
66}
67
68impl fmt::Display for ResponseStyle {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        formatter.write_str(self.as_str())
71    }
72}
73
74impl FromStr for ResponseStyle {
75    type Err = String;
76
77    fn from_str(value: &str) -> Result<Self, Self::Err> {
78        match value {
79            "concise" => Ok(Self::Concise),
80            "balanced" => Ok(Self::Balanced),
81            "detailed" => Ok(Self::Detailed),
82            _ => Err(format!("Unknown response style: {value}")),
83        }
84    }
85}
86
87/// Response-speed preference applied to one agent session.
88#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
89pub enum SpeedMode {
90    /// Use the provider's standard routing and pricing.
91    #[default]
92    Normal,
93    /// Request the provider's higher-cost low-latency routing.
94    Fast,
95}
96
97impl SpeedMode {
98    /// Stable selector ordering.
99    pub const ALL: [Self; 2] = [Self::Normal, Self::Fast];
100
101    /// Stable persisted identifier for this speed mode.
102    pub const fn as_str(self) -> &'static str {
103        match self {
104            Self::Normal => "normal",
105            Self::Fast => "fast",
106        }
107    }
108
109    /// User-visible selector label for this speed mode.
110    pub const fn name(self) -> &'static str {
111        match self {
112            Self::Normal => "Normal",
113            Self::Fast => "Fast",
114        }
115    }
116
117    /// User-visible explanation of this speed mode.
118    pub const fn description(self) -> &'static str {
119        match self {
120            Self::Normal => "Standard response speed and provider pricing.",
121            Self::Fast => "Faster responses at a higher provider cost.",
122        }
123    }
124
125    /// Codex app-server service-tier value for this speed mode.
126    pub const fn codex_service_tier(self) -> &'static str {
127        match self {
128            Self::Normal => "default",
129            Self::Fast => "fast",
130        }
131    }
132
133    /// Whether Claude Code should enable its `fastMode` setting.
134    pub const fn claude_fast_mode(self) -> bool {
135        matches!(self, Self::Fast)
136    }
137}
138
139impl fmt::Display for SpeedMode {
140    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141        formatter.write_str(self.as_str())
142    }
143}
144
145impl FromStr for SpeedMode {
146    type Err = String;
147
148    fn from_str(value: &str) -> Result<Self, Self::Err> {
149        match value {
150            "normal" => Ok(Self::Normal),
151            "fast" => Ok(Self::Fast),
152            _ => Err(format!("Unknown speed mode: {value}")),
153        }
154    }
155}
156
157/// Known availability of a session worktree diff.
158#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
159pub enum SessionDiffState {
160    /// Diff availability could not be determined, so callers should preserve
161    /// access to diagnostic diff output.
162    #[default]
163    Unknown,
164    /// The latest successful diff refresh returned no content.
165    Empty,
166    /// The latest successful diff refresh returned content.
167    Present,
168}
169
170/// Token and diff usage statistics associated with one agent session or
171/// isolated prompt.
172#[derive(Clone, PartialEq, Eq, Debug, Default)]
173pub struct SessionStats {
174    /// Added diff lines currently attributed to the session worktree.
175    pub added_lines: u64,
176    /// Deleted diff lines currently attributed to the session worktree.
177    pub deleted_lines: u64,
178    /// Availability derived from the latest worktree diff refresh.
179    pub diff_state: SessionDiffState,
180    /// Input/prompt tokens consumed by this session.
181    pub input_tokens: u64,
182    /// Output/response tokens produced by this session.
183    pub output_tokens: u64,
184}
185
186impl SessionStats {
187    /// Returns whether the UI should advertise access to the session diff.
188    ///
189    /// Unknown state retains the shortcut so a subsequent diff attempt can
190    /// surface the underlying Git diagnostic instead of hiding it.
191    pub fn should_show_diff(&self) -> bool {
192        self.diff_state != SessionDiffState::Empty
193    }
194
195    /// Counts added and deleted lines in one git patch while ignoring file
196    /// header markers such as `+++` and `---`.
197    pub fn line_change_counts(diff: &str) -> (u64, u64) {
198        diff.lines()
199            .fold((0_u64, 0_u64), |(added_lines, deleted_lines), line| {
200                if line.starts_with('+') && !line.starts_with("+++") {
201                    return (added_lines.saturating_add(1), deleted_lines);
202                }
203
204                if line.starts_with('-') && !line.starts_with("---") {
205                    return (added_lines, deleted_lines.saturating_add(1));
206                }
207
208                (added_lines, deleted_lines)
209            })
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn response_style_round_trips_persisted_values() {
219        // Arrange, Act, Assert
220        for response_style in ResponseStyle::ALL {
221            assert_eq!(
222                response_style.as_str().parse::<ResponseStyle>(),
223                Ok(response_style)
224            );
225            assert_eq!(response_style.to_string(), response_style.as_str());
226        }
227    }
228
229    #[test]
230    fn response_style_rejects_unknown_persisted_value() {
231        // Arrange, Act
232        let result = "verbose".parse::<ResponseStyle>();
233
234        // Assert
235        assert_eq!(result, Err("Unknown response style: verbose".to_string()));
236    }
237
238    #[test]
239    fn response_style_exposes_stable_labels_and_descriptions() {
240        // Arrange, Act
241        let values = ResponseStyle::ALL
242            .map(|response_style| (response_style.name(), response_style.description()));
243
244        // Assert
245        assert_eq!(
246            values,
247            [
248                (
249                    "Concise",
250                    "Compact answers with essential results, caveats, and verification."
251                ),
252                (
253                    "Balanced",
254                    "Enough context to understand and verify without exhaustive detail."
255                ),
256                (
257                    "Detailed",
258                    "Thorough decisions, trade-offs, effects, and verification."
259                ),
260            ]
261        );
262    }
263
264    #[test]
265    fn speed_mode_round_trips_persisted_values() {
266        // Arrange, Act, Assert
267        for speed_mode in SpeedMode::ALL {
268            assert_eq!(speed_mode.as_str().parse::<SpeedMode>(), Ok(speed_mode));
269            assert_eq!(speed_mode.to_string(), speed_mode.as_str());
270        }
271    }
272
273    #[test]
274    fn speed_mode_maps_provider_settings() {
275        // Arrange, Act, Assert
276        assert_eq!(SpeedMode::Normal.codex_service_tier(), "default");
277        assert!(!SpeedMode::Normal.claude_fast_mode());
278        assert_eq!(SpeedMode::Fast.codex_service_tier(), "fast");
279        assert!(SpeedMode::Fast.claude_fast_mode());
280    }
281
282    #[test]
283    fn speed_mode_rejects_unknown_persisted_value() {
284        // Arrange, Act
285        let result = "turbo".parse::<SpeedMode>();
286
287        // Assert
288        assert_eq!(result, Err("Unknown speed mode: turbo".to_string()));
289    }
290
291    #[test]
292    fn should_show_diff_hides_only_known_empty_diffs() {
293        // Arrange
294        let unknown = SessionStats::default();
295        let empty = SessionStats {
296            diff_state: SessionDiffState::Empty,
297            ..SessionStats::default()
298        };
299        let present = SessionStats {
300            diff_state: SessionDiffState::Present,
301            ..SessionStats::default()
302        };
303
304        // Act, Assert
305        assert!(unknown.should_show_diff());
306        assert!(!empty.should_show_diff());
307        assert!(present.should_show_diff());
308    }
309}