Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
codex_context.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How full a Codex thread's context is, for the pane's context meter.
5//!
6//! `codex exec --json` reports only the thread's running totals: three
7//! one-word turns read `input_tokens` 14,295, 28,608 and 42,939 (codex-cli
8//! 0.154.0), so its `turn.completed` is never a context size. Codex's own
9//! session file (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-…-<thread>.jsonl`,
10//! the local date the thread started) records each model call's usage:
11//!
12//! ```text
13//! {"type":"event_msg","payload":{"type":"token_count","info":{
14//!   "total_token_usage":{"input_tokens":42939,…},
15//!   "last_token_usage":{"input_tokens":14331,"cached_input_tokens":14080,…},
16//!   "model_context_window":258400}}}
17//! {"type":"turn_context","payload":{…,"model":"gpt-6-astra",…}}
18//! ```
19//!
20//! `last_token_usage.input_tokens` is the last call's whole prompt (cached
21//! included), and `model_context_window` the window Codex compacts against.
22//! After each host turn srv reads them and writes an `agentmux_context` frame
23//! into the pane's stream, which the frontend reads for any provider
24//! (frontend/app/view/agent/context-reader.ts). A container pane's session file
25//! is inside its container, so it gets none.
26
27use std::io::{Read, Seek, SeekFrom};
28use std::path::{Path, PathBuf};
29
30use chrono::{Duration, Local, TimeZone};
31use serde_json::{json, Value};
32
33/// How much of a session file's end is read: its last turn's `token_count`
34/// and `turn_context`. A long thread's file runs to megabytes.
35const TAIL_BYTES: u64 = 1024 * 1024;
36
37/// The last model call's context, from a Codex session file.
38#[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
45/// The `CODEX_HOME` a turn runs with: the pane's own (its account), else
46/// srv's, else Codex's default `~/.codex`.
47pub(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
56/// The thread's context after its last turn, or None when its session file
57/// can't be found or records none.
58pub(super) fn read(codex_home: &Path, thread_id: &str) -> Option<CodexContext> {
59    last_context(&session_file(codex_home, thread_id)?)
60}
61
62/// The `agentmux_context` frame for `ctx`.
63pub(super) fn frame(ctx: &CodexContext) -> Value {
64    json!({ "type": "agentmux_context", "tokens": ctx.tokens, "window": ctx.window, "model": ctx.model })
65}
66
67/// The thread's session file. A thread id is a UUIDv7, whose first 48 bits
68/// are when it started (unix ms), and Codex files it under that local date;
69/// the days either side are tried too, for a clock or time zone that moved.
70pub(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
84/// The last `token_count` in the file's tail, with the model of the last
85/// `turn_context` there (None when the tail holds none).
86fn 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    // The first line may be cut off by the seek; it fails to parse and is skipped.
95    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        // Cheap checks first: most lines are messages and tool output.
102        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    /// Lines shaped like codex-cli 0.154.0's (measured 2026-10-22): a thread
129    /// of three one-word turns, the last call 14,331 tokens of 258,400.
130    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}