From 71cad59842304e6ac85f1064274bf80952c7a7f5 Mon Sep 17 00:00:00 2001 From: Varun Ravindra Poojari Date: Mon, 28 Sep 2026 12:18:51 +0100 Subject: [PATCH] Record Codex token usage in cost tracking (SECFOO-37) codex exec prints its run total as a 'tokens used' line on stderr, but extract_usage() only ever saw stdout, so Codex runs showed 0 / '-' in secfoo cost and the dashboard. - base.py: add an extract_usage_from_stderr() hook, consulted only when extract_usage() finds nothing, so claude/gemini are unaffected. - codex.py: parse the last 'tokens used' total from stderr. Codex gives a single total with no split and no cost, so it is stored as input_tokens and cost stays unknown. - Tests for the parser and for the run() fallback. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BnvD24nuxVRZF72ZGNT6Rx --- src/secfoo/agents/base.py | 18 ++++++++++++- src/secfoo/agents/codex.py | 20 +++++++++++++- tests/test_agents/test_base.py | 21 +++++++++++++++ tests/test_agents/test_codex.py | 48 +++++++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 2 deletions(-) diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index a22b83a..054b718 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -99,6 +99,22 @@ def extract_usage(self, stdout: str) -> Usage: """Pull token counts / cost out of raw stdout. Default: unknown.""" return Usage() + def extract_usage_from_stderr(self, stderr: str) -> Usage: + """Pull token counts / cost out of raw stderr. Default: unknown. + + For CLIs that print usage alongside their progress output on stderr + rather than in stdout (e.g. Codex). Only consulted when + `extract_usage()` found nothing, so adapters that already read usage + from stdout are unaffected. + """ + return Usage() + + def _collect_usage(self, stdout: str, stderr: str) -> Usage: + usage = self.extract_usage(stdout) + if usage == Usage(): + usage = self.extract_usage_from_stderr(stderr) + return usage + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: if not self.is_available(): return AgentResult( @@ -133,7 +149,7 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen stdout, stderr = proc.communicate(timeout=effective_timeout) duration = time.monotonic() - started status: Status = "success" if proc.returncode == 0 else "failed" - usage = self.extract_usage(stdout) + usage = self._collect_usage(stdout, stderr) return AgentResult( agent=self.name, exit_code=proc.returncode, diff --git a/src/secfoo/agents/codex.py b/src/secfoo/agents/codex.py index be3efe0..28c6d4b 100644 --- a/src/secfoo/agents/codex.py +++ b/src/secfoo/agents/codex.py @@ -12,6 +12,13 @@ review never needs write access, so we pin `--sandbox read-only` instead. - `--json`: see above. +Token usage: `codex exec` ends its stderr with a "tokens used" line followed +by the run's total on the next line (e.g. "tokens used\n15,201"). It is a +single total with no input/output split and no cost, so it is recorded as +`input_tokens` with `output_tokens` and `cost_usd` left unknown (None) -- +`secfoo cost` then shows the total under "Input tokens", "-" for output, and +"-" for cost. + MCP servers from ~/.secfoo/config.toml are not wired up for Codex yet (`secfoo mcp sync --agent codex` is a follow-up); Codex runs use whatever is already in the user's own ~/.codex/config.toml. @@ -19,9 +26,13 @@ from __future__ import annotations +import re from pathlib import Path -from secfoo.agents.base import AgentAdapter +from secfoo.agents.base import AgentAdapter, Usage + +# "tokens used" on its own line, then the total (thousands separators allowed). +_TOKENS_USED_RE = re.compile(r"^\s*tokens used\s*\n\s*([\d,]+)\s*$", re.MULTILINE | re.IGNORECASE) class CodexAdapter(AgentAdapter): @@ -52,3 +63,10 @@ def build_command(self, prompt: str, *, workdir: Path) -> list[str]: "--", prompt, ] + + def extract_usage_from_stderr(self, stderr: str) -> Usage: + matches = _TOKENS_USED_RE.findall(stderr or "") + if not matches: + return Usage() + # Last occurrence is the end-of-run summary. + return Usage(input_tokens=int(matches[-1].replace(",", ""))) diff --git a/tests/test_agents/test_base.py b/tests/test_agents/test_base.py index ddf08b8..91d2025 100644 --- a/tests/test_agents/test_base.py +++ b/tests/test_agents/test_base.py @@ -100,3 +100,24 @@ def _raise(*a, **kw): monkeypatch.setattr("secfoo.agents.base.subprocess.run", _raise) _kill_process_tree(4321, posix=False) # must not raise + + +def test_run_falls_back_to_stderr_usage_when_stdout_has_none(fake_popen, tmp_path): + from secfoo.agents.codex import CodexAdapter + + fake_popen(returncode=0, stdout="# Report", stderr="working...\ntokens used\n15,201\n") + result = CodexAdapter().run("hi", workdir=tmp_path) + assert result.status == "success" + assert result.input_tokens == 15201 + assert result.output_tokens is None + assert result.cost_usd is None + + +def test_run_prefers_stdout_usage_over_stderr(fake_popen, tmp_path, monkeypatch): + from secfoo.agents.base import Usage + from secfoo.agents.codex import CodexAdapter + + monkeypatch.setattr(CodexAdapter, "extract_usage", lambda self, stdout: Usage(input_tokens=7, output_tokens=3)) + fake_popen(returncode=0, stdout="# Report", stderr="tokens used\n15,201\n") + result = CodexAdapter().run("hi", workdir=tmp_path) + assert (result.input_tokens, result.output_tokens) == (7, 3) diff --git a/tests/test_agents/test_codex.py b/tests/test_agents/test_codex.py index 30cc83d..1aadc39 100644 --- a/tests/test_agents/test_codex.py +++ b/tests/test_agents/test_codex.py @@ -41,3 +41,51 @@ def test_prompt_is_last_arg_after_double_dash(tmp_path): def test_extract_report_is_stdout_passthrough(): assert CodexAdapter().extract_report("final message") == "final message" + + +CODEX_STDERR = """OpenAI Codex v0.155.0 (research preview) +-------- +workdir: /tmp/target +model: gpt-5-codex +sandbox: read-only +-------- +user +Run a SAST review +exec +bash -lc 'ls -la' in /tmp/target + succeeded in 12ms: +app.py +codex +Report written. +tokens used +15,201 +""" + + +def test_extract_usage_from_stderr_reads_total_tokens(): + usage = CodexAdapter().extract_usage_from_stderr(CODEX_STDERR) + assert usage.input_tokens == 15201 + assert usage.output_tokens is None + assert usage.cost_usd is None # Codex never reports cost + + +def test_extract_usage_from_stderr_uses_last_occurrence(): + stderr = "tokens used\n100\nmore work\ntokens used\n2,500\n" + assert CodexAdapter().extract_usage_from_stderr(stderr).input_tokens == 2500 + + +def test_extract_usage_from_stderr_without_summary_is_unknown(): + usage = CodexAdapter().extract_usage_from_stderr("some progress output\n") + assert usage.input_tokens is None + assert CodexAdapter().extract_usage_from_stderr("").input_tokens is None + + +def test_extract_usage_from_stderr_ignores_prose_mentioning_tokens(): + # The phrase inside a sentence must not be mistaken for the summary. + stderr = "the tokens used by this API are 42 per call\n" + assert CodexAdapter().extract_usage_from_stderr(stderr).input_tokens is None + + +def test_stdout_usage_is_still_unknown(): + # The report on stdout carries no usage; stderr is the only source. + assert CodexAdapter().extract_usage("final message").input_tokens is None