Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(codex): add session-level token attribution

shukieshah5340465bb449
diff --git a/README.md b/README.md
index 2009f925..c2531f26 100644
--- a/README.md
+++ b/README.md
@@ -82,7 +82,7 @@ CI, and cloud surfaces.
| [Antigravity CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-antigravity-cli) | Native hooks | Prompt, pre-tool, post-tool, stop, invocation, command, and file telemetry where Antigravity exposes hook payloads |
| [Claude Code](https://docs.asymptotelabs.ai/cli/supported-runtimes-claude-code) | Local OTLP export plus optional hooks | Prompt, command, tool, file, approval, API/model lifecycle, MCP connection, subagent, and session telemetry where emitted through OTLP or hooks |
| [Cline](https://docs.asymptotelabs.ai/cli/supported-runtimes-cline) | Managed plugin hooks | Prompts, task lifecycle/errors, tool lifecycle/results, commands with exit codes, file reads/edits with diffs, MCP activity, and task token usage/cost |
-| [Codex CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-codex-cli) | Local OTLP logs | Session, prompt, approval, and tool-result activity from Codex semantic logs |
+| [Codex CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-codex-cli) | Local OTLP logs and selective turn traces plus a session identity hook | Session, prompt, approval, tool-result activity, and per-user/session/model turn token usage |
| [Cursor](https://docs.asymptotelabs.ai/cli/supported-runtimes-cursor) | Native hooks | Prompt, tool, shell command, MCP-like, approval, and file edit telemetry |
| [Devin CLI](https://docs.asymptotelabs.ai/cli/supported-runtimes-devin) | Native hooks | Session, prompt, pre-tool, post-tool, permission request, stop, session-end, approval, and file telemetry |
| [Devin Desktop](https://docs.asymptotelabs.ai/cli/supported-runtimes-devin-desktop) | Cascade/Windsurf hooks | Prompt, command, MCP tool, file read, and file write telemetry where Desktop exposes Cascade hook payloads |
diff --git a/cli/beacon-hooks/cmd/codex_session_context.go b/cli/beacon-hooks/cmd/codex_session_context.go
new file mode 100644
index 00000000..1f4d82b6
--- /dev/null
+++ b/cli/beacon-hooks/cmd/codex_session_context.go
@@ -0,0 +1,37 @@
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/logging"
+)
+
+var codexSessionContextCmd = &cobra.Command{
+ Use: "codex-session-context",
+ Short: "Record local user context for a Codex session",
+ Hidden: true,
+ Run: runCodexSessionContext,
+}
+
+func init() {
+ rootCmd.AddCommand(codexSessionContextCmd)
+}
+
+func runCodexSessionContext(cmd *cobra.Command, args []string) {
+ input, err := readStdinJSON()
+ if err != nil || platformFlag != "codex" {
+ outputJSON(emptyResponse)
+ return
+ }
+
+ sessionID := resolveSessionID(input, "codex")
+ if sessionID == "" {
+ outputJSON(emptyResponse)
+ return
+ }
+ logger := logging.NewSessionLogger("codex-session-context", "codex", sessionID)
+ fields := sessionFieldsForPlatform(sessionID, input, "codex")
+ fields["raw"] = map[string]interface{}{"source": "codex_session_start_hook"}
+ emitHookEvent(logger, "session.context", "session", "info", "Codex session context observed", input, fields)
+ outputJSON(emptyResponse)
+}
diff --git a/cli/beacon-hooks/cmd/codex_session_context_test.go b/cli/beacon-hooks/cmd/codex_session_context_test.go
new file mode 100644
index 00000000..398269f6
--- /dev/null
+++ b/cli/beacon-hooks/cmd/codex_session_context_test.go
@@ -0,0 +1,65 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestRunCodexSessionContextWritesAttributableSessionEvent(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("USER", "alice")
+ originalPlatform := platformFlag
+ platformFlag = "codex"
+ t.Cleanup(func() { platformFlag = originalPlatform })
+
+ runHookWithInput(t, runCodexSessionContext, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "session_id": "codex-session",
+ "model": "gpt-5.6-sol",
+ "cwd": "/repo",
+ })
+
+ events := endpointEvents(t, logPath)
+ if len(events) != 1 {
+ t.Fatalf("events = %d, want one session context", len(events))
+ }
+ event := events[0]
+ eventInfo := event["event"].(map[string]interface{})
+ if eventInfo["action"] != "session.context" || eventInfo["fidelity"] != "observed" {
+ t.Fatalf("event = %#v, want observed session.context", eventInfo)
+ }
+ if event["model"] != "gpt-5.6-sol" || event["repository"] != "/repo" {
+ t.Fatalf("model/repository = %#v/%#v", event["model"], event["repository"])
+ }
+ session := event["session"].(map[string]interface{})
+ if session["id"] != "codex-session" || session["working_directory"] != "/repo" {
+ t.Fatalf("session = %#v", session)
+ }
+ user := event["user"].(map[string]interface{})
+ if user["name"] != "alice" || user["uid"] == "" {
+ t.Fatalf("user = %#v, want local name and UID", user)
+ }
+ raw := event["raw"].(map[string]interface{})
+ if raw["source"] != "codex_session_start_hook" {
+ t.Fatalf("raw = %#v", raw)
+ }
+}
+
+func TestRunCodexSessionContextSkipsMissingSession(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ originalPlatform := platformFlag
+ platformFlag = "codex"
+ t.Cleanup(func() { platformFlag = originalPlatform })
+
+ runHookWithInput(t, runCodexSessionContext, map[string]interface{}{
+ "hook_event_name": "SessionStart",
+ "model": "gpt-5.6-sol",
+ })
+
+ if _, err := os.Stat(logPath); !os.IsNotExist(err) {
+ t.Fatalf("session context wrote an event without a session id: %v", err)
+ }
+}
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 750d7359..8b9bb50e 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"os"
+ osuser "os/user"
"path/filepath"
"runtime"
"strconv"
@@ -135,11 +136,17 @@ func (l *Logger) EndpointEventWithFidelity(action, category, severity, message,
func (l *Logger) baseEndpointEvent(action, category, severity, message, fidelity string) map[string]interface{} {
hostname, _ := os.Hostname()
+ userName := os.Getenv("USER")
user := map[string]interface{}{
- "name": os.Getenv("USER"),
+ "name": userName,
}
if uid := firstEnv("BEACON_CLOUD_USER_ID_HASH", "BEACON_CLOUD_USER_ID"); uid != "" {
user["uid"] = uid
+ } else if current, err := osuser.Current(); err == nil {
+ user["uid"] = current.Uid
+ if userName == "" {
+ user["name"] = current.Username
+ }
}
// Both blocks are assembled before the event literal so the provenance keys can be omitted
// rather than written empty. This path builds raw maps instead of the shared Event struct, so
diff --git a/cli/beacon/README.md b/cli/beacon/README.md
index f8375b02..32805f6e 100644
--- a/cli/beacon/README.md
+++ b/cli/beacon/README.md
@@ -138,6 +138,11 @@ The dashboard reads the configured runtime JSONL log and serves a local,
read-only view on loopback. It has no external network dependency during normal
use.
+Use `./beacon token-usage` for the same token data in the terminal. Claude Code
+and supported Codex versions share the canonical `gen_ai.usage` schema; Codex
+turn traces add per-session and per-model counts, and its metadata-only
+SessionStart hook enables local OS-user rollups.
+
Use the search bar to find events by action, command, file path, MCP tool,
approval decision, repository, session, or message. Quick filters surface
high-severity events, failures, approvals, MCP activity, file changes, and events
diff --git a/cli/beacon/cmd/endpoint_codex_usage_diagnostics_test.go b/cli/beacon/cmd/endpoint_codex_usage_diagnostics_test.go
new file mode 100644
index 00000000..9238c493
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_codex_usage_diagnostics_test.go
@@ -0,0 +1,48 @@
+package cmd
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+)
+
+func TestCodexTokenAttributionCheckReportsTurnUsage(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ line := `{"event":{"action":"token.usage"},"harness":{"name":"codex_cli"},"raw":{"source":"codex_turn_span"}}`
+ if err := os.WriteFile(logPath, []byte(line+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ got := codexTokenAttributionCheck(logPath, true)
+ if got.Status != diagnostics.StatusOK || got.Evidence != "codex_turn_usage_observed" {
+ t.Fatalf("check = %#v", got)
+ }
+}
+
+func TestCodexTokenAttributionCheckWarnsWhenContextHasNoUsage(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ line := `{"event":{"action":"session.context"},"harness":{"name":"codex_cli"},"raw":{"source":"codex_session_start_hook"}}`
+ if err := os.WriteFile(logPath, []byte(line+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ got := codexTokenAttributionCheck(logPath, false)
+ if got.Status != diagnostics.StatusWarn ||
+ got.Evidence != "codex_session_without_turn_usage" ||
+ !strings.Contains(got.Action, "--system") {
+ t.Fatalf("check = %#v", got)
+ }
+}
+
+func TestCodexTokenAttributionCheckIdentifiesLegacyMetrics(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ line := `{"event":{"action":"token.usage"},"harness":{"name":"codex_cli"},"raw":{"metric_name":"codex.turn.token_usage"}}`
+ if err := os.WriteFile(logPath, []byte(line+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ got := codexTokenAttributionCheck(logPath, true)
+ if got.Status != diagnostics.StatusWarn || got.Evidence != "codex_legacy_usage_metrics" {
+ t.Fatalf("check = %#v", got)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index b9cde9c5..f25e3582 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -153,8 +153,15 @@ func buildDoctorResult(status lifecycle.Status, generatedAt time.Time) doctorRes
if !status.RuntimeLog.EffectiveUserMode {
checks = append(checks, consoleUserConfigCheck())
}
+ codexDetected := false
for _, h := range status.Harnesses {
checks = append(checks, harnessCheck(h, status.LogPath, status.RuntimeLog.EffectiveUserMode))
+ if h.Detected && h.Name == "codex_cli" {
+ codexDetected = true
+ }
+ }
+ if codexDetected {
+ checks = append(checks, codexTokenAttributionCheck(status.LogPath, status.RuntimeLog.EffectiveUserMode))
}
result := doctorResult{
Status: aggregateCheckStatus(checks),
@@ -1244,6 +1251,38 @@ func harnessEventObserved(logPath, name string) bool {
return endpointintegrations.HasRecentHarnessEvent(logPath, name)
}
+func codexTokenAttributionCheck(logPath string, effectiveUserMode bool) diagnostics.Check {
+ signals := endpointintegrations.ScanCodexUsageSignals(logPath)
+ check := diagnostics.Check{
+ Name: "codex_token_attribution",
+ Target: "codex_cli",
+ Severity: diagnostics.SeverityInfo,
+ }
+ switch {
+ case signals.TurnSpans > 0:
+ check.Status = diagnostics.StatusOK
+ check.Message = "session-attributed Codex turn usage is present"
+ check.Evidence = "codex_turn_usage_observed"
+ case signals.SessionContexts > 0:
+ check.Status = diagnostics.StatusWarn
+ check.Severity = diagnostics.SeverityMedium
+ check.Message = "Codex session context is present but no attributable turn usage span has arrived"
+ check.Evidence = "codex_session_without_turn_usage"
+ check.Action = doctorRepairCommand(effectiveUserMode) + " and restart Codex"
+ case signals.LegacyMetrics > 0:
+ check.Status = diagnostics.StatusWarn
+ check.Severity = diagnostics.SeverityLow
+ check.Message = "only legacy aggregate Codex token metrics are present; session and user attribution are unavailable"
+ check.Evidence = "codex_legacy_usage_metrics"
+ check.Action = doctorRepairCommand(effectiveUserMode) + " and restart Codex"
+ default:
+ check.Status = diagnostics.StatusOK
+ check.Message = "no Codex token usage has been observed yet"
+ check.Evidence = "codex_usage_not_observed"
+ }
+ return check
+}
+
func harnessAction(h harness.Harness, effectiveUserMode bool) string {
switch h.Capability {
case "hooks", "plugin":
diff --git a/cli/beacon/cmd/endpoint_hooks.go b/cli/beacon/cmd/endpoint_hooks.go
index b2968fda..297b02ea 100644
--- a/cli/beacon/cmd/endpoint_hooks.go
+++ b/cli/beacon/cmd/endpoint_hooks.go
@@ -99,7 +99,7 @@ func installEndpointHookTarget(name string, cfg endpointconfig.Config) error {
if err != nil {
return err
}
- fmt.Printf("Codex CLI inventory hooks installed: %s\n", status.HooksPath)
+ fmt.Printf("Codex CLI endpoint hooks installed: %s\n", status.HooksPath)
case "vscode":
status, err := endpointhooks.InstallVSCode(endpointhooks.VSCodeOptions{
Level: endpointhooks.Level(endpointOpts.hookLevel),
diff --git a/cli/beacon/cmd/endpoint_targets.go b/cli/beacon/cmd/endpoint_targets.go
index b4f9dda9..fb24aa36 100644
--- a/cli/beacon/cmd/endpoint_targets.go
+++ b/cli/beacon/cmd/endpoint_targets.go
@@ -128,6 +128,14 @@ func splitEndpointTargets(values []string) (otlp []string, hooks []string, err e
otlp = append(otlp, target.Name)
seenOTLP[target.Name] = true
}
+ // Codex usage comes from OTLP turn spans, but those spans do not
+ // identify the local OS account. Its SessionStart context hook is
+ // therefore part of the token integration rather than an optional
+ // duplicate activity path.
+ if target.Name == "codex" && !seenHooks["codex"] {
+ hooks = append(hooks, "codex")
+ seenHooks["codex"] = true
+ }
case endpointTargetHook:
if !seenHooks[target.Name] {
hooks = append(hooks, target.Name)
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
index 5e7bca9c..d87931ae 100644
--- a/cli/beacon/cmd/endpoint_test.go
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -57,7 +57,7 @@ func TestSplitEndpointTargetsDedupesHookAliases(t *testing.T) {
if got, want := strings.Join(otlp, ","), "claude,codex"; got != want {
t.Fatalf("otlp targets = %q, want %q", got, want)
}
- if got, want := strings.Join(hooks, ","), "devin-cli,devin-desktop,hermes"; got != want {
+ if got, want := strings.Join(hooks, ","), "codex,devin-cli,devin-desktop,hermes"; got != want {
t.Fatalf("hook targets = %q, want %q", got, want)
}
}
@@ -189,7 +189,7 @@ func TestRepairInstalledEndpointUserConfigConfiguresNativeAndHooks(t *testing.T)
for _, want := range []string{
"[otel]",
`endpoint = "http://127.0.0.1:4317"`,
- "[otel.metrics_exporter.\"otlp-grpc\"]",
+ "[otel.trace_exporter.\"otlp-grpc\"]",
} {
if !strings.Contains(string(codexConfig), want) {
t.Fatalf("Codex config missing %q:\n%s", want, codexConfig)
diff --git a/cli/beacon/cmd/token_usage_test.go b/cli/beacon/cmd/token_usage_test.go
index f9297e52..9ddd7d9c 100644
--- a/cli/beacon/cmd/token_usage_test.go
+++ b/cli/beacon/cmd/token_usage_test.go
@@ -30,9 +30,10 @@ func writeTokensFixtureLog(t *testing.T) string {
t.Helper()
logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
lines := []string{
- `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"input_tokens":100}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
- `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"output_tokens":40}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
- `{"timestamp":"2026-06-11T10:05:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"cost.usage","category":"metric"},"severity":"info","endpoint":{"os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","run":{"provider":"github_actions","run_id":"777"},"gen_ai":{"usage":{"cost_usd":0.5}},"message":"claude_code.cost.usage","raw":{"metric_name":"claude_code.cost.usage","metric_temporality":"Delta"}}`,
+ `{"timestamp":"2026-06-11T09:59:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"session.context","category":"session"},"severity":"info","endpoint":{"hostname":"mac","os":"darwin"},"user":{"name":"alice","uid":"501"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"message":"Session context observed"}`,
+ `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"hostname":"mac","os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"input_tokens":100}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
+ `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"hostname":"mac","os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"output_tokens":40}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
+ `{"timestamp":"2026-06-11T10:05:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"cost.usage","category":"metric"},"severity":"info","endpoint":{"hostname":"mac","os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"session-1"},"model":"claude-sonnet-4-5","run":{"provider":"github_actions","run_id":"777"},"gen_ai":{"usage":{"cost_usd":0.5}},"message":"claude_code.cost.usage","raw":{"metric_name":"claude_code.cost.usage","metric_temporality":"Delta"}}`,
}
if err := os.WriteFile(logPath, []byte(strings.Join(lines, "\n")+"\n"), 0644); err != nil {
t.Fatalf("write fixture log: %v", err)
@@ -59,9 +60,10 @@ func TestTokenUsageTextReport(t *testing.T) {
logPath := writeTokensFixtureLog(t)
output := runTokenUsageCommand(t, "--log-path", logPath)
for _, want := range []string{
- "3 of 3 events carry usage",
+ "3 of 4 events carry usage",
"claude-sonnet-4-5",
"session-1",
+ "alice [501]",
"claude_code",
"github_actions/777",
"0.5000",
@@ -85,6 +87,9 @@ func TestTokenUsageJSONReport(t *testing.T) {
if len(report.ByRun) != 1 || report.ByRun[0].Key != "github_actions/777" {
t.Fatalf("by_run = %#v", report.ByRun)
}
+ if len(report.ByUser) != 1 || report.ByUser[0].Key != "alice [501]" {
+ t.Fatalf("by_user = %#v", report.ByUser)
+ }
if report.SessionDetail == nil || report.SessionDetail.SessionID != "session-1" || len(report.SessionDetail.Steps) != 3 {
t.Fatalf("session detail = %#v", report.SessionDetail)
}
diff --git a/cli/beacon/internal/endpoint/dashboard/server_test.go b/cli/beacon/internal/endpoint/dashboard/server_test.go
index c023c763..ca218702 100644
--- a/cli/beacon/internal/endpoint/dashboard/server_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/server_test.go
@@ -173,6 +173,7 @@ func itoa2(v int) string {
func TestTokensEndpointAggregatesUsage(t *testing.T) {
logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
lines := []string{
+ `{"timestamp":"2026-06-11T09:59:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"session.context","category":"session"},"severity":"info","endpoint":{"os":"darwin"},"user":{"name":"alice","uid":"501"},"harness":{"name":"claude_code"},"session":{"id":"local-session"},"message":"Session context observed"}`,
// Claude Code metric datapoint events (delta temporality).
`{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"local-session"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"input_tokens":100}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
`{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"os":"darwin"},"harness":{"name":"claude_code"},"session":{"id":"local-session"},"model":"claude-sonnet-4-5","gen_ai":{"usage":{"output_tokens":40}},"message":"claude_code.token.usage","raw":{"metric_name":"claude_code.token.usage","metric_temporality":"Delta"}}`,
@@ -207,6 +208,9 @@ func TestTokensEndpointAggregatesUsage(t *testing.T) {
if len(report.BySession) != 2 {
t.Fatalf("by_session = %#v", report.BySession)
}
+ if len(report.ByUser) != 1 || report.ByUser[0].Key != "alice [501]" || report.ByUser[0].Usage.InputTokens != 100 {
+ t.Fatalf("by_user = %#v", report.ByUser)
+ }
if len(report.Series) != 2 {
t.Fatalf("series = %#v", report.Series)
}
diff --git a/cli/beacon/internal/endpoint/dashboard/static/app.js b/cli/beacon/internal/endpoint/dashboard/static/app.js
index 5bde5382..1605981b 100644
--- a/cli/beacon/internal/endpoint/dashboard/static/app.js
+++ b/cli/beacon/internal/endpoint/dashboard/static/app.js
@@ -1145,6 +1145,7 @@ function renderTokensPage(report, session) {
renderUtilizationRows(report.utilization || []);
renderUsageGroupRows("#token-models", report.by_model || [], "model");
renderUsageGroupRows("#token-sessions", report.by_session || [], "session");
+ renderUsageGroupRows("#token-users", report.by_user || []);
renderUsageGroupRows("#token-runs", report.by_run || []);
renderUsageGroupRows("#token-harnesses", report.by_harness || []);
renderSessionDetail(report.session_detail, session);
diff --git a/cli/beacon/internal/endpoint/dashboard/static/tokens.html b/cli/beacon/internal/endpoint/dashboard/static/tokens.html
index 373ca42d..6e4ec2fc 100644
--- a/cli/beacon/internal/endpoint/dashboard/static/tokens.html
+++ b/cli/beacon/internal/endpoint/dashboard/static/tokens.html
@@ -74,6 +74,16 @@
</table>
</section>
+ <section class="panel">
+ <h2>By User</h2>
+ <table>
+ <thead>
+ <tr><th>User</th><th>Input</th><th>Output</th><th>Cache Read</th><th>Cache Create</th><th>Reasoning</th><th>Cost USD</th><th>Events</th></tr>
+ </thead>
+ <tbody id="token-users"></tbody>
+ </table>
+ </section>
+
<section class="panel" id="token-session-panel" hidden>
<h2 id="token-session-title">Session Detail</h2>
<table>
diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.go
index b890fd6e..5d75c98c 100644
--- a/cli/beacon/internal/endpoint/harness/harness.go
+++ b/cli/beacon/internal/endpoint/harness/harness.go
@@ -500,10 +500,11 @@ func codexOTELBlock(endpoint string, logUserPrompt bool) []string {
"[otel.exporter.\"otlp-grpc\"]",
fmt.Sprintf("endpoint = %q", endpoint),
"",
- // metrics_exporter is a separate Codex setting from the log/event
- // exporter above; without it Codex exports logs but no metrics, so the
- // codex.turn.token_usage histogram never reaches the collector.
- "[otel.metrics_exporter.\"otlp-grpc\"]",
+ // Codex's completed-turn trace carries thread, turn, model, and token
+ // fields together. The histogram exporter omits thread identity, so
+ // Beacon uses traces as the one live source and avoids double-counting
+ // the same turn through both channels.
+ "[otel.trace_exporter.\"otlp-grpc\"]",
fmt.Sprintf("endpoint = %q", endpoint),
}
}
diff --git a/cli/beacon/internal/endpoint/harness/harness_test.go b/cli/beacon/internal/endpoint/harness/harness_test.go
index 382f12a1..25e342ab 100644
--- a/cli/beacon/internal/endpoint/harness/harness_test.go
+++ b/cli/beacon/internal/endpoint/harness/harness_test.go
@@ -178,21 +178,21 @@ func TestConfigureCodexWritesTelemetryBlockAndBackup(t *testing.T) {
"log_user_prompt = true",
"[otel.exporter.\"otlp-grpc\"]",
"endpoint = \"http://127.0.0.1:4317\"",
- // metrics_exporter is required for the codex.turn.token_usage metric that
- // backs Codex token/cost attribution.
- "[otel.metrics_exporter.\"otlp-grpc\"]",
+ // Turn traces carry token counts together with thread, turn, and model
+ // identity, unlike the aggregate metric.
+ "[otel.trace_exporter.\"otlp-grpc\"]",
} {
if !strings.Contains(text, want) {
t.Fatalf("codex config missing %q:\n%s", want, text)
}
}
- // Traces stay disabled: Codex spans are high-volume and opt-in via
- // --include-codex-spans, and are not needed for token usage.
- for _, noisy := range []string{
- "[otel.trace_exporter.\"otlp-grpc\"]",
+ // Metrics stay disabled so one turn is not counted through both the
+ // attributable trace and the anonymous histogram.
+ for _, duplicate := range []string{
+ "[otel.metrics_exporter.\"otlp-grpc\"]",
} {
- if strings.Contains(text, noisy) {
- t.Fatalf("codex config should not enable noisy exporter %q:\n%s", noisy, text)
+ if strings.Contains(text, duplicate) {
+ t.Fatalf("codex config should not enable duplicate usage exporter %q:\n%s", duplicate, text)
}
}
backups, err := filepath.Glob(path + ".beacon.*.bak")
diff --git a/cli/beacon/internal/endpoint/hooks/codex.go b/cli/beacon/internal/endpoint/hooks/codex.go
index bee25977..ce321457 100644
--- a/cli/beacon/internal/endpoint/hooks/codex.go
+++ b/cli/beacon/internal/endpoint/hooks/codex.go
@@ -63,7 +63,10 @@ func codexStatusFromRuntime(status runtimeStatus) CodexStatus {
func installCodexHooks(path, binaryPath, logPath, configPath string) error {
prefix := endpointCommandPrefix("codex", binaryPath, logPath, configPath)
endpointHooks := map[string]settingsHookGroup{
- "SessionStart": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " inventory-heartbeat", Timeout: 10}}},
+ "SessionStart": {Hooks: []settingsHookRef{
+ {Type: "command", Command: prefix + " inventory-heartbeat", Timeout: 10},
+ {Type: "command", Command: prefix + " codex-session-context", Timeout: 10},
+ }},
"UserPromptSubmit": {Hooks: []settingsHookRef{{Type: "command", Command: prefix + " inventory-heartbeat", Timeout: 10}}},
}
return installSettingsEndpointHooks(path, "codex", endpointHooks)
diff --git a/cli/beacon/internal/endpoint/hooks/codex_test.go b/cli/beacon/internal/endpoint/hooks/codex_test.go
index 6293181c..650db15a 100644
--- a/cli/beacon/internal/endpoint/hooks/codex_test.go
+++ b/cli/beacon/internal/endpoint/hooks/codex_test.go
@@ -7,7 +7,7 @@ import (
"testing"
)
-func TestInstallCodexHooksUsesInventoryHeartbeatOnly(t *testing.T) {
+func TestInstallCodexHooksUsesInventoryAndSessionContext(t *testing.T) {
path := filepath.Join(t.TempDir(), "hooks.json")
existing := `{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo keep"},{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform codex inventory-heartbeat"}]}],"Stop":[{"hooks":[{"type":"command","command":"BEACON_ENDPOINT_MODE=1 beacon-hooks --platform codex codex-usage-sync"}]}]}}`
if err := os.WriteFile(path, []byte(existing), 0600); err != nil {
@@ -29,6 +29,7 @@ func TestInstallCodexHooksUsesInventoryHeartbeatOnly(t *testing.T) {
"UserPromptSubmit",
"--platform codex",
"inventory-heartbeat",
+ "codex-session-context",
"--log '/tmp/runtime.jsonl'",
"--config '/tmp/config.json'",
} {
@@ -38,7 +39,7 @@ func TestInstallCodexHooksUsesInventoryHeartbeatOnly(t *testing.T) {
}
for _, forbidden := range []string{"session-start", "prompt-submit", " stop", " session-end", "codex-usage-sync"} {
if strings.Contains(text, forbidden) {
- t.Fatalf("Codex inventory hooks should not emit runtime hook events %q:\n%s", forbidden, text)
+ t.Fatalf("Codex hooks should not install duplicate generic runtime hooks %q:\n%s", forbidden, text)
}
}
if !strings.Contains(text, "SessionStart") || strings.Contains(text, `"Stop"`) {
diff --git a/cli/beacon/internal/endpoint/integrations/logscan.go b/cli/beacon/internal/endpoint/integrations/logscan.go
index ef530c05..3f985289 100644
--- a/cli/beacon/internal/endpoint/integrations/logscan.go
+++ b/cli/beacon/internal/endpoint/integrations/logscan.go
@@ -10,6 +10,55 @@ import (
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
+type CodexUsageSignals struct {
+ SessionContexts int
+ TurnSpans int
+ LegacyMetrics int
+}
+
+// ScanCodexUsageSignals summarizes which Codex attribution source has reached
+// the active runtime log. It reads metadata only; prompt and tool content are
+// never decoded.
+func ScanCodexUsageSignals(logPath string) CodexUsageSignals {
+ var signals CodexUsageSignals
+ if logPath == "" {
+ return signals
+ }
+ file, err := os.Open(logPath)
+ if err != nil {
+ return signals
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ var event struct {
+ Event struct {
+ Action string `json:"action"`
+ } `json:"event"`
+ Harness struct {
+ Name string `json:"name"`
+ } `json:"harness"`
+ Raw map[string]interface{} `json:"raw"`
+ }
+ if err := json.Unmarshal(scanner.Bytes(), &event); err != nil ||
+ asymptoteobserve.NormalizeHarnessName(event.Harness.Name) != "codex_cli" {
+ continue
+ }
+ if event.Event.Action == "session.context" {
+ signals.SessionContexts++
+ }
+ if source, _ := event.Raw["source"].(string); source == "codex_turn_span" {
+ signals.TurnSpans++
+ }
+ if metric, _ := event.Raw["metric_name"].(string); metric == "codex.turn.token_usage" {
+ signals.LegacyMetrics++
+ }
+ }
+ return signals
+}
+
func HasRecentHarnessEvent(logPath, harnessName string) bool {
_, ok := LastHarnessEvent(logPath, harnessName)
return ok
diff --git a/cli/beacon/internal/endpoint/integrations/logscan_harness_test.go b/cli/beacon/internal/endpoint/integrations/logscan_harness_test.go
index 0340107e..6311dc3a 100644
--- a/cli/beacon/internal/endpoint/integrations/logscan_harness_test.go
+++ b/cli/beacon/internal/endpoint/integrations/logscan_harness_test.go
@@ -66,3 +66,17 @@ func TestVSCodeAndCopilotCLIRemainDistinct(t *testing.T) {
t.Error("a Copilot CLI event matched VS Code, which is a different product")
}
}
+
+func TestScanCodexUsageSignalsSeparatesAttributionSources(t *testing.T) {
+ log := writeLog(t,
+ `{"event":{"action":"session.context"},"harness":{"name":"codex"},"raw":{"source":"codex_session_start_hook"}}`,
+ `{"event":{"action":"token.usage"},"harness":{"name":"codex_cli"},"raw":{"source":"codex_turn_span","turn_id":"turn-1"}}`,
+ `{"event":{"action":"token.usage"},"harness":{"name":"codex_cli"},"raw":{"metric_name":"codex.turn.token_usage"}}`,
+ `{"event":{"action":"token.usage"},"harness":{"name":"claude_code"},"raw":{"metric_name":"claude_code.token.usage"}}`,
+ )
+
+ got := ScanCodexUsageSignals(log)
+ if got.SessionContexts != 1 || got.TurnSpans != 1 || got.LegacyMetrics != 1 {
+ t.Fatalf("signals = %#v, want one of each Codex source", got)
+ }
+}
diff --git a/cli/beacon/internal/tokens/report.go b/cli/beacon/internal/tokens/report.go
index ae2fc349..c4800d07 100644
--- a/cli/beacon/internal/tokens/report.go
+++ b/cli/beacon/internal/tokens/report.go
@@ -17,6 +17,7 @@ func RenderText(w io.Writer, report Report) {
writeGroups(w, "BY MODEL", report.ByModel)
writeGroups(w, "BY SESSION", report.BySession)
+ writeGroups(w, "BY USER", report.ByUser)
writeGroups(w, "BY HARNESS", report.ByHarness)
writeGroups(w, "BY REPOSITORY", report.ByRepository)
writeGroups(w, "BY RUN", report.ByRun)
diff --git a/cli/beacon/internal/tokens/tokens.go b/cli/beacon/internal/tokens/tokens.go
index 00785497..faa285f3 100644
--- a/cli/beacon/internal/tokens/tokens.go
+++ b/cli/beacon/internal/tokens/tokens.go
@@ -101,6 +101,7 @@ type Report struct {
Totals Usage `json:"totals"`
ByModel []Group `json:"by_model,omitempty"`
BySession []Group `json:"by_session,omitempty"`
+ ByUser []Group `json:"by_user,omitempty"`
ByHarness []Group `json:"by_harness,omitempty"`
ByRepository []Group `json:"by_repository,omitempty"`
ByRun []Group `json:"by_run,omitempty"`
@@ -118,8 +119,10 @@ type usageEvent struct {
order int
action string
name string
+ endpoint string
harness string
session string
+ user string
model string
repository string
run string
@@ -129,6 +132,7 @@ type usageEvent struct {
usage Usage
cumulative bool
metricName string
+ rawSource string
seriesField string
seriesValue float64
}
@@ -149,12 +153,14 @@ func Aggregate(events []schema.Event, opts Options) Report {
opts.NearLimitRatio = defaultNearLimitRatio
}
report := Report{TotalEvents: len(events)}
- usageEvents := collectUsageEvents(events)
+ usageEvents := collectUsageEvents(events, sessionUserContexts(events))
+ usageEvents = preferCodexTurnSpans(usageEvents)
usageEvents = dedupeOverlappingChannels(usageEvents)
resolveCumulativeSeries(usageEvents)
byModel := map[string]*Usage{}
bySession := map[string]*Usage{}
+ byUser := map[string]*Usage{}
byHarness := map[string]*Usage{}
byRepository := map[string]*Usage{}
byRun := map[string]*Usage{}
@@ -163,6 +169,7 @@ func Aggregate(events []schema.Event, opts Options) Report {
report.Totals.add(ue.usage)
addGroup(byModel, ue.model, ue.usage)
addGroup(bySession, ue.session, ue.usage)
+ addGroup(byUser, ue.user, ue.usage)
addGroup(byHarness, ue.harness, ue.usage)
addGroup(byRepository, ue.repository, ue.usage)
addGroup(byRun, ue.run, ue.usage)
@@ -177,6 +184,7 @@ func Aggregate(events []schema.Event, opts Options) Report {
report.EventsWithUsage = len(usageEvents)
report.ByModel = sortedGroups(byModel, opts.TopLimit)
report.BySession = sortedGroups(bySession, opts.TopLimit)
+ report.ByUser = sortedGroups(byUser, opts.TopLimit)
report.ByHarness = sortedGroups(byHarness, opts.TopLimit)
report.ByRepository = sortedGroups(byRepository, opts.TopLimit)
report.ByRun = sortedGroups(byRun, opts.TopLimit)
@@ -219,7 +227,110 @@ func AggregateScoped(events []schema.Event, runID string, opts Options) Report {
return Aggregate(filtered, opts)
}
-func collectUsageEvents(events []schema.Event) []*usageEvent {
+type sessionContextKey struct {
+ endpoint string
+ harness string
+ session string
+}
+
+type endpointContextKey struct {
+ endpoint string
+ harness string
+}
+
+type endpointUserNameKey struct {
+ endpoint string
+ harness string
+ name string
+}
+
+type sessionUserIndex struct {
+ bySession map[sessionContextKey]string
+ byEndpoint map[endpointContextKey]string
+ byEndpointName map[endpointUserNameKey]string
+}
+
+func sessionUserContexts(events []schema.Event) sessionUserIndex {
+ contexts := sessionUserIndex{
+ bySession: map[sessionContextKey]string{},
+ byEndpoint: map[endpointContextKey]string{},
+ byEndpointName: map[endpointUserNameKey]string{},
+ }
+ ambiguousEndpoints := map[endpointContextKey]bool{}
+ ambiguousNames := map[endpointUserNameKey]bool{}
+ for _, event := range events {
+ if event.Session == nil || strings.TrimSpace(event.Session.ID) == "" {
+ continue
+ }
+ user := userKey(event.User)
+ if user == "" {
+ continue
+ }
+ key := sessionKey(event)
+ if event.Event.Action == "session.context" || contexts.bySession[key] == "" {
+ contexts.bySession[key] = user
+ }
+ if event.Event.Action != "session.context" {
+ continue
+ }
+ endpointKey := endpointKey(event)
+ if current := contexts.byEndpoint[endpointKey]; current == "" {
+ if !ambiguousEndpoints[endpointKey] {
+ contexts.byEndpoint[endpointKey] = user
+ }
+ } else if current != user {
+ delete(contexts.byEndpoint, endpointKey)
+ ambiguousEndpoints[endpointKey] = true
+ }
+ if name := strings.ToLower(strings.TrimSpace(event.User.Name)); name != "" {
+ nameKey := endpointUserNameKey{endpoint: endpointKey.endpoint, harness: endpointKey.harness, name: name}
+ if current := contexts.byEndpointName[nameKey]; current == "" {
+ if !ambiguousNames[nameKey] {
+ contexts.byEndpointName[nameKey] = user
+ }
+ } else if current != user {
+ delete(contexts.byEndpointName, nameKey)
+ ambiguousNames[nameKey] = true
+ }
+ }
+ }
+ return contexts
+}
+
+func endpointKey(event schema.Event) endpointContextKey {
+ return endpointContextKey{
+ endpoint: strings.ToLower(strings.TrimSpace(event.Endpoint.Hostname)),
+ harness: strings.ToLower(strings.TrimSpace(event.Harness.Name)),
+ }
+}
+
+func sessionKey(event schema.Event) sessionContextKey {
+ session := ""
+ if event.Session != nil {
+ session = event.Session.ID
+ }
+ endpoint := endpointKey(event)
+ return sessionContextKey{
+ endpoint: endpoint.endpoint,
+ harness: endpoint.harness,
+ session: strings.ToLower(strings.TrimSpace(session)),
+ }
+}
+
+func userKey(user schema.UserInfo) string {
+ name := strings.TrimSpace(user.Name)
+ uid := strings.TrimSpace(user.UID)
+ switch {
+ case name != "" && uid != "":
+ return name + " [" + uid + "]"
+ case uid != "":
+ return uid
+ default:
+ return name
+ }
+}
+
+func collectUsageEvents(events []schema.Event, sessionUsers sessionUserIndex) []*usageEvent {
var out []*usageEvent
for i, event := range events {
if event.GenAI == nil || event.GenAI.Usage == nil {
@@ -230,7 +341,9 @@ func collectUsageEvents(events []schema.Event) []*usageEvent {
order: i,
action: event.Event.Action,
name: event.Message,
+ endpoint: event.Endpoint.Hostname,
harness: event.Harness.Name,
+ user: userKey(event.User),
model: event.Model,
repository: event.Repository,
usage: Usage{Events: 1},
@@ -240,6 +353,22 @@ func collectUsageEvents(events []schema.Event) []*usageEvent {
}
if event.Session != nil {
ue.session = event.Session.ID
+ if contextualUser := sessionUsers.bySession[sessionKey(event)]; contextualUser != "" {
+ ue.user = contextualUser
+ }
+ }
+ if ue.user == userKey(event.User) {
+ endpoint := endpointKey(event)
+ nameKey := endpointUserNameKey{
+ endpoint: endpoint.endpoint,
+ harness: endpoint.harness,
+ name: strings.ToLower(strings.TrimSpace(event.User.Name)),
+ }
+ if namedUser := sessionUsers.byEndpointName[nameKey]; namedUser != "" {
+ ue.user = namedUser
+ } else if endpointUser := sessionUsers.byEndpoint[endpoint]; endpointUser != "" {
+ ue.user = endpointUser
+ }
}
if event.Run != nil {
ue.run = RunKey(event.Run.Provider, event.Run.RunID)
@@ -275,12 +404,57 @@ func collectUsageEvents(events []schema.Event) []*usageEvent {
ue.cumulative = true
}
ue.metricName, _ = event.Raw["metric_name"].(string)
+ ue.rawSource, _ = event.Raw["source"].(string)
}
out = append(out, ue)
}
return out
}
+// preferCodexTurnSpans makes the attributable turn trace authoritative from
+// the first time it appears for an endpoint/model. Legacy aggregate metrics
+// before that cutover remain reportable, while a manually configured
+// trace+metric overlap after it cannot double-count the same turns.
+func preferCodexTurnSpans(events []*usageEvent) []*usageEvent {
+ type sourceKey struct {
+ endpoint string
+ harness string
+ model string
+ }
+ keyFor := func(event *usageEvent) sourceKey {
+ return sourceKey{
+ endpoint: strings.ToLower(strings.TrimSpace(event.endpoint)),
+ harness: strings.ToLower(strings.TrimSpace(event.harness)),
+ model: strings.ToLower(strings.TrimSpace(event.model)),
+ }
+ }
+ cutovers := map[sourceKey]time.Time{}
+ for _, event := range events {
+ if !strings.EqualFold(event.rawSource, "codex_turn_span") || event.ts.IsZero() {
+ continue
+ }
+ key := keyFor(event)
+ if current, ok := cutovers[key]; !ok || event.ts.Before(current) {
+ cutovers[key] = event.ts
+ }
+ }
+ if len(cutovers) == 0 {
+ return events
+ }
+ out := events[:0]
+ for _, event := range events {
+ cutover, ok := cutovers[keyFor(event)]
+ if ok &&
+ strings.EqualFold(event.metricName, "codex.turn.token_usage") &&
+ !event.ts.IsZero() &&
+ !event.ts.Before(cutover) {
+ continue
+ }
+ out = append(out, event)
+ }
+ return out
+}
+
// dedupeOverlappingChannels removes double-counted usage when a runtime reports
// the same tokens through two OTel channels. Claude Code emits each request's
// usage on both a claude_code.api_request log record and the
diff --git a/cli/beacon/internal/tokens/tokens_test.go b/cli/beacon/internal/tokens/tokens_test.go
index 61ed63af..364f99cf 100644
--- a/cli/beacon/internal/tokens/tokens_test.go
+++ b/cli/beacon/internal/tokens/tokens_test.go
@@ -73,6 +73,78 @@ func TestAggregateSumsDeltaUsageAcrossGroups(t *testing.T) {
}
}
+func TestAggregateAttributesUsageToSessionUserContext(t *testing.T) {
+ contextEvent := func(host, user, uid string) schema.Event {
+ return schema.Event{
+ Timestamp: "2026-06-11T09:59:00Z",
+ Event: schema.EventInfo{Kind: "agent_runtime", Action: "session.context", Category: "session"},
+ Endpoint: schema.EndpointInfo{Hostname: host, OS: "darwin"},
+ User: schema.UserInfo{Name: user, UID: uid},
+ Harness: schema.HarnessInfo{Name: "codex_cli"},
+ Session: &schema.SessionInfo{ID: "shared-session"},
+ }
+ }
+ usageEvent := func(host string, input int64) schema.Event {
+ return usageEventFixture("2026-06-11T10:00:00Z", "codex_cli", "shared-session", "gpt-5.6-sol", func(e *schema.Event) {
+ e.Endpoint = schema.EndpointInfo{Hostname: host, OS: "darwin"}
+ e.User = schema.UserInfo{Name: "root", UID: "0"}
+ e.GenAI.Usage.InputTokens = int64Ptr(input)
+ })
+ }
+
+ report := Aggregate([]schema.Event{
+ contextEvent("host-a", "alice", "501"),
+ usageEvent("host-a", 10),
+ contextEvent("host-b", "bob", "502"),
+ usageEvent("host-b", 20),
+ }, Options{})
+
+ if len(report.ByUser) != 2 {
+ t.Fatalf("by_user = %#v, want two endpoint-scoped users", report.ByUser)
+ }
+ users := map[string]Usage{}
+ for _, group := range report.ByUser {
+ users[group.Key] = group.Usage
+ }
+ if users["alice [501]"].InputTokens != 10 || users["bob [502]"].InputTokens != 20 {
+ t.Fatalf("by_user = %#v, want session context to override collector identity", users)
+ }
+}
+
+func TestAggregateAttributesAuxiliaryCodexSessionToUniqueEndpointUser(t *testing.T) {
+ contextEvent := schema.Event{
+ Timestamp: "2026-06-11T09:59:00Z",
+ Event: schema.EventInfo{Kind: "agent_runtime", Action: "session.context", Category: "session"},
+ Endpoint: schema.EndpointInfo{Hostname: "host-a", OS: "darwin"},
+ User: schema.UserInfo{Name: "shukan", UID: "501"},
+ Harness: schema.HarnessInfo{Name: "codex_cli"},
+ Session: &schema.SessionInfo{ID: "main-session"},
+ }
+ auxiliaryStarted := schema.Event{
+ Timestamp: "2026-06-11T10:00:00Z",
+ Event: schema.EventInfo{Kind: "agent_runtime", Action: "session.started", Category: "session"},
+ Endpoint: schema.EndpointInfo{Hostname: "host-a", OS: "darwin"},
+ User: schema.UserInfo{Name: "shukan"},
+ Harness: schema.HarnessInfo{Name: "codex_cli"},
+ Session: &schema.SessionInfo{ID: "title-session"},
+ }
+ mainUsage := usageEventFixture("2026-06-11T10:00:05Z", "codex_cli", "main-session", "gpt-5.6-sol", func(e *schema.Event) {
+ e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
+ e.User = schema.UserInfo{Name: "shukan"}
+ e.GenAI.Usage.InputTokens = int64Ptr(10)
+ })
+ auxiliaryUsage := usageEventFixture("2026-06-11T10:00:06Z", "codex_cli", "title-session", "gpt-5.6-sol", func(e *schema.Event) {
+ e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
+ e.User = schema.UserInfo{Name: "shukan"}
+ e.GenAI.Usage.InputTokens = int64Ptr(20)
+ })
+
+ report := Aggregate([]schema.Event{contextEvent, auxiliaryStarted, mainUsage, auxiliaryUsage}, Options{})
+ if len(report.ByUser) != 1 || report.ByUser[0].Key != "shukan [501]" || report.ByUser[0].Usage.InputTokens != 30 {
+ t.Fatalf("by_user = %#v, want both Codex sessions attributed to the unique endpoint user", report.ByUser)
+ }
+}
+
func TestAggregateDedupesDualChannelUsage(t *testing.T) {
// Claude Code reports each request's usage on both a claude_code.api_request
// log record (no metric_name) and the claude_code.token.usage metric, under
@@ -132,6 +204,40 @@ func TestAggregateDedupesDualChannelUsage(t *testing.T) {
}
}
+func TestAggregatePrefersCodexTurnSpansAfterCutover(t *testing.T) {
+ codexMetric := func(ts string, input int64) schema.Event {
+ return usageEventFixture(ts, "codex_cli", "", "gpt-5.6-sol", func(e *schema.Event) {
+ e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
+ e.GenAI.Usage.InputTokens = int64Ptr(input)
+ e.Raw = map[string]interface{}{
+ "metric_name": "codex.turn.token_usage",
+ "metric_temporality": "Delta",
+ }
+ })
+ }
+ turnSpan := usageEventFixture("2026-06-11T10:00:00Z", "codex_cli", "session-1", "gpt-5.6-sol", func(e *schema.Event) {
+ e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
+ e.GenAI.Usage.InputTokens = int64Ptr(20)
+ e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_id": "turn-1"}
+ })
+ events := []schema.Event{
+ // A pre-upgrade metric remains part of historical totals.
+ codexMetric("2026-06-11T09:00:00Z", 10),
+ turnSpan,
+ // The same live turn also flushed through a manually retained metric
+ // exporter; the turn span wins after cutover.
+ codexMetric("2026-06-11T10:00:05Z", 20),
+ }
+
+ report := Aggregate(events, Options{})
+ if report.Totals.InputTokens != 30 || report.Totals.Events != 2 {
+ t.Fatalf("totals = %#v, want legacy metric plus turn span only", report.Totals)
+ }
+ if len(report.BySession) != 1 || report.BySession[0].Key != "session-1" {
+ t.Fatalf("by_session = %#v, want attributable turn span", report.BySession)
+ }
+}
+
func TestAggregateDedupesCumulativeSeries(t *testing.T) {
cumulative := func(ts string, value int64) schema.Event {
return usageEventFixture(ts, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
diff --git a/collector-builder/exporter/beaconjsonexporter/README.md b/collector-builder/exporter/beaconjsonexporter/README.md
index 2913cd0d..7ae3c958 100644
--- a/collector-builder/exporter/beaconjsonexporter/README.md
+++ b/collector-builder/exporter/beaconjsonexporter/README.md
@@ -27,7 +27,7 @@ Required behavior:
- Redact common secrets and cap event size before writing.
- Emit health failure events when write failures occur.
-Token and cost usage metrics:
+Token and cost usage:
- Metrics named `gen_ai.client.token.usage` or ending in `.token.usage` or
`.cost.usage` (for example `claude_code.token.usage` and
@@ -44,14 +44,18 @@ Token and cost usage metrics:
cumulative series.
- All other metrics, and usage metrics without datapoints, keep the single
`metric.observed` event.
+- Codex's current live token source is the completed `session_task.turn` trace,
+ not its anonymous histogram. The exporter keeps that one span by default,
+ promotes `thread.id`/`turn.id`/model, and maps cache reads and cache writes to
+ disjoint canonical usage fields. Legacy Codex metric events remain readable.
Noise controls:
- Generic process/runtime metrics are dropped by default unless
`include_runtime_metrics: true` is set.
-- Codex spans are dropped by default because Codex semantic logs carry the
- endpoint activity Beacon needs. Set `include_codex_spans: true` only when
- troubleshooting Codex OTLP internals.
+- Codex spans are dropped by default except for a completed turn span carrying
+ `codex.turn.token_usage.*`. Set `include_codex_spans: true` only when
+ troubleshooting all Codex OTLP internals.
- Codex metrics and transport/startup/debug logs remain suppressed by default so
one prompt does not flood the endpoint runtime log.
- Copilot CLI metrics are suppressed by default, including
diff --git a/collector-builder/exporter/beaconjsonexporter/exporter_test.go b/collector-builder/exporter/beaconjsonexporter/exporter_test.go
index 52a54aba..ff6f0095 100644
--- a/collector-builder/exporter/beaconjsonexporter/exporter_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/exporter_test.go
@@ -1532,7 +1532,12 @@ func TestCodexInternalSpanFilter(t *testing.T) {
t.Fatal("expected Codex transport span to be dropped")
}
if !exp.shouldDropSpan(codexAttrs, testSpan("session_task.turn")) {
- t.Fatal("expected Codex session_task span to be dropped")
+ t.Fatal("expected Codex turn span without usage to be dropped")
+ }
+ usageSpan := testSpan("session_task.turn")
+ usageSpan.Attributes().PutInt("codex.turn.token_usage.input_tokens", 10)
+ if exp.shouldDropSpan(codexAttrs, usageSpan) {
+ t.Fatal("expected Codex turn span with usage to be kept")
}
if !exp.shouldDropSpan(codexAttrs, testSpan("op.dispatch.user_input_with_turn_context")) {
t.Fatal("expected Codex user input span to be dropped")
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
index a327e7c1..df36fda0 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
@@ -335,13 +335,18 @@ func (c Converter) EventFromLog(resourceAttrs map[string]interface{}, record plo
func (c Converter) EventFromSpan(resourceAttrs map[string]interface{}, span ptrace.Span) Event {
attrs := MergeMaps(resourceAttrs, AttrsToMap(span.Attributes()))
+ codexTurnUsage := IsCodexTurnUsageSpan(attrs, span.Name())
action := FirstString(attrs, "beacon.event.action", "event.action", "gen_ai.agent.action", "ai.agent.action")
fidelity := asymptoteobserve.FidelityObserved
if action == "" {
action, fidelity = InferActionWithFidelity(attrs, span.Name())
}
message := FirstNonEmpty(FirstString(attrs, "message", "gen_ai.prompt", "gen_ai.response"), span.Name())
- event := NewEvent(action, EventCategory(action, FirstString(attrs, "beacon.event.category", "event.category", "tool")), SpanSeverity(span.Status().Code().String()), HarnessName(attrs, message, span.Name()), Timestamp(span.StartTimestamp().AsTime()))
+ eventTime := span.StartTimestamp().AsTime()
+ if codexTurnUsage && span.EndTimestamp() != 0 {
+ eventTime = span.EndTimestamp().AsTime()
+ }
+ event := NewEvent(action, EventCategory(action, FirstString(attrs, "beacon.event.category", "event.category", "tool")), SpanSeverity(span.Status().Code().String()), HarnessName(attrs, message, span.Name()), Timestamp(eventTime))
event.Event.Fidelity = fidelity
event.Message = message
c.PopulateCommon(&event, attrs)
@@ -354,12 +359,18 @@ func (c Converter) EventFromSpan(resourceAttrs map[string]interface{}, span ptra
event.Trace.ParentSpanID = span.ParentSpanID().String()
}
}
- event.Raw = c.RawPayload(attrs, map[string]interface{}{
+ rawExtra := map[string]interface{}{
"otel_signal": "traces",
"span_name": span.Name(),
"span_kind": span.Kind().String(),
"status": span.Status().Code().String(),
- })
+ }
+ if codexTurnUsage {
+ rawExtra["source"] = "codex_turn_span"
+ rawExtra["turn_id"] = FirstString(attrs, "turn.id", "turn_id")
+ NormalizeCodexTurnUsageSpan(&event, attrs)
+ }
+ event.Raw = c.RawPayload(attrs, rawExtra)
c.PromoteRetainedContent(&event, attrs, span.Name())
return event
}
@@ -368,7 +379,7 @@ func (c Converter) ShouldDropSpan(resourceAttrs map[string]interface{}, span ptr
attrs := MergeMaps(resourceAttrs, AttrsToMap(span.Attributes()))
switch HarnessName(attrs, span.Name()) {
case "codex_cli":
- return !c.opts.IncludeCodexSpans
+ return !c.opts.IncludeCodexSpans && !IsCodexTurnUsageSpan(attrs, span.Name())
case "vscode_copilot":
return shouldDropVSCodeCopilotSpan(attrs, span.Name(), c.opts.IncludeRuntimeMetrics)
default:
@@ -376,6 +387,107 @@ func (c Converter) ShouldDropSpan(resourceAttrs map[string]interface{}, span ptr
}
}
+// IsCodexTurnUsageSpan identifies the single completed-turn span that carries
+// Codex's session-attributable token totals. The span name alone is not enough:
+// unfinished turns and some older builds can emit the same span with no usage.
+func IsCodexTurnUsageSpan(attrs map[string]interface{}, spanName string) bool {
+ if HarnessName(attrs, spanName) != "codex_cli" {
+ return false
+ }
+ for _, key := range []string{
+ "codex.turn.token_usage.input_tokens",
+ "codex.turn.token_usage.cached_input_tokens",
+ "codex.turn.token_usage.cache_write_input_tokens",
+ "codex.turn.token_usage.output_tokens",
+ "codex.turn.token_usage.reasoning_output_tokens",
+ "codex.turn.token_usage.total_tokens",
+ } {
+ if HasAttr(attrs, key) {
+ return true
+ }
+ }
+ return false
+}
+
+// NormalizeCodexTurnUsageSpan maps Codex's completed-turn trace attributes to
+// Beacon's canonical, disjoint gen_ai.usage representation.
+func NormalizeCodexTurnUsageSpan(event *Event, attrs map[string]interface{}) {
+ if event == nil {
+ return
+ }
+ event.Event.Action = "token.usage"
+ event.Event.Category = "metric"
+ event.Event.Fidelity = asymptoteobserve.FidelityObserved
+ event.Message = "codex.turn.token_usage"
+
+ sessionID := FirstString(attrs, "thread.id", "thread_id")
+ if sessionID != "" {
+ workingDirectory := ""
+ if event.Session != nil {
+ workingDirectory = event.Session.WorkingDirectory
+ }
+ event.Session = &SessionInfo{ID: sessionID, WorkingDirectory: workingDirectory}
+ if event.GenAI == nil {
+ event.GenAI = &GenAIInfo{}
+ }
+ event.GenAI.Conversation = &GenAIConversationInfo{ID: sessionID}
+ }
+ if event.GenAI == nil {
+ event.GenAI = &GenAIInfo{}
+ }
+ usage := &GenAIUsageInfo{}
+ hasUsage := false
+
+ inputTotal, hasInput := Int64Attr(attrs, "codex.turn.token_usage.input_tokens")
+ cached, hasCached := Int64Attr(attrs, "codex.turn.token_usage.cached_input_tokens")
+ cacheWrite, hasCacheWrite := Int64Attr(attrs, "codex.turn.token_usage.cache_write_input_tokens")
+ if !hasInput {
+ if nonCached, ok := Int64Attr(attrs, "codex.turn.token_usage.non_cached_input_tokens"); ok {
+ inputTotal = nonCached + cached
+ hasInput = true
+ }
+ }
+ if hasInput || hasCached || hasCacheWrite {
+ uncached := inputTotal - cached - cacheWrite
+ if uncached < 0 {
+ uncached = 0
+ }
+ usage.InputTokens = &uncached
+ hasUsage = true
+ }
+ if hasCached {
+ if cached < 0 {
+ cached = 0
+ }
+ usage.CacheRead = &GenAIUsageCacheReadInfo{InputTokens: &cached}
+ hasUsage = true
+ }
+ if hasCacheWrite {
+ if cacheWrite < 0 {
+ cacheWrite = 0
+ }
+ usage.CacheCreation = &GenAIUsageCacheCreationInfo{InputTokens: &cacheWrite}
+ hasUsage = true
+ }
+ if output, ok := Int64Attr(attrs, "codex.turn.token_usage.output_tokens"); ok {
+ if output < 0 {
+ output = 0
+ }
+ usage.OutputTokens = &output
+ hasUsage = true
+ }
+ if reasoning, ok := Int64Attr(attrs, "codex.turn.token_usage.reasoning_output_tokens"); ok {
+ if reasoning < 0 {
+ reasoning = 0
+ }
+ usage.Reasoning = &GenAIUsageReasoningInfo{OutputTokens: &reasoning}
+ hasUsage = true
+ }
+ if hasUsage {
+ event.GenAI.Usage = usage
+ }
+}
+
func (c Converter) NormalizeCodexLogEvent(event *Event, attrs map[string]interface{}) {
if event == nil || event.Harness.Name != "codex_cli" {
return
@@ -715,18 +827,19 @@ func (c Converter) EventsFromMetric(resourceAttrs map[string]interface{}, metric
func (c Converter) eventsFromUsageMetric(resourceAttrs map[string]interface{}, metric pmetric.Metric) []Event {
var events []Event
- // Codex reports input tokens inclusive of the cached_input subset (input =
- // uncached + cached, and total = input + output). Beacon's gen_ai.usage keeps
- // input_tokens and cache_read disjoint like Claude Code, so reduce input by
- // the per-turn cached_input before normalizing; otherwise totals double-count
- // cached prompt tokens. Returns nil (no-op) for every other usage metric.
- cachedInputByTurn := codexCachedInputByTimestamp(metric)
+ // Codex reports input tokens inclusive of both cached_input and
+ // cache_write_input. Beacon's gen_ai.usage keeps uncached input, cache read,
+ // and cache creation disjoint, so reduce input by both per-turn subsets;
+ // otherwise totals double-count cached prompt tokens. Returns nil (no-op)
+ // for every other usage metric.
+ inputSubsetsByTurn := codexInputSubsetsByTimestamp(metric)
adjustValue := func(dpAttrs pcommon.Map, ts pcommon.Timestamp, value float64) float64 {
- if cachedInputByTurn == nil {
+ if inputSubsetsByTurn == nil {
return value
}
if tt := FirstString(AttrsToMap(dpAttrs), "token_type"); strings.EqualFold(tt, "input") {
- if value -= cachedInputByTurn[ts.AsTime().UnixNano()]; value < 0 {
+ subsets := inputSubsetsByTurn[ts.AsTime().UnixNano()]
+ if value -= subsets.cached + subsets.cacheWrite; value < 0 {
value = 0
}
}
@@ -769,28 +882,39 @@ func (c Converter) eventsFromUsageMetric(resourceAttrs map[string]interface{}, m
return events
}
-// codexCachedInputByTimestamp sums each turn's cached_input datapoints from the
-// codex.turn.token_usage histogram, keyed by datapoint timestamp, so the input
-// datapoint can be reduced to its uncached portion (Codex's input is inclusive
-// of cached_input). Returns nil for any other metric so the generic usage path
-// is unaffected.
-func codexCachedInputByTimestamp(metric pmetric.Metric) map[int64]float64 {
+type codexInputSubsets struct {
+ cached float64
+ cacheWrite float64
+}
+
+// codexInputSubsetsByTimestamp collects each turn's cached and cache-write
+// datapoints so Codex's inclusive input count can be reduced to the canonical
+// uncached remainder. Returns nil for every other metric.
+func codexInputSubsetsByTimestamp(metric pmetric.Metric) map[int64]codexInputSubsets {
if !strings.EqualFold(strings.TrimSpace(metric.Name()), "codex.turn.token_usage") {
return nil
}
if metric.Type() != pmetric.MetricTypeHistogram {
return nil
}
- out := map[int64]float64{}
+ out := map[int64]codexInputSubsets{}
dps := metric.Histogram().DataPoints()
for i := 0; i < dps.Len(); i++ {
dp := dps.At(i)
if !dp.HasSum() {
continue
}
- if tt := FirstString(AttrsToMap(dp.Attributes()), "token_type"); strings.EqualFold(tt, "cached_input") {
- out[dp.Timestamp().AsTime().UnixNano()] += dp.Sum()
+ key := dp.Timestamp().AsTime().UnixNano()
+ subsets := out[key]
+ switch strings.ToLower(FirstString(AttrsToMap(dp.Attributes()), "token_type")) {
+ case "cached_input":
+ subsets.cached += dp.Sum()
+ case "cache_write_input":
+ subsets.cacheWrite += dp.Sum()
+ default:
+ continue
}
+ out[key] = subsets
}
return out
}
@@ -868,7 +992,7 @@ func ApplyTokenUsage(event *Event, tokenType string, value int64) {
usage.OutputTokens = &value
case "cacheread", "cachedinput":
usage.CacheRead = &GenAIUsageCacheReadInfo{InputTokens: &value}
- case "cachecreation":
+ case "cachecreation", "cachewrite", "cachewriteinput":
usage.CacheCreation = &GenAIUsageCacheCreationInfo{InputTokens: &value}
case "reasoning", "reasoningoutput":
usage.Reasoning = &GenAIUsageReasoningInfo{OutputTokens: &value}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
index 25842ee5..23426169 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
@@ -188,6 +188,68 @@ func TestEventFromSpanNormalizesClaudeCodeLLMRequestUsage(t *testing.T) {
}
}
+func TestEventsFromTracesKeepsAndNormalizesCodexTurnUsage(t *testing.T) {
+ traces := ptrace.NewTraces()
+ rs := traces.ResourceSpans().AppendEmpty()
+ rs.Resource().Attributes().PutStr("service.name", "codex_exec")
+ spans := rs.ScopeSpans().AppendEmpty().Spans()
+
+ internal := spans.AppendEmpty()
+ internal.SetName("handle_responses")
+
+ turn := spans.AppendEmpty()
+ turn.SetName("session_task.turn")
+ turn.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Unix(1700000000, 0).UTC()))
+ turn.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Unix(1700000005, 0).UTC()))
+ turn.Attributes().PutStr("thread.id", "codex-session")
+ turn.Attributes().PutStr("turn.id", "codex-turn")
+ turn.Attributes().PutStr("model", "gpt-5.6-sol")
+ turn.Attributes().PutInt("codex.turn.token_usage.input_tokens", 13347)
+ turn.Attributes().PutInt("codex.turn.token_usage.cached_input_tokens", 0)
+ turn.Attributes().PutInt("codex.turn.token_usage.cache_write_input_tokens", 13344)
+ turn.Attributes().PutInt("codex.turn.token_usage.non_cached_input_tokens", 13347)
+ turn.Attributes().PutInt("codex.turn.token_usage.output_tokens", 6)
+ turn.Attributes().PutInt("codex.turn.token_usage.reasoning_output_tokens", 2)
+ turn.Attributes().PutInt("codex.turn.token_usage.total_tokens", 13353)
+
+ events := NewConverter(Options{}).EventsFromTraces(traces)
+ if len(events) != 1 {
+ t.Fatalf("events = %d, want only the usage-bearing turn span", len(events))
+ }
+ event := events[0]
+ if event.Event.Action != "token.usage" || event.Event.Category != "metric" || event.Event.Fidelity != asymptoteobserve.FidelityObserved {
+ t.Fatalf("event = %#v, want observed token.usage metric", event.Event)
+ }
+ if event.Session == nil || event.Session.ID != "codex-session" {
+ t.Fatalf("session = %#v, want codex-session", event.Session)
+ }
+ if event.Model != "gpt-5.6-sol" {
+ t.Fatalf("model = %q, want gpt-5.6-sol", event.Model)
+ }
+ if event.Timestamp != "2023-11-14T22:13:25.000000000Z" {
+ t.Fatalf("timestamp = %q, want turn completion time", event.Timestamp)
+ }
+ usage := event.GenAI.Usage
+ if usage == nil || usage.InputTokens == nil || *usage.InputTokens != 3 {
+ t.Fatalf("input usage = %#v, want 3 uncached tokens", usage)
+ }
+ if usage.CacheRead == nil || usage.CacheRead.InputTokens == nil || *usage.CacheRead.InputTokens != 0 {
+ t.Fatalf("cache read = %#v, want explicit zero", usage.CacheRead)
+ }
+ if usage.CacheCreation == nil || usage.CacheCreation.InputTokens == nil || *usage.CacheCreation.InputTokens != 13344 {
+ t.Fatalf("cache creation = %#v, want 13344", usage.CacheCreation)
+ }
+ if usage.OutputTokens == nil || *usage.OutputTokens != 6 {
+ t.Fatalf("output usage = %#v, want 6", usage)
+ }
+ if usage.Reasoning == nil || usage.Reasoning.OutputTokens == nil || *usage.Reasoning.OutputTokens != 2 {
+ t.Fatalf("reasoning usage = %#v, want 2", usage)
+ }
+ if event.Raw["source"] != "codex_turn_span" || event.Raw["turn_id"] != "codex-turn" {
+ t.Fatalf("raw source metadata = %#v", event.Raw)
+ }
+}
+
func TestEventFromSpanCapturesTraceIdentity(t *testing.T) {
span, traces := newObserveSDKTraceSpan("agent.step")
span.SetTraceID(pcommon.TraceID([16]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}))
@@ -444,15 +506,16 @@ func TestEventsFromMetricsNormalizesCodexTurnTokenUsage(t *testing.T) {
metric.SetName("codex.turn.token_usage")
histogram := metric.SetEmptyHistogram()
histogram.SetAggregationTemporality(pmetric.AggregationTemporalityDelta)
- // Codex's input (120) is inclusive of cached_input (90), and total = input +
- // output. The normalized input_tokens must drop to the uncached portion (30)
- // so input_tokens + cache_read == input and totals don't double-count cache.
+ // Codex's input (120) is inclusive of cached_input (90) and
+ // cache_write_input (10). The normalized input_tokens must drop to the
+ // uncached portion (20) so the canonical fields remain disjoint.
tokenTypes := map[string]float64{
- "input": 120,
- "cached_input": 90,
- "output": 45,
- "reasoning_output": 30,
- "total": 165,
+ "input": 120,
+ "cached_input": 90,
+ "cache_write_input": 10,
+ "output": 45,
+ "reasoning_output": 30,
+ "total": 165,
}
for tokenType, value := range tokenTypes {
dp := histogram.DataPoints().AppendEmpty()
@@ -466,7 +529,7 @@ func TestEventsFromMetricsNormalizesCodexTurnTokenUsage(t *testing.T) {
if len(events) != len(tokenTypes) {
t.Fatalf("expected %d events (one per token_type), got %d", len(tokenTypes), len(events))
}
- var input, cacheRead, output, reasoning int64
+ var input, cacheRead, cacheCreation, output, reasoning int64
for _, event := range events {
if event.Event.Action != "token.usage" || event.Harness.Name != "codex_cli" {
t.Fatalf("event = %#v, want codex token.usage", event.Event)
@@ -484,15 +547,18 @@ func TestEventsFromMetricsNormalizesCodexTurnTokenUsage(t *testing.T) {
if usage.CacheRead != nil && usage.CacheRead.InputTokens != nil {
cacheRead += *usage.CacheRead.InputTokens
}
+ if usage.CacheCreation != nil && usage.CacheCreation.InputTokens != nil {
+ cacheCreation += *usage.CacheCreation.InputTokens
+ }
if usage.Reasoning != nil && usage.Reasoning.OutputTokens != nil {
reasoning += *usage.Reasoning.OutputTokens
}
}
- if input != 30 || cacheRead != 90 || output != 45 || reasoning != 30 {
- t.Fatalf("normalized usage = input %d, cache_read %d, output %d, reasoning %d (want 30/90/45/30)", input, cacheRead, output, reasoning)
+ if input != 20 || cacheRead != 90 || cacheCreation != 10 || output != 45 || reasoning != 30 {
+ t.Fatalf("normalized usage = input %d, cache_read %d, cache_creation %d, output %d, reasoning %d (want 20/90/10/45/30)", input, cacheRead, cacheCreation, output, reasoning)
}
- if input+cacheRead != 120 {
- t.Fatalf("input_tokens + cache_read = %d, want 120 (= Codex input, no double-count)", input+cacheRead)
+ if input+cacheRead+cacheCreation != 120 {
+ t.Fatalf("input + cache_read + cache_creation = %d, want 120 (= Codex input, no double-count)", input+cacheRead+cacheCreation)
}
}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index a3e8f284..b82a3c8f 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -11,6 +11,22 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
## August 2026
+### Codex token attribution · August 27, 2026
+
+- **Turn-level usage** · Beacon now configures Codex's local trace exporter and
+ retains only the completed turn span carrying thread, turn, model, and token
+ fields. The same canonical `gen_ai.usage` schema used by Claude Code records
+ uncached input, cache read, cache creation, output, and reasoning tokens.
+- **User and session rollups** · A metadata-only SessionStart hook records the
+ local OS user for each Codex session. The token report and dashboard join that
+ context by session ID and add a per-user breakdown.
+- **One live source** · Beacon-managed Codex configuration no longer enables the
+ anonymous token histogram alongside traces. Historical metric rows remain
+ readable, and post-cutover overlaps prefer the attributable turn span.
+- **Rollouts stay out of band** · Beacon does not continuously scan Codex
+ transcript files. Rollout JSONL remains a possible explicit recovery source,
+ not part of normal endpoint execution.
+
### Browser extension · August 24, 2026
- **Browser chat is a supported surface** · An optional Chrome MV3 extension
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index 2f056d6d..5f70c8a8 100644
--- a/docs/cli/endpoint-install.mdx
+++ b/docs/cli/endpoint-install.mdx
@@ -13,7 +13,7 @@ The service is a launchd job on macOS and a systemd unit on Linux. Where neither
beacon endpoint install
```
-By default, Beacon configures Claude Code and Codex CLI telemetry for local or customer-controlled runtime JSONL logs. Gemini CLI and VS Code Copilot telemetry are opt-in with the `gemini` and `vscode` harnesses. Claude Code can also use optional hook telemetry for richer lifecycle, subagent, permission, and tool detail; install the endpoint agent first, then add Claude hooks with `beacon endpoint hooks install --harness claude`. Codex runtime telemetry stays OTLP-based, but optional Codex hooks can trigger inventory heartbeats with `beacon endpoint hooks install --harness codex`. Beacon applies redaction, sanitization, truncation, and event-size limits before writing supported content fields. GitHub Copilot CLI and Factory Droid OTLP are managed through their launch environments, so Beacon validates their telemetry state but does not mutate shell profiles during install.
+By default, Beacon configures Claude Code and Codex CLI telemetry for local or customer-controlled runtime JSONL logs. Gemini CLI and VS Code Copilot telemetry are opt-in with the `gemini` and `vscode` harnesses. Claude Code can also use optional hook telemetry for richer lifecycle, subagent, permission, and tool detail; install the endpoint agent first, then add Claude hooks with `beacon endpoint hooks install --harness claude`. Codex uses OTLP logs plus one selective turn trace for tokens, and its required SessionStart hook adds local OS-user context and inventory heartbeats. Beacon applies redaction, sanitization, truncation, and event-size limits before writing supported content fields. GitHub Copilot CLI and Factory Droid OTLP are managed through their launch environments, so Beacon validates their telemetry state but does not mutate shell profiles during install.
## Flags
@@ -28,7 +28,7 @@ By default, Beacon configures Claude Code and Codex CLI telemetry for local or c
| `--collector <path>` | Path to a `beacon-otelcol` binary |
| `--no-start` | Write files without starting the collector service |
| `--include-runtime-metrics` | Include generic process, runtime, and harness operational OTLP metrics in Beacon JSONL. By default, low-signal metrics such as process CPU, memory, Node.js event loop, V8 heap, GitHub Copilot CLI, and OpenClaw operational metrics are filtered out |
-| `--include-codex-spans` | Include high-volume Codex OTLP spans for troubleshooting. By default, Beacon records Codex semantic logs and suppresses raw Codex spans |
+| `--include-codex-spans` | Include every high-volume Codex OTLP span for troubleshooting. By default, Beacon keeps semantic logs and only the usage-bearing completed turn span |
| `--splunk-hec-endpoint <url>` | Splunk HEC endpoint URL |
| `--splunk-hec-token <token>` | Splunk HEC token |
| `--splunk-index <index>` | Optional Splunk index |
diff --git a/docs/cli/endpoint-repair.mdx b/docs/cli/endpoint-repair.mdx
index 389486fb..66726ec4 100644
--- a/docs/cli/endpoint-repair.mdx
+++ b/docs/cli/endpoint-repair.mdx
@@ -28,7 +28,7 @@ During repair, Beacon removes the existing managed service before reinstalling i
| `--collector <path>` | Path to a `beacon-otelcol` binary |
| `--no-start` | Write files without starting the collector service |
| `--include-runtime-metrics` | Include generic process, runtime, and harness operational OTLP metrics in Beacon JSONL. By default, low-signal metrics such as process CPU, memory, Node.js event loop, V8 heap, GitHub Copilot CLI, and OpenClaw operational metrics are filtered out |
-| `--include-codex-spans` | Include high-volume Codex OTLP spans for troubleshooting. By default, Beacon records Codex semantic logs and suppresses raw Codex spans |
+| `--include-codex-spans` | Include every high-volume Codex OTLP span for troubleshooting. By default, Beacon keeps semantic logs and only the usage-bearing completed turn span |
| `--splunk-hec-endpoint <url>` | Splunk HEC endpoint URL |
| `--splunk-hec-token <token>` | Splunk HEC token |
| `--splunk-index <index>` | Optional Splunk index |
diff --git a/docs/cli/hooks.mdx b/docs/cli/hooks.mdx
index e4c7c900..3e8c57c6 100644
--- a/docs/cli/hooks.mdx
+++ b/docs/cli/hooks.mdx
@@ -71,7 +71,7 @@ Beacon validates the embedded `beacon-hooks` binary before writing hook configur
beacon endpoint hooks install --harness cursor
```
-The hook adapter records local endpoint events for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, permissions, diffs, and file edits where the selected runtime exposes those hook payloads. Antigravity hooks cover `PreInvocation`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostInvocation`, and `Stop`. Claude Code hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, `PermissionRequest`, and `SessionEnd`. Codex CLI hooks cover `SessionStart` and `UserPromptSubmit` for inventory heartbeats; Codex prompt, tool, and token telemetry still comes from its local OpenTelemetry export path. Devin CLI hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd`. Devin Desktop hooks use Cascade/Windsurf payloads for prompt submission, file writes, command execution, MCP tool use, and file reads. Factory hooks cover `SessionStart`, `UserPromptSubmit`, `PostToolUse` for write/edit/create operations, `Stop`, and `SessionEnd`. Grok Build hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SessionEnd`. Hermes Agent hooks cover session lifecycle, `pre_llm_call`, `pre_tool_call`, `post_tool_call`, approval request and response, and subagent stop events. OpenCode hooks use Beacon's managed local plugin to forward `chat.message`, session, command, permission, diff, and error events. Cline hooks use Beacon's managed local plugin to forward `beforeRun`, `beforeTool`, `afterTool`, and `afterRun`, and also accept Cline's file-based hook names (`TaskStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`) so one adapter serves both of Cline's hook surfaces.
+The hook adapter records local endpoint events for sessions, prompt submission, tool use, command execution, MCP-like tool activity, approval decisions, permissions, diffs, and file edits where the selected runtime exposes those hook payloads. Antigravity hooks cover `PreInvocation`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostInvocation`, and `Stop`. Claude Code hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, `SubagentStart`, `SubagentStop`, `PermissionRequest`, and `SessionEnd`. Codex CLI uses `SessionStart` for metadata-only OS-user context and inventory, plus `UserPromptSubmit` for inventory heartbeats; Codex prompt, tool, and token telemetry still comes from its local OpenTelemetry export path. Devin CLI hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `Stop`, and `SessionEnd`. Devin Desktop hooks use Cascade/Windsurf payloads for prompt submission, file writes, command execution, MCP tool use, and file reads. Factory hooks cover `SessionStart`, `UserPromptSubmit`, `PostToolUse` for write/edit/create operations, `Stop`, and `SessionEnd`. Grok Build hooks cover `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `Stop`, and `SessionEnd`. Hermes Agent hooks cover session lifecycle, `pre_llm_call`, `pre_tool_call`, `post_tool_call`, approval request and response, and subagent stop events. OpenCode hooks use Beacon's managed local plugin to forward `chat.message`, session, command, permission, diff, and error events. Cline hooks use Beacon's managed local plugin to forward `beforeRun`, `beforeTool`, `afterTool`, and `afterRun`, and also accept Cline's file-based hook names (`TaskStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`) so one adapter serves both of Cline's hook surfaces.
### Examples
@@ -442,7 +442,7 @@ Beacon's `PreToolUse` hook answers with an empty object on purpose. Qwen reads `
## Codex CLI troubleshooting
-Beacon writes Codex CLI inventory hooks to `~/.codex/hooks.json` for user-level installs or `./.codex/hooks.json` for project-level installs. These hooks trigger inventory heartbeats on `SessionStart` and `UserPromptSubmit`; they do not replace the Codex OTLP runtime telemetry path for prompt, tool, or token events.
+Beacon writes Codex CLI endpoint hooks to `~/.codex/hooks.json` for user-level installs or `./.codex/hooks.json` for project-level installs. `SessionStart` writes local OS-user/session context and triggers inventory; `UserPromptSubmit` refreshes inventory. These metadata-only hooks do not replace the Codex OTLP runtime path for prompt, tool, or token events.
If Codex inventory updates are missing, check the selected level, confirm the hook file contains commands with `--platform codex`, and restart Codex CLI so new sessions pick up the updated hook configuration.
diff --git a/docs/cli/token-usage.mdx b/docs/cli/token-usage.mdx
index 294225be..604ec8a8 100644
--- a/docs/cli/token-usage.mdx
+++ b/docs/cli/token-usage.mdx
@@ -5,7 +5,7 @@ description: "Report token usage and attribution from Beacon runtime logs"
## Command overview
-`beacon token-usage` reads Beacon runtime events from the JSONL log and summarizes token usage, cost, models, sessions, runs, harnesses, and repositories.
+`beacon token-usage` reads Beacon runtime events from the JSONL log and summarizes token usage, cost, users, models, sessions, runs, harnesses, and repositories.
```bash title="Command syntax"
beacon token-usage [flags]
@@ -23,19 +23,23 @@ Beacon normalizes token telemetry from every runtime into one canonical [`gen_ai
A few rules shape how the numbers read:
-- **Counts are kept disjoint.** `input_tokens`, `output_tokens`, `cache_read`, and `cache_creation` do not overlap, so a total is `input + output + cache_read + cache_creation` without double-counting. When a runtime reports prompt tokens inclusive of cache (Codex), Beacon subtracts the cached portion so the disjoint model holds.
+- **Counts are kept disjoint.** `input_tokens`, `output_tokens`, `cache_read`, and `cache_creation` do not overlap, so a total is `input + output + cache_read + cache_creation` without double-counting. Codex reports input inclusive of both cache reads and cache writes, so Beacon subtracts both before storing uncached input.
- **Cost is runtime-reported only.** `cost_usd` reflects what the runtime emits. Beacon never derives cost from local pricing tables, so cost appears only for runtimes that report it.
-- **Attribution depends on the metadata a runtime attaches.** Model, harness, repository, and run grouping work whenever those fields are present. Per-session grouping (`--session`, the session step tree) requires a session or conversation id on the usage signal.
+- **Attribution depends on the metadata a runtime attaches.** Model, harness, repository, and run grouping work whenever those fields are present. Per-session grouping (`--session`, the session step tree) requires a session or conversation id on the usage signal. Per-user grouping uses the event user directly or a matching session context event from a local hook.
- **Duplicate channels are de-duplicated.** When a runtime emits the same usage on more than one signal (Claude Code reports it on both logs and metrics), Beacon counts it once.
### Per-runtime coverage
-| Runtime | Tokens | Cost | Per-session |
-|---------|--------|------|-------------|
-| Claude Code | input, output, cache read, cache creation, reasoning | Reported (`cost_usd`) | Yes |
-| Codex CLI | input, output, cache read, reasoning | Not emitted by Codex | No (metric carries no conversation id) |
+| Runtime | Tokens | Cost | Per-session | Per-user |
+|---------|--------|------|-------------|----------|
+| Claude Code | input, output, cache read, cache creation, reasoning | Reported (`cost_usd`) | Yes | When local user context is present |
+| Codex CLI | input, output, cache read, cache creation, reasoning | Not emitted by Codex | Yes, from the turn trace | Yes, from matching SessionStart context |
-`cost_usd` and `--session` detail are empty for Codex because Codex does not emit a cost signal or a conversation id on its usage metric. This is not a Beacon limitation. See the [Codex CLI](/runtimes/codex-cli#token-usage-and-cost) and [Claude Code](/runtimes/claude-code) runtime pages for details.
+`cost_usd` remains empty for Codex because the attributable turn trace does not emit cost. Legacy metric-only Codex rows remain visible in historical totals but cannot be assigned to a session or user. See the [Codex CLI](/runtimes/codex-cli#token-usage-and-cost) and [Claude Code](/runtimes/claude-code) runtime pages for details.
+
+### Cost estimates are separate
+
+Beacon does not turn Codex token counts into `cost_usd`. A future report may show a separately labeled estimate with the pricing source, effective date, model, and service tier. Unknown models must remain unknown rather than reading as zero cost, and reasoning tokens must not be charged a second time because they are already included in output.
## Examples
diff --git a/docs/guides/jamf-anthropic-openai-cursor-mdm.mdx b/docs/guides/jamf-anthropic-openai-cursor-mdm.mdx
index 31ffdb8f..1a7e8375 100644
--- a/docs/guides/jamf-anthropic-openai-cursor-mdm.mdx
+++ b/docs/guides/jamf-anthropic-openai-cursor-mdm.mdx
@@ -40,7 +40,7 @@ After rollout:
- The S3 forwarder runs as `com.beacon.endpoint.s3-forwarder`.
- Claude Code hooks write local runtime telemetry.
- Cursor hooks write local runtime telemetry.
-- Codex CLI sends OTLP logs and token metrics to Beacon's local collector.
+- Codex CLI sends OTLP logs and an attributable turn-usage trace to Beacon's local collector; its SessionStart hook records the console user.
- Runtime telemetry is written locally to `/var/log/beacon-agent/runtime.jsonl`.
- Inventory telemetry is written locally to `/var/log/beacon-agent/inventory_state.jsonl`.
- Vector uploads both JSONL streams to your S3 bucket.
@@ -60,7 +60,7 @@ Runtime objects contain agent activity. Inventory objects contain agent configur
| --- | --- | --- |
| Claude Code | S3 helper installs Claude Code hooks for the console user | Prompt, lifecycle, tool, permission, command, file, and inventory telemetry where Claude Code exposes it |
| Cursor | Separate user hook policy installs Cursor hooks | Prompt, tool, shell command, MCP-like, approval, file edit, and inventory telemetry where Cursor exposes it |
-| Codex CLI | Separate user config policy writes `~/.codex/config.toml` | Codex semantic logs and token usage metrics emitted through local OTLP |
+| Codex CLI | User config repair writes `~/.codex/config.toml` and endpoint hooks | Codex semantic logs plus per-user/session/model turn usage emitted through local OTLP and joined to OS-user context |
| Claude Cowork, cloud agents, CI, SDK apps | Out of scope for this Mac MDM runbook | Configure those from their runtime-specific pages |
## Prerequisites
diff --git a/docs/runtimes/codex-cli.mdx b/docs/runtimes/codex-cli.mdx
index 24367a66..e6874d9d 100644
--- a/docs/runtimes/codex-cli.mdx
+++ b/docs/runtimes/codex-cli.mdx
@@ -5,34 +5,42 @@ description: "Asymptote support details for Codex CLI endpoint telemetry"
## Runtime overview
-Asymptote supports Codex CLI runtime telemetry through local OTLP logs and token usage metrics, with optional raw Codex spans for troubleshooting. Codex hooks can also trigger endpoint inventory heartbeats without replacing the OTLP runtime path.
+Asymptote supports Codex CLI runtime telemetry through local OTLP logs and one selective usage-bearing turn trace. A lightweight SessionStart hook records the local OS user for token attribution and also triggers endpoint inventory heartbeats.
## Prerequisites
Before enabling Codex CLI telemetry, make sure:
- Codex CLI is installed and available as the `codex` executable for the user or managed endpoint.
+- Codex CLI 0.149.1 or newer is used for verified turn-trace token attribution.
- `beacon endpoint install` has run so the local collector, endpoint config, and runtime log path exist.
- The install includes the `codex` harness, either through the default harness list or an explicit `--harness codex` value.
- Your team has reviewed content handling and destination access for prompt telemetry.
## Collection path
-Codex CLI exports local OpenTelemetry logs and metrics to Asymptote's localhost collector. Asymptote uses Codex semantic logs for session, prompt, approval, and tool-result events, and keeps the `codex.turn.token_usage` metric for token attribution. Other high-volume Codex metrics, and Codex spans, are suppressed by default. Optional Codex hooks are heartbeat-only and refresh `inventory_state.jsonl`; they do not write duplicate runtime prompt or session events.
+Codex CLI exports local OpenTelemetry logs and traces to Asymptote's localhost collector. Asymptote uses Codex semantic logs for session, prompt, approval, and tool-result events. For tokens it keeps only the completed `session_task.turn` span carrying `thread.id`, `turn.id`, model, and usage; hundreds of transport and internal spans remain suppressed. The SessionStart hook writes a metadata-only `session.context` event and refreshes `inventory_state.jsonl`; it never reads transcript content.
-Use `--include-codex-spans` during install or repair only when you need raw Codex spans for troubleshooting.
+Use `--include-codex-spans` during install or repair only when you need every raw Codex span for troubleshooting. It is not required for token attribution.
### Token usage and cost
-`beacon endpoint install` configures both the Codex log exporter and the Codex metrics exporter in `~/.codex/config.toml`, so Codex's per-turn `codex.turn.token_usage` metric reaches the collector. Beacon normalizes it into the canonical `gen_ai.usage` fields (`input_tokens`, `output_tokens`, `cache_read.input_tokens`, `reasoning.output_tokens`). Codex reports prompt tokens inclusive of the cached portion, so Beacon subtracts cached input to keep `input_tokens` and `cache_read` disjoint and avoid double-counting in totals.
+`beacon endpoint install` configures Codex's log and trace exporters in `~/.codex/config.toml`. Beacon normalizes the completed turn span into the same canonical `gen_ai.usage` fields used for Claude Code: uncached `input_tokens`, `output_tokens`, `cache_read.input_tokens`, `cache_creation.input_tokens`, and `reasoning.output_tokens`. Codex's input count includes both cache reads and cache writes, so Beacon subtracts both before recording uncached input.
-Two attribution limits are specific to Codex and follow from what Codex emits, not from Beacon:
+The span directly supplies the model and `session.id` (from Codex `thread.id`). Beacon joins the matching SessionStart context event to attribute local reports by OS user. The runtime log therefore contains both the token event and its session identity context, and both forward through configured JSONL shippers.
-- **No cost.** Codex does not emit a cost signal, so `gen_ai.usage.cost_usd` is empty for Codex turns. Beacon never derives cost from local pricing tables.
-- **No per-session attribution.** Codex's usage metric carries no conversation id, so Codex turns do not roll up by session. Model, harness, repository, and run attribution work normally.
+Codex still does not emit a cost signal on this span, so `gen_ai.usage.cost_usd` remains empty. Beacon never puts locally estimated pricing into that runtime-reported field.
+
+Legacy `codex.turn.token_usage` metrics in older logs remain reportable, but they have no session or user identity. New Beacon-managed configuration uses traces as the single live token source so spans and metrics cannot double-count the same turn.
See [How token attribution works](/cli/token-usage#how-token-attribution-works) for the cross-runtime model.
+### Rollout JSONL recovery
+
+Beacon does not continuously scan `~/.codex/sessions` or ingest rollout transcripts. Turn traces are structured, attributable, and avoid reading files that can contain prompts, tool output, and code.
+
+If historical backfill is added later, it should be an explicit recovery action over a hook-provided transcript path. A safe parser must read only session metadata, turn boundaries, and `token_count` records; compute positive field-by-field deltas from cumulative totals; handle repeated snapshots, forks, and resumes; and atomically checkpoint complete JSONL lines. It must never inspect `auth.json`.
+
## CI support
Asymptote can also capture Codex telemetry in CI with `beacon ci start` and `beacon ci finish`. In GitHub Actions, the Asymptote action creates a temporary `CODEX_HOME` with Codex OTLP settings and exposes it as `steps.<id>.outputs.codex-home` for actions such as `openai/codex-action`.
@@ -66,16 +74,18 @@ Asymptote detects Codex CLI through the `codex` executable and `~/.codex/config.
`beacon endpoint install` writes Codex OTLP exporter tables to `~/.codex/config.toml`.
-To let Codex sessions trigger inventory heartbeats, install optional Codex hooks after the endpoint is installed:
+`beacon endpoint install --harness codex` installs the required user-level
+session context and inventory hooks with the OTLP configuration. To refresh
+them independently, run:
```bash
beacon endpoint hooks install --harness codex
```
-The hook installer writes heartbeat-only hooks to `~/.codex/hooks.json` or project `.codex/hooks.json`, depending on `--level`. A successful user-level install prints:
+The hook installer writes the metadata-only session context hook plus inventory heartbeats to `~/.codex/hooks.json` or project `.codex/hooks.json`, depending on `--level`. A successful user-level install prints:
```text
-Codex CLI inventory hooks installed: /Users/you/.codex/hooks.json
+Codex CLI endpoint hooks installed: /Users/you/.codex/hooks.json
```
## Telemetry coverage
@@ -84,9 +94,10 @@ Codex CLI inventory hooks installed: /Users/you/.codex/hooks.json
|------|---------|
| Prompt telemetry | Supported when emitted through Codex semantic logs |
| Command, tool, and file telemetry | Supported when emitted through Codex semantic logs |
-| Token usage | Supported through the `codex.turn.token_usage` metric (input, output, cache read, reasoning) |
+| Token usage | Supported per turn through a selective OTLP trace (input, output, cache read, cache creation, reasoning) |
| Cost attribution | Not available; Codex emits no cost signal |
-| Per-session attribution | Not available; Codex usage metric carries no conversation id |
+| Per-session attribution | Supported from `thread.id` on the turn span |
+| Per-user attribution | Supported in local reports by joining the OS-user SessionStart context |
| Local JSONL and dashboard | Supported |
| MDM deployment | Supported through the system-mode package or MDM-managed config |
diff --git a/docs/runtimes/index.mdx b/docs/runtimes/index.mdx
index e10dcd83..7db58eba 100644
--- a/docs/runtimes/index.mdx
+++ b/docs/runtimes/index.mdx
@@ -22,7 +22,7 @@ These integrations are grouped by where the agent runs and how telemetry is coll
| [Antigravity CLI](/runtimes/antigravity-cli) | Native hooks | Prompt, pre-tool, post-tool, stop, invocation, command, and file telemetry where Antigravity exposes hook payloads |
| [Claude Code](/runtimes/claude-code) | Local OTLP export plus optional hooks | Prompt, command, tool, file, lifecycle, subagent, and permission telemetry where emitted through OTLP or hooks |
| [Cline](/runtimes/cline) | Managed plugin hooks | Prompts, task lifecycle, tool lifecycle, commands, file reads and edits with diffs, MCP activity, and token usage |
-| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs plus optional inventory hooks | Session, prompt, approval, and tool-result activity from Codex semantic logs; inventory heartbeat triggers from hooks |
+| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs and a selective usage trace plus endpoint hooks | Session, prompt, approval, and tool-result activity plus per-user/session/model turn token usage |
| [Cursor](/runtimes/cursor) | Native hooks | Prompt, tool, shell command, MCP-like, approval, and file edit telemetry |
| [Devin CLI](/runtimes/devin) | Native hooks | Session, prompt, pre-tool, post-tool, permission request, stop, session-end, approval, and file telemetry |
| [Devin Desktop](/runtimes/devin-desktop) | Cascade/Windsurf hooks | Prompt, command, MCP tool, file read, and file write telemetry where Desktop exposes Cascade hook payloads |
diff --git a/docs/runtimes/integration-model.mdx b/docs/runtimes/integration-model.mdx
index 7267b188..99964ead 100644
--- a/docs/runtimes/integration-model.mdx
+++ b/docs/runtimes/integration-model.mdx
@@ -37,7 +37,7 @@ During install, Beacon configures the runtime surfaces it can safely manage:
| Runtime or surface | Install-time behavior |
|--------------------|-----------------------|
| [Claude Code](/runtimes/claude-code) | Beacon points Claude Code at the local OTLP collector. Hook installation is separate through [`beacon endpoint hooks`](/cli/hooks). |
-| [Codex CLI](/runtimes/codex-cli) | Beacon points Codex CLI at the local OTLP collector, writes structured OTLP exporter tables to `~/.codex/config.toml`, sets `log_user_prompt = false`, and sends logs, traces, and metrics to the local collector. |
+| [Codex CLI](/runtimes/codex-cli) | Beacon points Codex CLI at the local OTLP collector, writes log and trace exporter tables to `~/.codex/config.toml`, enables prompt logging, retains one usage-bearing turn span, and installs a metadata-only SessionStart identity hook. |
| [Gemini CLI](/runtimes/gemini-cli) | Optional with `--harness gemini`. Beacon writes local OTLP settings to `~/.gemini/settings.json`, sets `target` to `local`, uses OTLP gRPC, enables the collector, and removes `outfile` so telemetry flows to Beacon. |
| [VS Code](/runtimes/vscode) | Optional with `--harness vscode`. Beacon writes Copilot Chat OTel settings to VS Code user settings and points OTLP/HTTP to the local collector. |
| [GitHub Copilot CLI](/runtimes/github-copilot-cli) | Copilot's OTLP HTTP endpoint remains under MDM or customer-owned launch-environment policy. Beacon validates `COPILOT_OTEL_ENABLED=true` and a localhost OTLP endpoint but does not write Copilot configuration. |
@@ -50,7 +50,7 @@ During install, Beacon configures the runtime surfaces it can safely manage:
| Runtime | Collection path | Notes |
|---------|-----------------|-------|
| [Claude Code](/runtimes/claude-code) | Local OTLP export plus optional hooks | Uses Claude settings to enable telemetry and point OTLP to localhost; Beacon decodes nested tool operands and separates API/session lifecycle from tool execution, while optional hooks add lifecycle, subagent, permission, and tool detail. |
-| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs, traces, and metrics | Beacon writes structured Codex OTLP config and filters noisy internal transport spans. |
+| [Codex CLI](/runtimes/codex-cli) | Local OTLP logs and selective turn traces plus a SessionStart hook | Beacon writes structured Codex OTLP config, filters noisy internal spans, and joins OS-user context to per-turn usage. |
| [Gemini CLI](/runtimes/gemini-cli) | Opt-in local OTLP logs, traces, and metrics | Beacon writes Gemini telemetry settings and maps Gemini prompts, tool calls, MCP activity, file operations, and approval events into endpoint events. |
| [GitHub Copilot CLI](/runtimes/github-copilot-cli) | MDM-managed OTLP HTTP export | Beacon validates Copilot's effective launch environment and maps Copilot spans into prompt, session, tool, and approval-like endpoint events. |
| [VS Code](/runtimes/vscode) | Copilot Chat OTel plus optional preview hooks | Beacon writes VS Code Copilot OTel settings and maps Copilot prompts, sessions, model metadata, and tool activity into endpoint events. Hooks are optional for extra lifecycle and cross-agent detail. |
diff --git a/docs/security/data-inventory.mdx b/docs/security/data-inventory.mdx
index 1a443b4f..0e5bea3e 100644
--- a/docs/security/data-inventory.mdx
+++ b/docs/security/data-inventory.mdx
@@ -12,7 +12,7 @@ Beacon writes normalized endpoint events only when supported runtimes provide te
| Agent harness | Collection path | Commonly available telemetry |
|---------------|-----------------|------------------------------|
| Claude Code | Local OTLP export | Prompt, command, tool, and file telemetry when emitted through OTLP |
-| Codex CLI | Local OTLP logs plus optional inventory hooks | Session, prompt, approval, and tool-result activity from Codex semantic logs; inventory heartbeat triggers from hooks |
+| Codex CLI | Local OTLP logs and a selective usage trace plus endpoint hooks | Session, prompt, approval, and tool-result activity; per-user/session/model token usage; metadata-only user context and inventory triggers from hooks |
| Gemini CLI | Opt-in local OTLP | Prompts, tool calls, MCP activity, file operations, and approval-related events emitted through OTLP |
| Grok Build | Native hooks | Session, prompt, pre-tool, post-tool, failed tool, stop, session-end, command, and file telemetry |
| OpenCode | Managed plugin hooks | Prompts, assistant text/reasoning, model and usage metadata, tool inputs/results/failures, commands and output, file activity/diffs, web/MCP calls, approvals, and session lifecycle/errors |
diff --git a/docs/telemetry-schema/examples.mdx b/docs/telemetry-schema/examples.mdx
index dec07a3e..fa8a791a 100644
--- a/docs/telemetry-schema/examples.mdx
+++ b/docs/telemetry-schema/examples.mdx
@@ -134,7 +134,7 @@ Beacon records supported content fields when source runtimes emit them. Redactio
Beacon caps event size, redacts common secret patterns, and marks events with `field_truncated` when fields must be shortened before writing. The `content` object can describe whether content was included, redacted, or truncated for a specific event. When present, `content.truncated` identifies truncation for that event's content payload even if downstream views also summarize top-level `field_truncated`.
-For Codex CLI, Beacon writes semantic session, prompt, approval, and tool-result events while suppressing noisy startup, turn, transport, metric, and duplicate span records by default. For GitHub Copilot CLI, Beacon maps OTLP spans into prompt, session, tool, and approval-like events. Beacon also filters generic process and runtime OTLP metrics, such as process CPU, memory, Node.js event loop, and V8 heap telemetry, plus Copilot CLI and OpenClaw operational metrics, out of the JSONL log by default. Use `--include-runtime-metrics` during endpoint install or repair only when those low-level metrics are required, and use `--include-codex-spans` only when raw Codex spans are needed for troubleshooting. The schema remains the same; these filters reduce low-signal records rather than changing event fields.
+For Codex CLI, Beacon writes semantic session, prompt, approval, and tool-result events plus the single completed turn span carrying attributable token usage, while suppressing noisy startup, transport, metric, and duplicate span records by default. For GitHub Copilot CLI, Beacon maps OTLP spans into prompt, session, tool, and approval-like events. Beacon also filters generic process and runtime OTLP metrics, such as process CPU, memory, Node.js event loop, and V8 heap telemetry, plus Copilot CLI and OpenClaw operational metrics, out of the JSONL log by default. Use `--include-runtime-metrics` during endpoint install or repair only when those low-level metrics are required, and use `--include-codex-spans` only when every raw Codex span is needed for troubleshooting. The schema remains the same; these filters reduce low-signal records rather than changing event fields.
## Related
diff --git a/docs/telemetry-schema/normalization.mdx b/docs/telemetry-schema/normalization.mdx
index eb597a3e..03c1998b 100644
--- a/docs/telemetry-schema/normalization.mdx
+++ b/docs/telemetry-schema/normalization.mdx
@@ -160,7 +160,7 @@ Beacon preserves OpenTelemetry GenAI semantic convention fields under the nested
| `gen_ai.usage.reasoning.output_tokens` | `gen_ai.usage.reasoning.output_tokens` |
| `gen_ai.usage.cost`, runtime `*.cost.usage` metric datapoints | `gen_ai.usage.cost_usd` |
-Usage also arrives as metric datapoints, not just span and log attributes. Claude Code's `claude_code.token.usage` and `claude_code.cost.usage` and Codex's `codex.turn.token_usage` are expanded per datapoint and mapped into the same `gen_ai.usage` fields by their `token_type` (for example Codex `cached_input` maps to `cache_read.input_tokens` and `reasoning_output` to `reasoning.output_tokens`; rollup types such as `total` are ignored). `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never derived from a local pricing table. See [How token attribution works](/cli/token-usage#how-token-attribution-works) for how these normalized fields aggregate into local reports.
+Usage also arrives as metric datapoints, not just span and log attributes. Claude Code's `claude_code.token.usage` and `claude_code.cost.usage` are expanded per datapoint. Codex's live source is its completed turn span, whose input, cache-read, cache-write, output, and reasoning attributes map into the same `gen_ai.usage` fields with `thread.id` promoted to `session.id`. Legacy `codex.turn.token_usage` metric rows remain supported for older logs. `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never derived from a local pricing table. See [How token attribution works](/cli/token-usage#how-token-attribution-works) for how these normalized fields aggregate into local reports.
## Prompt and content handling