agentmux_srv_core/backend/blockcontroller/subprocess/
codex_usage.rs1use std::collections::HashMap;
19use std::io::{BufRead, BufReader, Seek, SeekFrom};
20use std::path::{Path, PathBuf};
21use std::sync::{LazyLock, Mutex};
22
23use serde_json::Value;
24
25use crate::backend::token_ledger::FoundCall;
26use crate::backend::usage_of::usage_of_value;
27
28const SLACK_MS: i64 = 5_000;
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
33struct Mark {
34 path: PathBuf,
35 offset: u64,
36 model: Option<String>,
37 last_total: Option<String>,
39}
40
41static MARKS: LazyLock<Mutex<HashMap<String, Mark>>> = LazyLock::new(Mutex::default);
42
43pub(super) fn read_new(codex_home: &Path, thread_id: &str, started_ms: i64) -> Vec<FoundCall> {
46 let Some(path) = super::codex_context::session_file(codex_home, thread_id) else { return Vec::new() };
47 let known = MARKS.lock().unwrap_or_else(|e| e.into_inner()).get(thread_id).cloned().filter(|m| m.path == path);
48 let (found, mark) = scan(&path, thread_id, known, started_ms - SLACK_MS);
49 if let Some(mark) = mark {
50 MARKS.lock().unwrap_or_else(|e| e.into_inner()).insert(thread_id.to_string(), mark);
51 }
52 found
53}
54
55fn scan(path: &Path, thread_id: &str, known: Option<Mark>, not_before_ms: i64) -> (Vec<FoundCall>, Option<Mark>) {
58 let Ok(mut file) = std::fs::File::open(path) else { return (Vec::new(), None) };
59 let len = file.metadata().map(|m| m.len()).unwrap_or(0);
60 let from_start = known.as_ref().is_none_or(|m| m.offset > len);
62 let mut mark = if from_start { Mark { path: path.to_path_buf(), ..Mark::default() } } else { known.unwrap_or_default() };
63 if file.seek(SeekFrom::Start(mark.offset)).is_err() {
64 return (Vec::new(), None);
65 }
66 let mut found = Vec::new();
67 let mut reader = BufReader::new(file);
68 let mut line = Vec::new();
69 loop {
70 line.clear();
71 let Ok(n) = reader.read_until(b'\n', &mut line) else { break };
72 if n == 0 {
73 break;
74 }
75 if line.last() != Some(&b'\n') {
77 break;
78 }
79 let start = mark.offset;
80 mark.offset += n as u64;
81 let Ok(text) = std::str::from_utf8(&line) else { continue };
82 if let Some(call) = call_in(text, &mut mark) {
83 let at_ms = timestamp_ms(text).unwrap_or_else(agentmux_common::time::now_ms);
84 if !from_start || at_ms >= not_before_ms {
85 found.push(FoundCall { id: format!("codex|{thread_id}|{start}"), at_ms, call });
86 }
87 }
88 }
89 (found, Some(mark))
90}
91
92fn call_in(text: &str, mark: &mut Mark) -> Option<crate::backend::usage_of::CallUsage> {
94 let context = text.contains("\"turn_context\"");
96 if !context && !text.contains("\"token_count\"") {
97 return None;
98 }
99 let v: Value = serde_json::from_str(text).ok()?;
100 if context && v.get("type").and_then(Value::as_str) == Some("turn_context") {
101 mark.model = v.pointer("/payload/model").and_then(Value::as_str).filter(|m| !m.is_empty()).map(str::to_string);
102 return None;
103 }
104 let mut call = usage_of_value(&v)?;
106 let total = v.pointer("/payload/info/total_token_usage").map(Value::to_string);
107 if total.is_some() && total == mark.last_total {
108 return None;
109 }
110 mark.last_total = total;
111 call.model = mark.model.clone();
112 Some(call)
113}
114
115fn timestamp_ms(text: &str) -> Option<i64> {
116 let v: Value = serde_json::from_str(text).ok()?;
117 chrono::DateTime::parse_from_rfc3339(v.get("timestamp")?.as_str()?).ok().map(|t| t.timestamp_millis())
118}
119
120#[cfg(test)]
121#[path = "codex_usage_tests.rs"]
122mod tests;