Skip to content

Commit b8c1be2

Browse files
unhappychoiceclaude
andcommitted
feat(fetcher/codex): scaffold module + shared session helpers
Lays the foundation for the codex_* family. `common.rs` carries the bits that both upcoming fetchers will share: - `discover_session_dirs()` + `list_session_files()` walk `~/.codex/sessions/` (or `$CODEX_HOME/sessions/`) and enumerate `rollout-*.jsonl` under the `YYYY/MM/DD/` tree, sorted lexically so the prefix gives free chronological order. - `price_for()` / `cost_usd()` cover the GPT-5 / GPT-4.1 / o-series prices with a longest-prefix-wins lookup; unknown models contribute $0 rather than hiding token activity behind an error. - `format_cost` / `format_tokens` keep figures compact enough for Badge or Text headlines; `project_name_from_cwd` / `short_model_name` normalise the axis labels that downstream rollups will use. `fetchers()` returns an empty vec for now — member fetchers join in follow-up commits. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 833bc31 commit b8c1be2

3 files changed

Lines changed: 381 additions & 0 deletions

File tree

‎src/fetcher/codex/common.rs‎

Lines changed: 348 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,348 @@
1+
//! Shared helpers for the `codex_*` family — model pricing, cost math, and the date-tree
2+
//! discovery used by `codex_usage` and `codex_subscription`.
3+
//!
4+
//! Pricing lives in source rather than a vendored file because the OpenAI model surface is
5+
//! small enough to track by hand; bumping a constant is less error-prone than parsing an
6+
//! external table on every fetch. When a new family ships, add a [`PRICE_TABLE`] row matching
7+
//! the model-id prefix.
8+
9+
use std::fs;
10+
use std::path::PathBuf;
11+
12+
/// USD per million tokens for a single OpenAI model family. `cached_input` covers the prompt
13+
/// cache discount (Codex CLI's `cached_input_tokens` lands here, billed at the discounted rate
14+
/// instead of the full `input` rate). Reasoning output is billed at the same rate as regular
15+
/// output today, so it folds into [`Price::output`].
16+
#[derive(Debug, Clone, Copy)]
17+
pub struct Price {
18+
pub input: f64,
19+
pub cached_input: f64,
20+
pub output: f64,
21+
}
22+
23+
const GPT_5: Price = Price {
24+
input: 1.25,
25+
cached_input: 0.125,
26+
output: 10.0,
27+
};
28+
29+
const GPT_5_MINI: Price = Price {
30+
input: 0.25,
31+
cached_input: 0.025,
32+
output: 2.0,
33+
};
34+
35+
const GPT_5_NANO: Price = Price {
36+
input: 0.05,
37+
cached_input: 0.005,
38+
output: 0.40,
39+
};
40+
41+
const GPT_4_1: Price = Price {
42+
input: 2.0,
43+
cached_input: 0.50,
44+
output: 8.0,
45+
};
46+
47+
const GPT_4_1_MINI: Price = Price {
48+
input: 0.40,
49+
cached_input: 0.10,
50+
output: 1.60,
51+
};
52+
53+
const O3: Price = Price {
54+
input: 2.0,
55+
cached_input: 0.50,
56+
output: 8.0,
57+
};
58+
59+
const O4_MINI: Price = Price {
60+
input: 1.10,
61+
cached_input: 0.275,
62+
output: 4.40,
63+
};
64+
65+
/// Prefix table — longest-prefix entries come first so `gpt-5-mini` doesn't get swallowed by
66+
/// `gpt-5`. Match is on the full lowercased model id.
67+
const PRICE_TABLE: &[(&str, Price)] = &[
68+
("gpt-5-nano", GPT_5_NANO),
69+
("gpt-5-mini", GPT_5_MINI),
70+
("gpt-5", GPT_5),
71+
("gpt-4.1-mini", GPT_4_1_MINI),
72+
("gpt-4.1", GPT_4_1),
73+
("o4-mini", O4_MINI),
74+
("o3", O3),
75+
];
76+
77+
pub fn price_for(model: &str) -> Option<Price> {
78+
let lower = model.to_lowercase();
79+
PRICE_TABLE
80+
.iter()
81+
.find(|(prefix, _)| lower.starts_with(prefix))
82+
.map(|(_, p)| *p)
83+
}
84+
85+
/// USD cost of a single turn given a model. Unknown models contribute 0 — surfacing them as
86+
/// "free" is friendlier than hiding the underlying token activity behind an error.
87+
pub fn cost_usd(
88+
model: &str,
89+
input_tokens: u64,
90+
cached_input_tokens: u64,
91+
output_tokens: u64,
92+
) -> f64 {
93+
let Some(p) = price_for(model) else {
94+
return 0.0;
95+
};
96+
let per_token = |rate_per_mt: f64, count: u64| (count as f64) * rate_per_mt / 1_000_000.0;
97+
// OpenAI reports `cached_input_tokens` as a subset of `input_tokens`; bill the cached chunk
98+
// at the discounted rate and the rest at the full input rate.
99+
let billable_input = input_tokens.saturating_sub(cached_input_tokens);
100+
per_token(p.input, billable_input)
101+
+ per_token(p.cached_input, cached_input_tokens)
102+
+ per_token(p.output, output_tokens)
103+
}
104+
105+
/// "$12.34" / "$0.05" / "$1.2k" — compact enough to fit a Badge or a Text headline.
106+
pub fn format_cost(usd: f64) -> String {
107+
if usd >= 1_000.0 {
108+
format!("${:.1}k", usd / 1_000.0)
109+
} else if usd >= 10.0 {
110+
format!("${:.2}", usd)
111+
} else if usd > 0.0 {
112+
format!("${:.3}", usd)
113+
} else {
114+
"$0.00".into()
115+
}
116+
}
117+
118+
/// "3.4M" / "812k" / "42" — same compact strategy for raw token counts.
119+
pub fn format_tokens(count: u64) -> String {
120+
if count >= 1_000_000 {
121+
format!("{:.1}M", count as f64 / 1_000_000.0)
122+
} else if count >= 1_000 {
123+
format!("{}k", count / 1_000)
124+
} else {
125+
count.to_string()
126+
}
127+
}
128+
129+
/// Codex CLI's per-day session roots. Default `~/.codex/sessions/`; the `CODEX_HOME` env var
130+
/// (Codex's own override) wins so power users with relocated installs stay covered.
131+
pub fn discover_session_dirs() -> Vec<PathBuf> {
132+
if let Ok(raw) = std::env::var("CODEX_HOME") {
133+
return vec![PathBuf::from(raw).join("sessions")];
134+
}
135+
dirs::home_dir()
136+
.map(|h| h.join(".codex").join("sessions"))
137+
.filter(|p| p.is_dir())
138+
.into_iter()
139+
.collect()
140+
}
141+
142+
/// Enumerate every `rollout-*.jsonl` under the `YYYY/MM/DD/` tree of each root. Sorted by
143+
/// filename (lexically chronological — Codex's `rollout-<rfc3339>` prefix gives free ordering).
144+
pub fn list_session_files(roots: &[PathBuf]) -> Vec<PathBuf> {
145+
let mut files: Vec<PathBuf> = roots.iter().flat_map(walk_year_month_day).collect();
146+
files.sort();
147+
files
148+
}
149+
150+
fn walk_year_month_day(root: &PathBuf) -> Vec<PathBuf> {
151+
read_subdirs(root)
152+
.into_iter()
153+
.flat_map(|year| read_subdirs(&year))
154+
.flat_map(|month| read_subdirs(&month))
155+
.flat_map(|day| read_jsonl_files(&day))
156+
.collect()
157+
}
158+
159+
fn read_subdirs(dir: &PathBuf) -> Vec<PathBuf> {
160+
fs::read_dir(dir)
161+
.ok()
162+
.into_iter()
163+
.flat_map(|it| it.flatten())
164+
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
165+
.map(|e| e.path())
166+
.collect()
167+
}
168+
169+
fn read_jsonl_files(dir: &PathBuf) -> Vec<PathBuf> {
170+
fs::read_dir(dir)
171+
.ok()
172+
.into_iter()
173+
.flat_map(|it| it.flatten())
174+
.map(|e| e.path())
175+
.filter(|p| p.extension().is_some_and(|x| x == "jsonl"))
176+
.collect()
177+
}
178+
179+
/// Last path component of a Codex `cwd` field — the bare project name without filesystem noise.
180+
/// Empty cwd falls back to `"(unknown)"` so renderers always get a non-empty key.
181+
pub fn project_name_from_cwd(cwd: &str) -> String {
182+
PathBuf::from(cwd)
183+
.file_name()
184+
.map(|n| n.to_string_lossy().into_owned())
185+
.filter(|s| !s.is_empty())
186+
.unwrap_or_else(|| "(unknown)".into())
187+
}
188+
189+
/// `gpt-5.5` → `gpt-5.5`, `gpt-5-2025-08-12` → `gpt-5`, `gpt-5-mini-2025-08-12` → `gpt-5-mini`.
190+
/// Drops a trailing dash-separated `YYYY-MM-DD` release stamp so the `group_by = model` axis
191+
/// collapses release ids into a family. Anything else passes through unchanged.
192+
pub fn short_model_name(model: &str) -> String {
193+
let lower = model.to_lowercase();
194+
strip_trailing_iso_date(&lower).unwrap_or(lower)
195+
}
196+
197+
fn strip_trailing_iso_date(s: &str) -> Option<String> {
198+
let bytes = s.as_bytes();
199+
// Match `-YYYY-MM-DD` at the end (11 chars total). Cheap manual scan; chrono would pull in
200+
// strftime parsing for what amounts to a regex literal.
201+
if bytes.len() < 11 {
202+
return None;
203+
}
204+
let tail = &bytes[bytes.len() - 11..];
205+
let ok = tail[0] == b'-'
206+
&& tail[5] == b'-'
207+
&& tail[8] == b'-'
208+
&& tail[1..5].iter().all(|b| b.is_ascii_digit())
209+
&& tail[6..8].iter().all(|b| b.is_ascii_digit())
210+
&& tail[9..11].iter().all(|b| b.is_ascii_digit());
211+
ok.then(|| s[..s.len() - 11].to_string())
212+
}
213+
214+
#[cfg(test)]
215+
mod tests {
216+
use super::*;
217+
218+
#[test]
219+
fn price_for_matches_gpt_5_family_by_prefix() {
220+
assert!(price_for("gpt-5").is_some());
221+
assert!(price_for("gpt-5.5").is_some());
222+
assert!(price_for("gpt-5-mini").is_some());
223+
assert!(price_for("gpt-5-nano").is_some());
224+
assert!(price_for("o4-mini").is_some());
225+
}
226+
227+
#[test]
228+
fn price_for_unknown_model_returns_none() {
229+
assert!(price_for("claude-opus-4-7").is_none());
230+
assert!(price_for("").is_none());
231+
}
232+
233+
#[test]
234+
fn price_for_longer_prefix_wins_over_shorter() {
235+
// gpt-5-mini must resolve to GPT_5_MINI, not GPT_5 (it's listed before in PRICE_TABLE).
236+
let mini = price_for("gpt-5-mini").unwrap();
237+
assert!(
238+
(mini.input - 0.25).abs() < 1e-9,
239+
"expected gpt-5-mini rate, got {}",
240+
mini.input
241+
);
242+
}
243+
244+
#[test]
245+
fn cost_usd_zero_for_unknown_model_even_with_tokens() {
246+
assert_eq!(cost_usd("claude-opus-4-7", 1_000_000, 0, 1_000_000), 0.0);
247+
}
248+
249+
#[test]
250+
fn cost_usd_charges_cached_input_at_discounted_rate() {
251+
// gpt-5: 1M billable input @ $1.25 + 0M cached + 0M output = $1.25
252+
let full = cost_usd("gpt-5", 1_000_000, 0, 0);
253+
assert!((full - 1.25).abs() < 1e-9, "got {full}");
254+
// Same input but all cached → 1M @ $0.125 = $0.125
255+
let cached = cost_usd("gpt-5", 1_000_000, 1_000_000, 0);
256+
assert!((cached - 0.125).abs() < 1e-9, "got {cached}");
257+
}
258+
259+
#[test]
260+
fn cost_usd_splits_partial_cache_against_full_and_cached_rates() {
261+
// 1M input where 0.5M is cached → 0.5M @ $1.25 + 0.5M @ $0.125 = $0.625 + $0.0625 = $0.6875
262+
let c = cost_usd("gpt-5", 1_000_000, 500_000, 0);
263+
assert!((c - 0.6875).abs() < 1e-9, "got {c}");
264+
}
265+
266+
#[test]
267+
fn format_cost_picks_unit_by_magnitude() {
268+
assert_eq!(format_cost(0.0), "$0.00");
269+
assert_eq!(format_cost(0.005), "$0.005");
270+
assert_eq!(format_cost(2.50), "$2.500");
271+
assert_eq!(format_cost(12.34), "$12.34");
272+
assert_eq!(format_cost(1234.0), "$1.2k");
273+
}
274+
275+
#[test]
276+
fn format_tokens_uses_m_and_k_suffixes() {
277+
assert_eq!(format_tokens(0), "0");
278+
assert_eq!(format_tokens(42), "42");
279+
assert_eq!(format_tokens(1_500), "1k");
280+
assert_eq!(format_tokens(3_400_000), "3.4M");
281+
}
282+
283+
#[test]
284+
fn project_name_from_cwd_takes_last_component() {
285+
assert_eq!(
286+
project_name_from_cwd("/home/owner/.ghq/github.com/unhappychoice/splashboard"),
287+
"splashboard"
288+
);
289+
assert_eq!(project_name_from_cwd(""), "(unknown)");
290+
}
291+
292+
#[test]
293+
fn short_model_name_strips_trailing_iso_date_only() {
294+
assert_eq!(short_model_name("gpt-5-2025-08-12"), "gpt-5");
295+
assert_eq!(short_model_name("gpt-5-mini-2025-08-12"), "gpt-5-mini");
296+
// No trailing date → pass through unchanged.
297+
assert_eq!(short_model_name("gpt-5.5"), "gpt-5.5");
298+
assert_eq!(short_model_name("o4-mini"), "o4-mini");
299+
// A trailing integer that isn't an ISO date must not be stripped.
300+
assert_eq!(short_model_name("gpt-5-mini-12345"), "gpt-5-mini-12345");
301+
}
302+
303+
#[test]
304+
fn discover_session_dirs_honours_codex_home_env() {
305+
let _lock = crate::paths::TEST_ENV_LOCK
306+
.lock()
307+
.unwrap_or_else(|e| e.into_inner());
308+
let prev = std::env::var("CODEX_HOME").ok();
309+
unsafe { std::env::set_var("CODEX_HOME", "/tmp/codex-test-home") };
310+
let dirs = discover_session_dirs();
311+
assert_eq!(dirs.len(), 1);
312+
assert!(dirs[0].ends_with("codex-test-home/sessions"));
313+
match prev {
314+
Some(v) => unsafe { std::env::set_var("CODEX_HOME", v) },
315+
None => unsafe { std::env::remove_var("CODEX_HOME") },
316+
}
317+
}
318+
319+
#[test]
320+
fn list_session_files_walks_year_month_day_tree_sorted() {
321+
let tmp = tempfile::tempdir().unwrap();
322+
let day = tmp.path().join("2026").join("05").join("23");
323+
fs::create_dir_all(&day).unwrap();
324+
fs::write(day.join("rollout-2026-05-23T01-00-00-b.jsonl"), "").unwrap();
325+
fs::write(day.join("rollout-2026-05-23T00-00-00-a.jsonl"), "").unwrap();
326+
// Non-jsonl + extra noise must be ignored.
327+
fs::write(day.join("note.txt"), "").unwrap();
328+
let files = list_session_files(&[tmp.path().to_path_buf()]);
329+
assert_eq!(files.len(), 2);
330+
// Lexical sort = chronological because filenames are rfc3339-prefixed.
331+
assert!(
332+
files[0]
333+
.file_name()
334+
.unwrap()
335+
.to_str()
336+
.unwrap()
337+
.contains("00-00-00-a")
338+
);
339+
assert!(
340+
files[1]
341+
.file_name()
342+
.unwrap()
343+
.to_str()
344+
.unwrap()
345+
.contains("01-00-00-b")
346+
);
347+
}
348+
}

