agentmux_srv_core/backend/blockcontroller/subprocess/
codex_context.rs1use std::io::{Read, Seek, SeekFrom};
28use std::path::{Path, PathBuf};
29
30use chrono::{Duration, Local, TimeZone};
31use serde_json::{json, Value};
32
33const TAIL_BYTES: u64 = 1024 * 1024;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub(super) struct CodexContext {
40 pub tokens: u64,
41 pub window: Option<u64>,
42 pub model: Option<String>,
43}
44
45pub(super) fn codex_home(env_vars: &std::collections::HashMap<String, String>) -> Option<PathBuf> {
48 env_vars
49 .get("CODEX_HOME")
50 .filter(|h| !h.is_empty())
51 .map(PathBuf::from)
52 .or_else(|| std::env::var_os("CODEX_HOME").filter(|h| !h.is_empty()).map(PathBuf::from))
53 .or_else(|| dirs::home_dir().map(|h| h.join(".codex")))
54}
55
56pub(super) fn read(codex_home: &Path, thread_id: &str) -> Option<CodexContext> {
59 last_context(&session_file(codex_home, thread_id)?)
60}
61
62pub(super) fn frame(ctx: &CodexContext) -> Value {
64 json!({ "type": "agentmux_context", "tokens": ctx.tokens, "window": ctx.window, "model": ctx.model })
65}
66
67pub(super) fn session_file(codex_home: &Path, thread_id: &str) -> Option<PathBuf> {
71 let hex: String = thread_id.chars().filter(|c| *c != '-').take(12).collect();
72 let started_ms = i64::from_str_radix(&hex, 16).ok().filter(|_| hex.len() == 12)?;
73 let started = Local.timestamp_millis_opt(started_ms).single()?;
74 let suffix = format!("-{thread_id}.jsonl");
75 [0, -1, 1].into_iter().find_map(|days| {
76 let day = started + Duration::days(days);
77 let dir = codex_home.join("sessions").join(day.format("%Y").to_string()).join(day.format("%m").to_string()).join(day.format("%d").to_string());
78 std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).find(|p| {
79 p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("rollout-") && n.ends_with(&suffix))
80 })
81 })
82}
83
84fn last_context(path: &Path) -> Option<CodexContext> {
87 let mut file = std::fs::File::open(path).ok()?;
88 let len = file.metadata().ok()?.len();
89 let start = len.saturating_sub(TAIL_BYTES);
90 file.seek(SeekFrom::Start(start)).ok()?;
91 let mut tail = Vec::with_capacity((len - start) as usize);
92 file.read_to_end(&mut tail).ok()?;
93 let text = String::from_utf8_lossy(&tail);
94 let mut usage: Option<(u64, Option<u64>)> = None;
96 let mut model: Option<String> = None;
97 for line in text.lines().rev() {
98 if usage.is_some() && model.is_some() {
99 break;
100 }
101 let is_count = usage.is_none() && line.contains("\"token_count\"");
103 let is_context = model.is_none() && line.contains("\"turn_context\"");
104 if !is_count && !is_context {
105 continue;
106 }
107 let Ok(v) = serde_json::from_str::<Value>(line) else { continue };
108 if is_count && v.pointer("/payload/type").and_then(Value::as_str) == Some("token_count") {
109 let info = v.pointer("/payload/info");
110 let tokens = info.and_then(|i| i.pointer("/last_token_usage/input_tokens")).and_then(Value::as_u64).filter(|t| *t > 0);
111 if let Some(tokens) = tokens {
112 let window = info.and_then(|i| i.get("model_context_window")).and_then(Value::as_u64).filter(|w| *w > 0);
113 usage = Some((tokens, window));
114 }
115 }
116 if is_context && v.get("type").and_then(Value::as_str) == Some("turn_context") {
117 model = v.pointer("/payload/model").and_then(Value::as_str).filter(|m| !m.is_empty()).map(str::to_string);
118 }
119 }
120 let (tokens, window) = usage?;
121 Some(CodexContext { tokens, window, model })
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 fn session_lines() -> Vec<String> {
131 let count = |total: u64, last: u64| {
132 json!({ "timestamp": "2026-10-23T01:15:23.217Z", "type": "event_msg", "payload": { "type": "token_count", "info": {
133 "total_token_usage": { "input_tokens": total, "cached_input_tokens": total - 2_000, "output_tokens": 5 },
134 "last_token_usage": { "input_tokens": last, "cached_input_tokens": last - 251, "output_tokens": 5 },
135 "model_context_window": 258_400 } } })
136 .to_string()
137 };
138 let context = json!({ "type": "turn_context", "payload": { "cwd": "/w", "model": "gpt-6-astra", "approval_policy": "never" } }).to_string();
139 let message = json!({ "type": "response_item", "payload": { "type": "message", "role": "assistant", "content": [{ "type": "output_text", "text": "token_count is in this reply" }] } }).to_string();
140 vec![context.clone(), message.clone(), count(14_295, 14_295), context, message.clone(), count(28_608, 14_313), count(42_939, 14_331), message]
141 }
142
143 fn write_session(home: &Path, thread_id: &str, lines: &[String]) -> PathBuf {
144 let hex: String = thread_id.chars().filter(|c| *c != '-').take(12).collect();
145 let day = Local.timestamp_millis_opt(i64::from_str_radix(&hex, 16).unwrap()).single().unwrap();
146 let dir = home.join("sessions").join(day.format("%Y/%m/%d").to_string());
147 std::fs::create_dir_all(&dir).unwrap();
148 let path = dir.join(format!("rollout-{}-{thread_id}.jsonl", day.format("%Y-%m-%dT%H-%M-%S")));
149 std::fs::write(&path, lines.join("\n") + "\n").unwrap();
150 path
151 }
152
153 const THREAD: &str = "01a16653-6ccb-7842-8746-7619c0f55215";
154
155 #[test]
156 fn reads_the_last_calls_context_never_the_threads_total() {
157 let home = tempfile::tempdir().unwrap();
158 write_session(home.path(), THREAD, &session_lines());
159 let ctx = read(home.path(), THREAD).expect("a reading");
160 assert_eq!(ctx, CodexContext { tokens: 14_331, window: Some(258_400), model: Some("gpt-6-astra".into()) });
161 assert_eq!(frame(&ctx), json!({ "type": "agentmux_context", "tokens": 14_331, "window": 258_400, "model": "gpt-6-astra" }));
162 }
163
164 #[test]
165 fn finds_the_file_from_the_date_in_the_thread_id() {
166 let home = tempfile::tempdir().unwrap();
167 let path = write_session(home.path(), THREAD, &session_lines());
168 assert_eq!(session_file(home.path(), THREAD), Some(path));
169 assert_eq!(session_file(home.path(), "01a16653-6ccb-7842-8746-000000000000"), None, "another thread of the same day");
170 assert_eq!(session_file(home.path(), "not-a-uuid"), None);
171 }
172
173 #[test]
174 fn a_tail_past_the_turn_context_still_has_the_tokens() {
175 let home = tempfile::tempdir().unwrap();
176 let mut lines = session_lines();
177 lines.retain(|l| !l.contains("turn_context"));
178 write_session(home.path(), THREAD, &lines);
179 assert_eq!(read(home.path(), THREAD).map(|c| (c.tokens, c.model)), Some((14_331, None)));
180 }
181
182 #[test]
183 fn none_without_a_session_file_or_a_count() {
184 let home = tempfile::tempdir().unwrap();
185 assert_eq!(read(home.path(), THREAD), None);
186 let lines: Vec<String> = session_lines().into_iter().filter(|l| !l.contains("\"token_count\"")).collect();
187 write_session(home.path(), THREAD, &lines);
188 assert_eq!(read(home.path(), THREAD), None);
189 }
190
191 #[test]
192 fn the_panes_own_codex_home_comes_first() {
193 let env = std::collections::HashMap::from([("CODEX_HOME".to_string(), "/accounts/a/codex".to_string())]);
194 assert_eq!(codex_home(&env), Some(PathBuf::from("/accounts/a/codex")));
195 }
196}