Skip to main content

kaizen/collect/tail/
codex.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2//! Parse Codex (OpenAI) transcript `.jsonl` files into Events.
3//! Pure parser — no notify dependency, no IO beyond file reads.
4
5use crate::collect::model_from_json;
6use crate::core::cost::estimate_tail_event_cost_usd_e6;
7use crate::core::event::{Event, EventKind, EventSource, SessionRecord, SessionStatus};
8use anyhow::{Context, Result};
9use serde_json::Value;
10use std::path::Path;
11
12/// Parse one `.jsonl` line. Returns `Some(Event)` for action-bearing lines.
13/// Extracts `usage.prompt_tokens` / `usage.completion_tokens` when present.
14pub fn parse_codex_line(
15    session_id: &str,
16    seq: u64,
17    base_ts: u64,
18    line: &str,
19) -> Result<Option<Event>> {
20    let v: Value = serde_json::from_str(line.trim()).context("codex transcript: invalid JSON")?;
21    let obj = match v.as_object() {
22        Some(o) => o,
23        None => return Ok(None),
24    };
25
26    let tokens_in = obj
27        .get("usage")
28        .and_then(|u| u.get("prompt_tokens"))
29        .and_then(|v| v.as_u64())
30        .map(|v| v as u32);
31
32    let tokens_out = obj
33        .get("usage")
34        .and_then(|u| u.get("completion_tokens"))
35        .and_then(|v| v.as_u64())
36        .map(|v| v as u32);
37
38    let reasoning_tokens = obj
39        .get("usage")
40        .and_then(|u| u.get("completion_tokens_details"))
41        .and_then(|d| d.get("reasoning_tokens"))
42        .and_then(|v| v.as_u64())
43        .map(|v| v as u32)
44        .or_else(|| {
45            obj.get("usage")
46                .and_then(|u| u.get("output_tokens_details"))
47                .and_then(|d| d.get("reasoning_tokens"))
48                .and_then(|v| v.as_u64())
49                .map(|v| v as u32)
50        });
51
52    let ts_ms = line_ts_ms(obj).unwrap_or(base_ts + seq * 100);
53    let ts_exact = line_ts_ms(obj).is_some();
54    let line_model = model_from_json::from_object(obj);
55    let cost_usd_e6 = estimate_tail_event_cost_usd_e6(
56        line_model.as_deref(),
57        tokens_in,
58        tokens_out,
59        reasoning_tokens,
60    );
61
62    // Tool calls are in top-level `tool_calls` array
63    if let Some(first) = obj
64        .get("tool_calls")
65        .and_then(|tc| tc.as_array())
66        .and_then(|arr| arr.first())
67    {
68        let tool_name = first
69            .get("function")
70            .and_then(|f| f.get("name"))
71            .and_then(|n| n.as_str())
72            .unwrap_or("")
73            .to_string();
74        return Ok(Some(Event {
75            session_id: session_id.to_string(),
76            seq,
77            ts_ms,
78            ts_exact,
79            kind: EventKind::ToolCall,
80            source: EventSource::Tail,
81            tool: Some(tool_name),
82            tool_call_id: first
83                .get("id")
84                .and_then(|v| v.as_str())
85                .map(ToOwned::to_owned),
86            tokens_in,
87            tokens_out,
88            reasoning_tokens,
89            cost_usd_e6,
90            stop_reason: None,
91            latency_ms: None,
92            ttft_ms: None,
93            retry_count: None,
94            context_used_tokens: None,
95            context_max_tokens: None,
96            cache_creation_tokens: None,
97            cache_read_tokens: None,
98            system_prompt_tokens: None,
99            payload: first.clone(),
100        }));
101    }
102
103    Ok(None)
104}
105
106fn line_ts_ms(obj: &serde_json::Map<String, Value>) -> Option<u64> {
107    ["timestamp_ms", "ts_ms", "created_at_ms", "timestamp"]
108        .iter()
109        .find_map(|k| obj.get(*k).and_then(crate::collect::tail::value_ts_ms))
110}
111
112/// Walk all `.jsonl` files under `dir`; return inferred `SessionRecord` + events.
113/// Agent = "codex". Session id = dir name.
114pub fn scan_codex_session_dir(dir: &Path) -> Result<(SessionRecord, Vec<Event>)> {
115    let session_id = dir
116        .file_name()
117        .and_then(|n| n.to_str())
118        .unwrap_or("")
119        .to_string();
120
121    let workspace = dir
122        .parent()
123        .and_then(|p| p.parent())
124        .map(|p| p.to_string_lossy().to_string())
125        .unwrap_or_default();
126
127    let mut events = Vec::new();
128    let mut seq: u64 = 0;
129    let mut model: Option<String> = None;
130
131    let base_ts = crate::collect::tail::dir_mtime_ms(dir);
132    let mut entries: Vec<_> = std::fs::read_dir(dir)
133        .with_context(|| format!("read dir: {}", dir.display()))?
134        .filter_map(|e| e.ok())
135        .filter(|e| e.path().extension().map(|x| x == "jsonl").unwrap_or(false))
136        .collect();
137    entries.sort_by_key(|e| e.file_name());
138
139    for entry in entries {
140        let content = std::fs::read_to_string(entry.path())?;
141        for line in content.lines() {
142            if line.trim().is_empty() {
143                continue;
144            }
145            if let Some(m) = model_from_json::from_line(line) {
146                model = Some(m);
147            }
148            if let Some(ev) = parse_codex_line(&session_id, seq, base_ts, line)? {
149                events.push(ev);
150            }
151            seq += 1;
152        }
153    }
154
155    let record = SessionRecord {
156        id: session_id.clone(),
157        agent: "codex".to_string(),
158        model,
159        workspace,
160        started_at_ms: crate::collect::tail::dir_mtime_ms(dir),
161        ended_at_ms: None,
162        status: SessionStatus::Done,
163        trace_path: dir.to_string_lossy().to_string(),
164        start_commit: None,
165        end_commit: None,
166        branch: None,
167        dirty_start: None,
168        dirty_end: None,
169        repo_binding_source: None,
170        prompt_fingerprint: None,
171        parent_session_id: None,
172        agent_version: None,
173        os: None,
174        arch: None,
175        repo_file_count: None,
176        repo_total_loc: None,
177    };
178    Ok((record, events))
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    const TOOL_USE_LINE: &str = r#"{"role":"assistant","content":null,"tool_calls":[{"id":"call_01","type":"function","function":{"name":"shell","arguments":"{\"command\":\"ls\"}"}}]}"#;
186    const WITH_USAGE_LINE: &str = r#"{"role":"assistant","content":null,"tool_calls":[{"id":"call_02","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"src/main.rs\"}"}}],"usage":{"prompt_tokens":500,"completion_tokens":300,"total_tokens":800}}"#;
187
188    #[test]
189    fn parse_tool_use() {
190        let ev = parse_codex_line("s1", 0, 0, TOOL_USE_LINE)
191            .unwrap()
192            .unwrap();
193        assert_eq!(ev.kind, EventKind::ToolCall);
194        assert_eq!(ev.tool.as_deref(), Some("shell"));
195        assert_eq!(ev.tool_call_id.as_deref(), Some("call_01"));
196        assert_eq!(ev.session_id, "s1");
197    }
198
199    #[test]
200    fn parse_with_usage() {
201        let ev = parse_codex_line("s1", 0, 0, WITH_USAGE_LINE)
202            .unwrap()
203            .unwrap();
204        assert_eq!(ev.tokens_in, Some(500));
205        assert_eq!(ev.tokens_out, Some(300));
206        assert!(
207            ev.cost_usd_e6.is_some_and(|c| c > 0),
208            "expected tail cost from usage"
209        );
210    }
211
212    #[test]
213    fn scan_fixture_dir() {
214        let fixture_dir =
215            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/codex");
216        let (record, events) = scan_codex_session_dir(&fixture_dir).unwrap();
217        assert_eq!(record.agent, "codex");
218        assert_eq!(record.model.as_deref(), Some("gpt-4o-fixture"));
219        assert!(!events.is_empty(), "expected events from fixture files");
220        assert!(
221            events.iter().any(|e| e.cost_usd_e6.is_some_and(|c| c > 0)),
222            "with_usage fixture should yield cost"
223        );
224    }
225}