Skip to main content

agentmux_srv_core/backend/blockcontroller/subprocess/
codex_usage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The calls a Codex thread made, read from its session file for the per-task token ledger
5//! (`docs/specs/SPEC_TOKEN_ANALYSIS_PER_KANBAN_TASK_2026_11_22.md` section 4.2). `codex exec --json` reports only the
6//! thread's running totals, so the ledger reads the calls from Codex's own file (the one `codex_context.rs` finds),
7//! once each turn has exited.
8//!
9//! The file is append-only, so a byte offset names a line for good: a call's id is its thread and the offset its line
10//! starts at, and the offset read up to is kept per thread, so a turn reads only what it added. The ledger keeps each
11//! counted id, so reading a line twice (after a restart, which loses the offset) adds nothing; only lines made at or
12//! after the turn's start count when there is no offset, so a restart does not count a thread's history again.
13//!
14//! One `token_count` event with a non-null `info` is one call, from its `last_token_usage`. Codex repeats an event
15//! when nothing ran between two of them: an event whose `total_token_usage` equals the last one's is not a call. The
16//! model is the last `turn_context` before the event. Nothing but counts, a model name, a time and an offset is kept.
17
18use 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
28/// A turn's own events may be stamped a little before the time its process started (clocks, the file's own write time).
29const SLACK_MS: i64 = 5_000;
30
31/// How far a thread's file was read, and what the lines before that said.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33struct Mark {
34    path: PathBuf,
35    offset: u64,
36    model: Option<String>,
37    /// The `total_token_usage` of the last event counted, as text.
38    last_total: Option<String>,
39}
40
41static MARKS: LazyLock<Mutex<HashMap<String, Mark>>> = LazyLock::new(Mutex::default);
42
43/// The calls a thread's file has gained since the last read, with the model each ran on. `started_ms` is when the
44/// turn that has just ended started.
45pub(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
55/// Read `path` from the mark (or from its start when there is none, counting only events made at or after
56/// `not_before_ms`). The new mark is None when the file could not be read.
57fn 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    // A file shorter than the mark was replaced: read it from the start.
61    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        // The last line may be half written: leave it for the next read.
76        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
92/// What `text` adds to the mark (a model, a last total) and the call it reports, if it reports one.
93fn call_in(text: &str, mark: &mut Mark) -> Option<crate::backend::usage_of::CallUsage> {
94    // Cheap tests first: most lines are messages and tool output.
95    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    // A null `info` (before the first call) reads as no call.
105    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;