1use regex::Regex;
16use serde_json::Value;
17use std::fs;
18use std::path::{Path, PathBuf};
19use std::sync::LazyLock;
20
21use crate::file_tail::{default_home_dir, read_file_tail};
22use crate::result_metadata::ResultMetadata;
23use crate::usage_limit::{format_epoch_reset_time_utc, is_usage_limit_text};
24
25pub const CODEX_SESSIONS_DIRNAME: &str = "sessions";
27
28pub const ROLLOUT_TAIL_BYTES: u64 = 1024 * 1024;
30
31pub const CODEX_ROLLOUT_LIMIT_SOURCE: &str = "codex-rollout";
33
34const MAX_ROLLOUT_SEARCH_DEPTH: usize = 5;
36const TURN_START_TYPES: [&str; 2] = ["task_started", "turn_started"];
37
38static THREAD_ID_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
40 Regex::new(r"^[0-9a-zA-Z][0-9a-zA-Z_-]{7,127}$").expect("valid thread id regex")
41});
42
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct CodexRolloutOptions {
46 pub codex_home: Option<PathBuf>,
49 pub home_dir: Option<PathBuf>,
51 pub max_bytes: Option<u64>,
53}
54
55impl CodexRolloutOptions {
56 pub fn for_run_env(extra_env: &[(String, String)], unset_env: &[String]) -> Self {
60 let passed = extra_env
61 .iter()
62 .rev()
63 .find(|(name, value)| name == "CODEX_HOME" && !value.is_empty())
64 .map(|(_, value)| PathBuf::from(value));
65 let codex_home = passed.or_else(|| {
66 unset_env
67 .iter()
68 .any(|name| name == "CODEX_HOME")
69 .then(|| default_home_dir().join(".codex"))
70 });
71 Self {
72 codex_home,
73 ..Self::default()
74 }
75 }
76
77 fn max_bytes(&self) -> u64 {
78 self.max_bytes.unwrap_or(ROLLOUT_TAIL_BYTES)
79 }
80}
81
82pub fn codex_sessions_dir(options: &CodexRolloutOptions) -> PathBuf {
84 let codex_home = options
85 .codex_home
86 .clone()
87 .filter(|path| !path.as_os_str().is_empty())
88 .or_else(|| {
89 std::env::var_os("CODEX_HOME")
90 .filter(|value| !value.is_empty())
91 .map(PathBuf::from)
92 })
93 .unwrap_or_else(|| {
94 options
95 .home_dir
96 .clone()
97 .unwrap_or_else(default_home_dir)
98 .join(".codex")
99 });
100 codex_home.join(CODEX_SESSIONS_DIRNAME)
101}
102
103pub fn is_codex_rollout_file_name(name: &str, thread_id: &str) -> bool {
105 name.starts_with("rollout-") && name.ends_with(&format!("-{thread_id}.jsonl"))
106}
107
108pub fn find_codex_rollout_file(sessions_dir: &Path, thread_id: &str) -> Option<PathBuf> {
110 if !THREAD_ID_PATTERN.is_match(thread_id) {
111 return None;
112 }
113 walk(sessions_dir, thread_id, 0)
114}
115
116fn walk(dir: &Path, thread_id: &str, depth: usize) -> Option<PathBuf> {
117 let mut entries: Vec<(String, fs::FileType)> = fs::read_dir(dir)
118 .ok()?
119 .filter_map(Result::ok)
120 .filter_map(|entry| {
121 let file_type = entry.file_type().ok()?;
122 Some((entry.file_name().to_string_lossy().into_owned(), file_type))
123 })
124 .collect();
125 entries.sort_by(|a, b| b.0.cmp(&a.0));
126 if let Some((name, _)) = entries.iter().find(|(name, file_type)| {
127 file_type.is_file() && is_codex_rollout_file_name(name, thread_id)
128 }) {
129 return Some(dir.join(name));
130 }
131 if depth >= MAX_ROLLOUT_SEARCH_DEPTH {
132 return None;
133 }
134 entries
135 .iter()
136 .filter(|(_, file_type)| file_type.is_dir())
137 .find_map(|(name, _)| walk(&dir.join(name), thread_id, depth + 1))
138}
139
140pub fn can_resume_codex_session(thread_id: &str, options: &CodexRolloutOptions) -> bool {
145 find_codex_rollout_file(&codex_sessions_dir(options), thread_id).is_some()
146}
147
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
150pub struct CodexLimitVerdict {
151 pub reached: bool,
152 pub reason: String,
153 pub reset_time: Option<String>,
155 pub timezone: Option<String>,
157 pub resets_at: Option<i64>,
159 pub window: Option<String>,
161 pub rollout_path: Option<PathBuf>,
162}
163
164fn number(value: Option<&Value>) -> Option<f64> {
165 match value? {
166 Value::Number(number) => number.as_f64(),
167 Value::String(text) => text.trim().parse().ok(),
168 _ => None,
169 }
170 .filter(|number: &f64| number.is_finite())
171}
172
173fn format_number(value: f64) -> String {
174 if value.fract() == 0.0 && value.abs() < 1e15 {
175 format!("{value:.0}")
176 } else {
177 value.to_string()
178 }
179}
180
181fn describe_window(minutes: Option<f64>) -> String {
182 let Some(minutes) = minutes.filter(|minutes| *minutes > 0.0) else {
183 return "usage".to_string();
184 };
185 match format_number(minutes).as_str() {
186 "300" => "5-hour".to_string(),
187 "10080" => "weekly".to_string(),
188 label => format!("{label}-minute"),
189 }
190}
191
192struct RateWindow<'a> {
193 name: &'a str,
194 used_percent: f64,
195 resets_at: Option<f64>,
196 window_minutes: Option<f64>,
197}
198
199pub fn classify_codex_rate_limit_snapshot(snapshot: Option<&Value>) -> CodexLimitVerdict {
204 let Some(snapshot) = snapshot.filter(|value| value.is_object()) else {
205 return CodexLimitVerdict {
206 reason: "no rate_limits snapshot".to_string(),
207 ..CodexLimitVerdict::default()
208 };
209 };
210 let windows: Vec<RateWindow<'_>> = ["primary", "secondary"]
211 .into_iter()
212 .filter_map(|name| {
213 let window = snapshot.get(name)?;
214 Some(RateWindow {
215 name,
216 used_percent: number(window.get("used_percent"))?,
217 resets_at: number(window.get("resets_at")),
218 window_minutes: number(window.get("window_minutes")),
219 })
220 })
221 .collect();
222 let type_note = snapshot
223 .get("rate_limit_reached_type")
224 .and_then(Value::as_str)
225 .filter(|kind| !kind.is_empty())
226 .map(|kind| format!(" ({kind})"))
227 .unwrap_or_default();
228 let reached = windows
230 .iter()
231 .filter(|window| {
232 window.used_percent >= 100.0 && window.resets_at.is_some_and(|at| at > 0.0)
233 })
234 .max_by(|a, b| {
235 a.resets_at
236 .partial_cmp(&b.resets_at)
237 .unwrap_or(std::cmp::Ordering::Equal)
238 });
239 let Some(window) = reached else {
240 let peak = windows
241 .iter()
242 .map(|window| window.used_percent)
243 .reduce(f64::max)
244 .map_or_else(
245 || "no windows".to_string(),
246 |peak| format!("peak used_percent {}", format_number(peak)),
247 );
248 return CodexLimitVerdict {
249 reason: format!("no window at 100% with resets_at ({peak}){type_note}"),
250 ..CodexLimitVerdict::default()
251 };
252 };
253 let label = describe_window(window.window_minutes);
254 #[allow(clippy::cast_possible_truncation)]
255 let resets_at = window.resets_at.map(|at| at as i64);
256 CodexLimitVerdict {
257 reached: true,
258 reason: format!(
259 "{} {label} window at {}%{type_note}",
260 window.name,
261 format_number(window.used_percent)
262 ),
263 reset_time: resets_at.and_then(format_epoch_reset_time_utc),
264 timezone: Some("UTC".to_string()),
265 resets_at,
266 window: Some(label),
267 rollout_path: None,
268 }
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Eq)]
273pub struct CodexRolloutLimitFacts {
274 pub rate_limits: Option<Value>,
276 pub error_text: Option<String>,
278 pub error_info: Option<Value>,
280}
281
282fn is_usage_limit_error_info(info: Option<&Value>) -> bool {
283 match info {
284 None | Some(Value::Null) => false,
285 Some(Value::String(text)) => text.to_lowercase().contains("usage_limit_exceeded"),
286 Some(value) => value
287 .to_string()
288 .to_lowercase()
289 .contains("usage_limit_exceeded"),
290 }
291}
292
293fn rollout_event_payload(line: &str) -> Option<Value> {
295 let mut entry: Value = serde_json::from_str(line).ok()?;
296 if entry.get("type").and_then(Value::as_str) != Some("event_msg") {
297 return None;
298 }
299 match entry.get_mut("payload").map(Value::take) {
300 Some(payload) if payload.is_object() => Some(payload),
301 _ => Some(entry),
302 }
303}
304
305fn collect_limit_fact(facts: &mut CodexRolloutLimitFacts, payload: &Value) {
307 let kind = payload.get("type").and_then(Value::as_str);
308 let rate_limits = payload.get("rate_limits").filter(|value| !value.is_null());
309 if kind == Some("token_count") && rate_limits.is_some() {
310 if facts.rate_limits.is_none() {
311 facts.rate_limits = rate_limits.cloned();
312 }
313 return;
314 }
315 if kind != Some("error") || facts.error_text.is_some() {
316 return;
317 }
318 let message = payload
319 .get("message")
320 .and_then(Value::as_str)
321 .unwrap_or_default();
322 let info = payload
323 .get("codex_error_info")
324 .filter(|value| !value.is_null());
325 if is_usage_limit_error_info(info) || is_usage_limit_text(message) {
326 facts.error_text = Some(if message.is_empty() {
327 "usage_limit_exceeded".to_string()
328 } else {
329 message.to_string()
330 });
331 facts.error_info = info.cloned();
332 }
333}
334
335pub fn codex_rollout_limit_facts(text: &str) -> CodexRolloutLimitFacts {
337 let mut facts = CodexRolloutLimitFacts::default();
338 for line in text.lines().rev() {
339 let Some(payload) = rollout_event_payload(line) else {
340 continue;
341 };
342 let kind = payload.get("type").and_then(Value::as_str);
343 if kind.is_some_and(|kind| TURN_START_TYPES.contains(&kind)) {
344 break;
345 }
346 collect_limit_fact(&mut facts, &payload);
347 }
348 facts
349}
350
351pub fn read_codex_rollout_limit_facts(
355 thread_id: &str,
356 options: &CodexRolloutOptions,
357) -> Result<(PathBuf, CodexRolloutLimitFacts), String> {
358 if thread_id.is_empty() {
359 return Err("no thread id".to_string());
360 }
361 let sessions_dir = codex_sessions_dir(options);
362 let rollout_path = find_codex_rollout_file(&sessions_dir, thread_id)
363 .ok_or_else(|| format!("no rollout under {}", sessions_dir.display()))?;
364 let text =
365 read_file_tail(&rollout_path, options.max_bytes()).map_err(|error| error.to_string())?;
366 Ok((rollout_path, codex_rollout_limit_facts(&text)))
367}
368
369pub fn detect_codex_rollout_usage_limit(
374 thread_id: &str,
375 options: &CodexRolloutOptions,
376) -> CodexLimitVerdict {
377 let (rollout_path, facts) = match read_codex_rollout_limit_facts(thread_id, options) {
378 Ok(read) => read,
379 Err(reason) => {
380 return CodexLimitVerdict {
381 reason,
382 ..CodexLimitVerdict::default()
383 }
384 }
385 };
386 let snapshot = classify_codex_rate_limit_snapshot(facts.rate_limits.as_ref());
387 if snapshot.reached {
388 return CodexLimitVerdict {
389 rollout_path: Some(rollout_path),
390 ..snapshot
391 };
392 }
393 CodexLimitVerdict {
394 reached: facts.error_text.is_some(),
395 reason: facts
396 .error_text
397 .map_or(snapshot.reason, |text| format!("rollout error: {text}")),
398 rollout_path: Some(rollout_path),
399 ..CodexLimitVerdict::default()
400 }
401}
402
403pub fn apply_codex_rollout_usage_limit(
409 metadata: &mut ResultMetadata,
410 options: &CodexRolloutOptions,
411) -> bool {
412 let Some(thread_id) = metadata.session_id.clone().filter(|id| !id.is_empty()) else {
413 return false;
414 };
415 if metadata.tool != "codex"
416 || metadata.exit_code == 0
417 || metadata.signal.is_some()
418 || metadata.limit_reached
419 {
420 return false;
421 }
422 let verdict = detect_codex_rollout_usage_limit(&thread_id, options);
423 if !verdict.reached {
424 return false;
425 }
426 metadata.success = false;
427 metadata.limit_reached = true;
428 metadata.limit_reset_time = verdict.reset_time;
429 metadata.limit_timezone = verdict.timezone;
430 metadata.limit_resets_at = verdict.resets_at;
431 metadata.limit_window = verdict.window;
432 metadata.limit_source = Some(CODEX_ROLLOUT_LIMIT_SOURCE.to_string());
433 true
434}