Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 52 additions & 6 deletions bin/omarchy-agent-usage-codex
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,29 @@ def add_usage(day, session_key, model, input_tokens, output_tokens, cache_read,
today_tokens_by_model[model] = today_tokens_by_model.get(model, 0) + total


def pi_parent_session(path):
try:
with open(path, encoding="utf-8", errors="replace") as session_file:
header = json.loads(session_file.readline())
except (OSError, json.JSONDecodeError):
return None

if not isinstance(header, dict):
return None
parent = header.get("parentSession")
if not isinstance(parent, str) or not parent:
return None
return os.path.abspath(os.path.expanduser(parent))


def scan_pi_sessions():
roots = [
Path.home() / ".pi" / "agent" / "sessions",
Path.home() / ".omp" / "agent" / "sessions",
]
rg = find_command("rg") or "rg"
session_keys = {}
today_session_keys = {}
for root in roots:
if not root.exists():
continue
Expand All @@ -163,16 +180,22 @@ def scan_pi_sessions():
if event.get("type") != "match":
continue
line = event.get("data", {}).get("lines", {}).get("text", "")
path = event.get("data", {}).get("path", {}).get("text", "pi-session")
raw_path = event.get("data", {}).get("path", {}).get("text", "pi-session")
path = os.path.abspath(os.path.expanduser(raw_path))
entry = json.loads(line)
except Exception:
continue

if entry.get("type") != "message":
continue
message_key = path + ":" + str(entry.get("id") or "")
if message_key in seen_pi_messages:
continue
message_id = str(entry.get("id") or "")
message_timestamp = str(entry.get("timestamp") or "")
# Forks retain both fields; IDs alone can collide across sessions.
if message_id and message_timestamp:
message_key = ("entry", message_id, message_timestamp)
else:
message_key = ("path", path, message_id)
duplicate = message_key in seen_pi_messages
seen_pi_messages.add(message_key)
message = entry.get("message") or {}
if message.get("role") != "assistant":
Expand All @@ -196,14 +219,37 @@ def scan_pi_sessions():
continue

day = local_day(entry.get("timestamp") or message.get("timestamp"))
session_key = path
add_usage(day, session_key, model_name(message.get("model")), input_tokens, output_tokens, cache_read, cache_write)
session_keys.setdefault(path, set()).add(message_key)
if day == today:
today_session_keys.setdefault(path, set()).add(message_key)
if duplicate:
continue
add_usage(day, path, model_name(message.get("model")), input_tokens, output_tokens, cache_read, cache_write)

try:
proc.wait(timeout=1)
except Exception:
proc.kill()

# Resolve session ownership after scanning so rg's file order cannot affect it.
parents = {path: pi_parent_session(path) for path in session_keys}
total_sessions.difference_update(session_keys)
today_sessions.difference_update(session_keys)
for path, keys in session_keys.items():
inherited = set()
visited = {path}
parent = parents.get(path)
while parent and parent not in visited:
visited.add(parent)
inherited.update(session_keys.get(parent, ()))
parent = parents.get(parent)

unique_keys = keys - inherited
if unique_keys:
total_sessions.add(path)
if unique_keys & today_session_keys.get(path, set()):
today_sessions.add(path)


def scan_opencode_sessions():
# A subscription burned entirely through opencode leaves no native session
Expand Down
30 changes: 25 additions & 5 deletions test/shell.d/agent-usage-codex-scanner-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ source "$(dirname "$0")/base-test.sh"

require_command jq
require_command python3
require_command rg

TEST_HOME=$(mktemp -d)
trap 'rm -rf "$TEST_HOME"' EXIT
Expand Down Expand Up @@ -37,6 +38,7 @@ EOF
chmod +x "$TEST_HOME/bin/codex"

timestamp="$(date +%Y-%m-%d)T12:00:00Z"
collision_timestamp="$(date +%Y-%m-%d)T12:00:01Z"
session="$TEST_HOME/.codex/sessions/$(date +%Y/%m/%d)/rollout.jsonl"
cat >"$session" <<EOF
{"timestamp":"$timestamp","type":"turn_context","payload":{"model":"gpt-test"}}
Expand Down Expand Up @@ -74,8 +76,22 @@ PI_HOME=$(mktemp -d)
trap 'rm -rf "$TEST_HOME" "$PI_HOME"' EXIT
mkdir -p "$PI_HOME/bin" "$PI_HOME/.pi/agent/sessions/project" "$PI_HOME/.omp/agent/sessions/project"
cp "$TEST_HOME/bin/codex" "$PI_HOME/bin/codex"
real_rg=$(command -v rg)
cat >"$PI_HOME/bin/rg" <<EOF
#!/bin/bash
exec "$real_rg" --sort path "\$@"
EOF
chmod +x "$PI_HOME/bin/rg"
cat >"$PI_HOME/.pi/agent/sessions/project/pi.jsonl" <<EOF
{"type":"message","id":"pi-1","timestamp":"$timestamp","message":{"role":"assistant","provider":"openai-codex","api":"openai-codex-responses","model":"gpt-pi","usage":{"input":10,"output":4,"cacheRead":3,"cacheWrite":2,"totalTokens":19}}}
{"type":"message","id":"deadbeef","timestamp":"$timestamp","message":{"role":"assistant","provider":"openai-codex","api":"openai-codex-responses","model":"gpt-pi","usage":{"input":10,"output":4,"cacheRead":3,"cacheWrite":2,"totalTokens":19}}}
EOF
cat >"$PI_HOME/.pi/agent/sessions/project/pi-fork.jsonl" <<EOF
{"type":"session","id":"pi-fork","parentSession":"$PI_HOME/.pi/agent/sessions/project/pi.jsonl"}
{"type":"message","id":"deadbeef","timestamp":"$timestamp","message":{"role":"assistant","provider":"openai-codex","api":"openai-codex-responses","model":"gpt-pi","usage":{"input":10,"output":4,"cacheRead":3,"cacheWrite":2,"totalTokens":19}}}
{"type":"message","id":"cafebabe","timestamp":"$timestamp","message":{"role":"assistant","provider":"openai-codex","api":"openai-codex-responses","model":"gpt-pi","usage":{"input":6,"output":1,"cacheRead":0,"cacheWrite":0,"totalTokens":7}}}
EOF
cat >"$PI_HOME/.pi/agent/sessions/project/pi-id-collision.jsonl" <<EOF
{"type":"message","id":"deadbeef","timestamp":"$collision_timestamp","message":{"role":"assistant","provider":"openai-codex","api":"openai-codex-responses","model":"gpt-pi","usage":{"input":8,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":8}}}
EOF
cat >"$PI_HOME/.omp/agent/sessions/project/omp.jsonl" <<EOF
{ "type": "message", "id": "omp-1", "timestamp": "$timestamp", "message": { "role": "assistant", "provider": "openai-codex", "model": "gpt-omp", "usage": { "input": 20, "output": 5, "cacheRead": 4, "cacheWrite": 1, "totalTokens": 30 } } }
Expand All @@ -85,11 +101,15 @@ EOF
result=$(HOME="$PI_HOME" CODEX_HOME="$PI_HOME/.codex" XDG_DATA_HOME="$PI_HOME/.local/share" \
PATH="$PI_HOME/bin:$PATH" "$ROOT/bin/omarchy-agent-usage-codex")

[[ $(jq -r '.todayTotalTokens' <<<"$result") == "49" ]] ||
fail "Codex collector counts usage from pi and omp sessions" "$result"
[[ $(jq -c '.modelUsage' <<<"$result") == '{"gpt-pi":{"inputTokens":10,"outputTokens":4,"cacheReadInputTokens":3,"cacheCreationInputTokens":2},"gpt-omp":{"inputTokens":20,"outputTokens":5,"cacheReadInputTokens":4,"cacheCreationInputTokens":1}}' ]] ||
[[ $(jq -r '.todayTotalTokens' <<<"$result") == "64" ]] ||
fail "Codex collector counts Pi fork and OMP usage once" "$result"
[[ $(jq -c '.modelUsage' <<<"$result") == '{"gpt-pi":{"inputTokens":24,"outputTokens":5,"cacheReadInputTokens":3,"cacheCreationInputTokens":2},"gpt-omp":{"inputTokens":20,"outputTokens":5,"cacheReadInputTokens":4,"cacheCreationInputTokens":1}}' ]] ||
fail "Codex collector filters pi and omp sessions to Codex providers" "$result"
pass "Codex collector counts pi and omp subscription usage"
[[ $(jq -r '.todayPrompts' <<<"$result") == "4" ]] ||
fail "Codex collector keeps distinct Pi messages with colliding IDs" "$result"
[[ $(jq -c '[.todaySessions,.totalSessions]' <<<"$result") == '[4,4]' ]] ||
fail "Codex collector attributes new fork usage to its own session" "$result"
pass "Codex collector deduplicates Pi forks without collapsing ID collisions"

# A subscription burned entirely through opencode has no native session files;
# usage must come from opencode's message database, filtered to OpenAI.
Expand Down