Skip to main content

agent_commander/
codex_rollout.rs

1//! Codex rollouts (hive-mind#2888, #3570).
2//!
3//! Codex writes each thread to
4//! `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<timestamp>-<thread id>.jsonl`.
5//! `codex exec resume <id>` reads only that directory, so a run in a fresh
6//! container or `CODEX_HOME` cannot resume a thread whose rollout is missing.
7//!
8//! `codex exec --json` does not always report a usage limit on stdout or
9//! stderr. The rollout keeps two more sources: `event_msg` `token_count` with
10//! `rate_limits.{primary,secondary}` (`used_percent`, `window_minutes`,
11//! `resets_at` epoch seconds), and `event_msg` `error` with
12//! `codex_error_info` `usage_limit_exceeded` (older Codex versions). Only the
13//! last turn is read, so a limit an earlier turn waited out is not reported.
14
15use regex::Regex;
16use serde_json::Value;
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::sync::LazyLock;
20
21use crate::context_usage::extract_context_usage;
22use crate::file_tail::{default_home_dir, read_file_tail};
23use crate::result_metadata::ResultMetadata;
24use crate::usage_limit::{format_epoch_reset_time_utc, is_usage_limit_text};
25use crate::usage_windows::codex_rate_limit_windows;
26
27/// Directory under `CODEX_HOME` that holds the rollouts
28pub const CODEX_SESSIONS_DIRNAME: &str = "sessions";
29
30/// Bytes read from the end of a rollout
31pub const ROLLOUT_TAIL_BYTES: u64 = 1024 * 1024;
32
33/// `limit_source` of a limit found in a rollout
34pub const CODEX_ROLLOUT_LIMIT_SOURCE: &str = "codex-rollout";
35
36// `YYYY/MM/DD` plus slack; the walk never goes deeper.
37const MAX_ROLLOUT_SEARCH_DEPTH: usize = 5;
38const TURN_START_TYPES: [&str; 2] = ["task_started", "turn_started"];
39
40// Only ids of this shape are matched against file names.
41static THREAD_ID_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
42    Regex::new(r"^[0-9a-zA-Z][0-9a-zA-Z_-]{7,127}$").expect("valid thread id regex")
43});
44
45/// Where to look for Codex rollouts
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
47pub struct CodexRolloutOptions {
48    /// `CODEX_HOME`; defaults to the `CODEX_HOME` environment variable, then
49    /// `~/.codex`
50    pub codex_home: Option<PathBuf>,
51    /// Home directory; defaults to `HOME` (`USERPROFILE` on Windows)
52    pub home_dir: Option<PathBuf>,
53    /// Bytes read from the end of a rollout; defaults to [`ROLLOUT_TAIL_BYTES`]
54    pub max_bytes: Option<u64>,
55}
56
57impl CodexRolloutOptions {
58    /// Options for a run launched with `extra_env` and `unset_env`.
59    ///
60    /// A `CODEX_HOME` passed to the run wins; an unset one means `~/.codex`.
61    pub fn for_run_env(extra_env: &[(String, String)], unset_env: &[String]) -> Self {
62        let passed = extra_env
63            .iter()
64            .rev()
65            .find(|(name, value)| name == "CODEX_HOME" && !value.is_empty())
66            .map(|(_, value)| PathBuf::from(value));
67        let codex_home = passed.or_else(|| {
68            unset_env
69                .iter()
70                .any(|name| name == "CODEX_HOME")
71                .then(|| default_home_dir().join(".codex"))
72        });
73        Self {
74            codex_home,
75            ..Self::default()
76        }
77    }
78
79    fn max_bytes(&self) -> u64 {
80        self.max_bytes.unwrap_or(ROLLOUT_TAIL_BYTES)
81    }
82}
83
84/// Codex `sessions` directory
85pub fn codex_sessions_dir(options: &CodexRolloutOptions) -> PathBuf {
86    let codex_home = options
87        .codex_home
88        .clone()
89        .filter(|path| !path.as_os_str().is_empty())
90        .or_else(|| {
91            std::env::var_os("CODEX_HOME")
92                .filter(|value| !value.is_empty())
93                .map(PathBuf::from)
94        })
95        .unwrap_or_else(|| {
96            options
97                .home_dir
98                .clone()
99                .unwrap_or_else(default_home_dir)
100                .join(".codex")
101        });
102    codex_home.join(CODEX_SESSIONS_DIRNAME)
103}
104
105/// Whether `name` is the rollout file of `thread_id`
106pub fn is_codex_rollout_file_name(name: &str, thread_id: &str) -> bool {
107    name.starts_with("rollout-") && name.ends_with(&format!("-{thread_id}.jsonl"))
108}
109
110/// Find a thread's rollout; the newest date directories are searched first
111pub fn find_codex_rollout_file(sessions_dir: &Path, thread_id: &str) -> Option<PathBuf> {
112    if !THREAD_ID_PATTERN.is_match(thread_id) {
113        return None;
114    }
115    walk(sessions_dir, thread_id, 0)
116}
117
118fn walk(dir: &Path, thread_id: &str, depth: usize) -> Option<PathBuf> {
119    let mut entries: Vec<(String, fs::FileType)> = fs::read_dir(dir)
120        .ok()?
121        .filter_map(Result::ok)
122        .filter_map(|entry| {
123            let file_type = entry.file_type().ok()?;
124            Some((entry.file_name().to_string_lossy().into_owned(), file_type))
125        })
126        .collect();
127    entries.sort_by(|a, b| b.0.cmp(&a.0));
128    if let Some((name, _)) = entries.iter().find(|(name, file_type)| {
129        file_type.is_file() && is_codex_rollout_file_name(name, thread_id)
130    }) {
131        return Some(dir.join(name));
132    }
133    if depth >= MAX_ROLLOUT_SEARCH_DEPTH {
134        return None;
135    }
136    entries
137        .iter()
138        .filter(|(_, file_type)| file_type.is_dir())
139        .find_map(|(name, _)| walk(&dir.join(name), thread_id, depth + 1))
140}
141
142/// Whether `codex exec resume <thread_id>` can find the thread.
143///
144/// A run in a new container or `CODEX_HOME` should start a new session
145/// instead (hive-mind#2888).
146pub fn can_resume_codex_session(thread_id: &str, options: &CodexRolloutOptions) -> bool {
147    find_codex_rollout_file(&codex_sessions_dir(options), thread_id).is_some()
148}
149
150/// Usage-limit verdict from a rollout
151#[derive(Debug, Clone, Default, PartialEq, Eq)]
152pub struct CodexLimitVerdict {
153    pub reached: bool,
154    pub reason: String,
155    /// Reset time formatted as `MMM D, YYYY, h:mm A`
156    pub reset_time: Option<String>,
157    /// Always `UTC` when `reset_time` is set
158    pub timezone: Option<String>,
159    /// Reset epoch (seconds)
160    pub resets_at: Option<i64>,
161    /// `5-hour`, `weekly`, `N-minute` or `usage`
162    pub window: Option<String>,
163    pub rollout_path: Option<PathBuf>,
164}
165
166fn number(value: Option<&Value>) -> Option<f64> {
167    match value? {
168        Value::Number(number) => number.as_f64(),
169        Value::String(text) => text.trim().parse().ok(),
170        _ => None,
171    }
172    .filter(|number: &f64| number.is_finite())
173}
174
175fn format_number(value: f64) -> String {
176    if value.fract() == 0.0 && value.abs() < 1e15 {
177        format!("{value:.0}")
178    } else {
179        value.to_string()
180    }
181}
182
183fn describe_window(minutes: Option<f64>) -> String {
184    let Some(minutes) = minutes.filter(|minutes| *minutes > 0.0) else {
185        return "usage".to_string();
186    };
187    match format_number(minutes).as_str() {
188        "300" => "5-hour".to_string(),
189        "10080" => "weekly".to_string(),
190        label => format!("{label}-minute"),
191    }
192}
193
194struct RateWindow<'a> {
195    name: &'a str,
196    used_percent: f64,
197    resets_at: Option<f64>,
198    window_minutes: Option<f64>,
199}
200
201/// Classify a rollout `token_count.rate_limits` snapshot.
202///
203/// A window is reached at `used_percent >= 100` with a `resets_at`;
204/// `rate_limit_reached_type` alone (no reset) stays unclassified.
205pub fn classify_codex_rate_limit_snapshot(snapshot: Option<&Value>) -> CodexLimitVerdict {
206    let Some(snapshot) = snapshot.filter(|value| value.is_object()) else {
207        return CodexLimitVerdict {
208            reason: "no rate_limits snapshot".to_string(),
209            ..CodexLimitVerdict::default()
210        };
211    };
212    let windows: Vec<RateWindow<'_>> = ["primary", "secondary"]
213        .into_iter()
214        .filter_map(|name| {
215            let window = snapshot.get(name)?;
216            Some(RateWindow {
217                name,
218                used_percent: number(window.get("used_percent"))?,
219                resets_at: number(window.get("resets_at")),
220                window_minutes: number(window.get("window_minutes")),
221            })
222        })
223        .collect();
224    let type_note = snapshot
225        .get("rate_limit_reached_type")
226        .and_then(Value::as_str)
227        .filter(|kind| !kind.is_empty())
228        .map(|kind| format!(" ({kind})"))
229        .unwrap_or_default();
230    // The latest reset is when every exhausted window is usable again.
231    let reached = windows
232        .iter()
233        .filter(|window| {
234            window.used_percent >= 100.0 && window.resets_at.is_some_and(|at| at > 0.0)
235        })
236        .max_by(|a, b| {
237            a.resets_at
238                .partial_cmp(&b.resets_at)
239                .unwrap_or(std::cmp::Ordering::Equal)
240        });
241    let Some(window) = reached else {
242        let peak = windows
243            .iter()
244            .map(|window| window.used_percent)
245            .reduce(f64::max)
246            .map_or_else(
247                || "no windows".to_string(),
248                |peak| format!("peak used_percent {}", format_number(peak)),
249            );
250        return CodexLimitVerdict {
251            reason: format!("no window at 100% with resets_at ({peak}){type_note}"),
252            ..CodexLimitVerdict::default()
253        };
254    };
255    let label = describe_window(window.window_minutes);
256    #[allow(clippy::cast_possible_truncation)]
257    let resets_at = window.resets_at.map(|at| at as i64);
258    CodexLimitVerdict {
259        reached: true,
260        reason: format!(
261            "{} {label} window at {}%{type_note}",
262            window.name,
263            format_number(window.used_percent)
264        ),
265        reset_time: resets_at.and_then(format_epoch_reset_time_utc),
266        timezone: Some("UTC".to_string()),
267        resets_at,
268        window: Some(label),
269        rollout_path: None,
270    }
271}
272
273/// Usage-limit facts of a rollout's last turn
274#[derive(Debug, Clone, Default, PartialEq, Eq)]
275pub struct CodexRolloutLimitFacts {
276    /// Newest `token_count.rate_limits` snapshot
277    pub rate_limits: Option<Value>,
278    /// Message of the newest usage-limit `error` event
279    pub error_text: Option<String>,
280    /// Its `codex_error_info`
281    pub error_info: Option<Value>,
282}
283
284fn is_usage_limit_error_info(info: Option<&Value>) -> bool {
285    match info {
286        None | Some(Value::Null) => false,
287        Some(Value::String(text)) => text.to_lowercase().contains("usage_limit_exceeded"),
288        Some(value) => value
289            .to_string()
290            .to_lowercase()
291            .contains("usage_limit_exceeded"),
292    }
293}
294
295// The `event_msg` payload of one rollout line, if it is one.
296fn rollout_event_payload(line: &str) -> Option<Value> {
297    let mut entry: Value = serde_json::from_str(line).ok()?;
298    if entry.get("type").and_then(Value::as_str) != Some("event_msg") {
299        return None;
300    }
301    match entry.get_mut("payload").map(Value::take) {
302        Some(payload) if payload.is_object() => Some(payload),
303        _ => Some(entry),
304    }
305}
306
307// Keep the newest rate_limits snapshot and usage-limit error of a turn.
308fn collect_limit_fact(facts: &mut CodexRolloutLimitFacts, payload: &Value) {
309    let kind = payload.get("type").and_then(Value::as_str);
310    let rate_limits = payload.get("rate_limits").filter(|value| !value.is_null());
311    if kind == Some("token_count") && rate_limits.is_some() {
312        if facts.rate_limits.is_none() {
313            facts.rate_limits = rate_limits.cloned();
314        }
315        return;
316    }
317    if kind != Some("error") || facts.error_text.is_some() {
318        return;
319    }
320    let message = payload
321        .get("message")
322        .and_then(Value::as_str)
323        .unwrap_or_default();
324    let info = payload
325        .get("codex_error_info")
326        .filter(|value| !value.is_null());
327    if is_usage_limit_error_info(info) || is_usage_limit_text(message) {
328        facts.error_text = Some(if message.is_empty() {
329            "usage_limit_exceeded".to_string()
330        } else {
331            message.to_string()
332        });
333        facts.error_info = info.cloned();
334    }
335}
336
337/// Collect usage-limit facts from a rollout's last turn (JSONL text)
338pub fn codex_rollout_limit_facts(text: &str) -> CodexRolloutLimitFacts {
339    let mut facts = CodexRolloutLimitFacts::default();
340    for line in text.lines().rev() {
341        let Some(payload) = rollout_event_payload(line) else {
342            continue;
343        };
344        let kind = payload.get("type").and_then(Value::as_str);
345        if kind.is_some_and(|kind| TURN_START_TYPES.contains(&kind)) {
346            break;
347        }
348        collect_limit_fact(&mut facts, &payload);
349    }
350    facts
351}
352
353/// Read the last turn of a thread's rollout.
354///
355/// Returns the rollout path and its facts, or why no rollout was read.
356pub fn read_codex_rollout_limit_facts(
357    thread_id: &str,
358    options: &CodexRolloutOptions,
359) -> Result<(PathBuf, CodexRolloutLimitFacts), String> {
360    if thread_id.is_empty() {
361        return Err("no thread id".to_string());
362    }
363    let sessions_dir = codex_sessions_dir(options);
364    let rollout_path = find_codex_rollout_file(&sessions_dir, thread_id)
365        .ok_or_else(|| format!("no rollout under {}", sessions_dir.display()))?;
366    let text =
367        read_file_tail(&rollout_path, options.max_bytes()).map_err(|error| error.to_string())?;
368    Ok((rollout_path, codex_rollout_limit_facts(&text)))
369}
370
371/// Usage-limit verdict from a thread's rollout.
372///
373/// Used for a failed Codex exit that did not report the limit itself
374/// (hive-mind#3570).
375pub fn detect_codex_rollout_usage_limit(
376    thread_id: &str,
377    options: &CodexRolloutOptions,
378) -> CodexLimitVerdict {
379    let (rollout_path, facts) = match read_codex_rollout_limit_facts(thread_id, options) {
380        Ok(read) => read,
381        Err(reason) => {
382            return CodexLimitVerdict {
383                reason,
384                ..CodexLimitVerdict::default()
385            }
386        }
387    };
388    let snapshot = classify_codex_rate_limit_snapshot(facts.rate_limits.as_ref());
389    if snapshot.reached {
390        return CodexLimitVerdict {
391            rollout_path: Some(rollout_path),
392            ..snapshot
393        };
394    }
395    CodexLimitVerdict {
396        reached: facts.error_text.is_some(),
397        reason: facts
398            .error_text
399            .map_or(snapshot.reason, |text| format!("rollout error: {text}")),
400        rollout_path: Some(rollout_path),
401        ..CodexLimitVerdict::default()
402    }
403}
404
405/// Fill a failed Codex run's usage-limit fields from its rollout when the
406/// output did not report the limit.
407///
408/// A killed process cannot report one, so signalled runs are skipped.
409/// Returns whether the metadata changed.
410pub fn apply_codex_rollout_usage_limit(
411    metadata: &mut ResultMetadata,
412    options: &CodexRolloutOptions,
413) -> bool {
414    let Some(thread_id) = metadata.session_id.clone().filter(|id| !id.is_empty()) else {
415        return false;
416    };
417    if metadata.tool != "codex"
418        || metadata.exit_code == Some(0)
419        || metadata.signal.is_some()
420        || metadata.limit_reached
421    {
422        return false;
423    }
424    let verdict = detect_codex_rollout_usage_limit(&thread_id, options);
425    if !verdict.reached {
426        return false;
427    }
428    metadata.success = false;
429    metadata.limit_reached = true;
430    metadata.limit_reset_time = verdict.reset_time;
431    metadata.limit_timezone = verdict.timezone;
432    metadata.limit_resets_at = verdict.resets_at;
433    metadata.limit_window = verdict.window;
434    metadata.limit_source = Some(CODEX_ROLLOUT_LIMIT_SOURCE.to_string());
435    true
436}
437
438/// Fill a Codex run's `usage_windows` from the newest `rate_limits` snapshot
439/// in its rollout: `codex exec --json` does not stream the windows (issue #57).
440///
441/// Returns whether the metadata changed.
442pub fn apply_codex_rollout_usage_windows(
443    metadata: &mut ResultMetadata,
444    options: &CodexRolloutOptions,
445) -> bool {
446    let Some(thread_id) = metadata.session_id.clone().filter(|id| !id.is_empty()) else {
447        return false;
448    };
449    if metadata.tool != "codex" || !metadata.usage_windows.is_empty() {
450        return false;
451    }
452    let Ok((_, facts)) = read_codex_rollout_limit_facts(&thread_id, options) else {
453        return false;
454    };
455    metadata.usage_windows = codex_rate_limit_windows(facts.rate_limits.as_ref());
456    !metadata.usage_windows.is_empty()
457}
458
459/// Context usage from a rollout's `token_count` events (issue #57)
460pub fn codex_rollout_context_usage(text: &str) -> Option<crate::ContextUsage> {
461    let events: Vec<Value> = text.lines().filter_map(rollout_event_payload).collect();
462    extract_context_usage(&events)
463}
464
465/// Fill a Codex run's `context_usage` from the `token_count` events in its
466/// rollout: `codex exec --json` does not stream them (issue #57).
467///
468/// Returns whether the metadata changed.
469pub fn apply_codex_rollout_context_usage(
470    metadata: &mut ResultMetadata,
471    options: &CodexRolloutOptions,
472) -> bool {
473    let Some(thread_id) = metadata.session_id.clone().filter(|id| !id.is_empty()) else {
474        return false;
475    };
476    if metadata.tool != "codex" || metadata.context_usage.is_some() {
477        return false;
478    }
479    let sessions_dir = codex_sessions_dir(options);
480    let text = find_codex_rollout_file(&sessions_dir, &thread_id)
481        .and_then(|path| read_file_tail(&path, options.max_bytes()).ok());
482    metadata.context_usage = text.as_deref().and_then(codex_rollout_context_usage);
483    metadata.context_usage.is_some()
484}