‎src/fetcher/codex/mod.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//! Codex (OpenAI Codex CLI) fetchers.
2+
//!
3+
//! Scaffolding for the family. Individual fetchers (`codex_usage`, `codex_subscription`,
4+
//! etc.) live as siblings of [`common`] and register through [`fetchers`].
5+
//!
6+
//! `Safety::Safe` — every member of the family reads from `~/.codex/sessions/` (or the
7+
//! `CODEX_HOME` override) and never opens a network connection.
8+
9+
mod common;
10+
11+
use std::sync::Arc;
12+
13+
use crate::fetcher::Fetcher;
14+
15+
pub fn fetchers() -> Vec<Arc<dyn Fetcher>> {
16+
Vec::new()
17+
}
18+
19+
#[cfg(test)]
20+
mod tests {
21+
use super::*;
22+
23+
#[test]
24+
fn fetchers_entry_point_starts_empty_until_members_are_registered() {
25+
// Commit-1 contract: the entry point exists and returns an empty vec. Member fetchers
26+
// are added by subsequent commits; this assertion is amended as they land.
27+
assert!(fetchers().is_empty());
28+
}
29+
}

‎src/fetcher/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ pub mod calendar;
1717
pub mod claude;
1818
pub mod clock;
1919
pub mod code;
20+
pub mod codex;
2021
pub mod crypto_trending;
2122
pub mod crypto_watchlist;
2223
pub mod deal;
@@ -353,6 +354,9 @@ impl Registry {
353354
for f in claude::fetchers() {
354355
r.register(f);
355356
}
357+
for f in codex::fetchers() {
358+
r.register(f);
359+
}
356360
for f in deal::fetchers() {
357361
r.register(f);
358362
}

0 commit comments

Comments
 (0)