From 7ddf36e6425f1bfb4d4115e8ad6194d3829bd9cb Mon Sep 17 00:00:00 2001 From: surim0n Date: Sat, 5 Sep 2026 11:20:35 -0400 Subject: [PATCH 1/3] Add a dedicated pi agent usage collector pi and oh-my-pi sessions are currently folded into the Claude and Codex collectors, which only count Anthropic and openai-codex providers. Users on any other backend (OpenRouter, Kimi, etc.) never see their usage in the agents panel. Add bin/omarchy-agent-usage-pi to scan ~/.pi and ~/.omp sessions for any provider, and stop counting those sessions in the Claude and Codex collectors. Fixes #8270 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- bin/omarchy-agent-usage-claude | 4 - bin/omarchy-agent-usage-codex | 1 - bin/omarchy-agent-usage-pi | 270 ++++++++++++++++++ .../agent-usage-claude-scanner-test.sh | 10 +- .../shell.d/agent-usage-codex-scanner-test.sh | 10 +- test/shell.d/agent-usage-pi-scanner-test.sh | 41 +++ 6 files changed, 321 insertions(+), 15 deletions(-) create mode 100755 bin/omarchy-agent-usage-pi create mode 100755 test/shell.d/agent-usage-pi-scanner-test.sh diff --git a/bin/omarchy-agent-usage-claude b/bin/omarchy-agent-usage-claude index 5b3634aef1c7..00478f3b681b 100755 --- a/bin/omarchy-agent-usage-claude +++ b/bin/omarchy-agent-usage-claude @@ -871,10 +871,6 @@ def main() -> int: if today_prompts or today_sessions: stats = dict(stats, todayPrompts=today_prompts, todaySessions=today_sessions) - pi_usage = scan_pi_usage(scan_age) - if pi_usage is not None: - stats = merge_stats(stats, pi_usage) - opencode = scan_opencode_usage(scan_age) if opencode is not None: stats = merge_stats(stats, opencode) diff --git a/bin/omarchy-agent-usage-codex b/bin/omarchy-agent-usage-codex index 972c164dee96..65e040e8d0f0 100755 --- a/bin/omarchy-agent-usage-codex +++ b/bin/omarchy-agent-usage-codex @@ -433,7 +433,6 @@ def local_stats(): def run_local_scans(): - scan_pi_sessions() scan_native_codex_sessions() complete = scan_opencode_sessions() return local_stats(), complete diff --git a/bin/omarchy-agent-usage-pi b/bin/omarchy-agent-usage-pi new file mode 100755 index 000000000000..eaac3429ccad --- /dev/null +++ b/bin/omarchy-agent-usage-pi @@ -0,0 +1,270 @@ +#!/usr/bin/python3 +# omarchy:summary=Print the Pi/Oh My Pi usage record as JSON +# omarchy:args=[--force] [--limits-only] +# omarchy:hidden=true +"""Collect Pi and Oh My Pi usage into one display-ready JSON record. + +Scans ~/.pi/agent/sessions and ~/.omp/agent/sessions for any provider that +writes provider, model, and token usage on assistant messages. This deliberately +does not filter by backend, so OpenRouter, Anthropic, OpenAI, and any other +configured provider all contribute to a single 'pi' record. +""" + +import datetime as dt +import fcntl +import json +import os +import tempfile +import time +from pathlib import Path +from typing import Any + +AGENT_ID = "pi" +AGENT_NAME = "Pi" +SCAN_REUSE_SECONDS = 20 +LIMITS_ONLY_REUSE_SECONDS = 900 + + +def cache_root() -> Path: + root = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "omarchy" / "agent-usage" + root.mkdir(parents=True, exist_ok=True) + return root + + +def date_string(value: dt.date) -> str: + return value.strftime("%Y-%m-%d") + + +def recent_date_strings() -> list[str]: + today = dt.datetime.now().date() + return [date_string(today - dt.timedelta(days=offset)) for offset in range(6, -1, -1)] + + +def local_date_string() -> str: + return date_string(dt.datetime.now().date()) + + +def local_date_from_timestamp(value: Any) -> str: + if value is None: + return local_date_string() + + if isinstance(value, (int, float)): + try: + seconds = float(value) / 1000.0 if float(value) > 10_000_000_000 else float(value) + return date_string(dt.datetime.fromtimestamp(seconds).date()) + except Exception: + return local_date_string() + + raw = str(value).strip() + if not raw: + return local_date_string() + + try: + parsed = dt.datetime.fromisoformat(raw.replace("Z", "+00:00")) + if parsed.tzinfo is not None: + parsed = parsed.astimezone() + return date_string(parsed.date()) + except Exception: + return local_date_string() + + +def usage_token(usage: dict[str, Any], snake_key: str, camel_key: str) -> int: + value = usage.get(snake_key, usage.get(camel_key, 0)) + try: + return round(float(value or 0)) + except Exception: + return 0 + + +def number(value: Any) -> int: + try: + n = float(value or 0) + return round(n) if n == n else 0 + except Exception: + return 0 + + +def empty_bucket() -> dict[str, int]: + return { + "inputTokens": 0, + "outputTokens": 0, + "cacheReadInputTokens": 0, + "cacheCreationInputTokens": 0, + } + + +def read_fresh_json(path: Path, max_age_seconds: float) -> dict[str, Any] | None: + if max_age_seconds <= 0 or not path.exists(): + return None + try: + if time.time() - path.stat().st_mtime <= max_age_seconds: + return json.loads(path.read_text(encoding="utf-8")) + except Exception: + return None + return None + + +def write_json(path: Path, payload: dict[str, Any]) -> None: + handle_fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp") + tmp = Path(tmp_name) + try: + with os.fdopen(handle_fd, "w", encoding="utf-8") as handle: + handle.write(json.dumps(payload, separators=(",", ":"), sort_keys=True) + "\n") + tmp.chmod(0o644) + tmp.replace(path) + except BaseException: + tmp.unlink(missing_ok=True) + raise + + +def scan_sessions() -> dict[str, Any] | None: + roots = [ + Path.home() / ".pi" / "agent" / "sessions", + Path.home() / ".omp" / "agent" / "sessions", + ] + cache_file = cache_root() / "pi-sessions.json" + + today = local_date_string() + recent_dates = recent_date_strings() + recent = {day: {"date": day, "messageCount": 0} for day in recent_dates} + sessions: set[str] = set() + active_days: set[str] = set() + today_sessions: set[str] = set() + today_tokens: dict[str, int] = {} + usage_by_model: dict[str, dict[str, int]] = {} + seen: set[str] = set() + prompts = 0 + today_prompt_count = 0 + today_token_total = 0 + + for root in roots: + files = root.rglob("*.jsonl") if root.is_dir() else [] + for path in files: + try: + with path.open("r", encoding="utf-8", errors="replace") as handle: + for line_number, line in enumerate(handle, 1): + if '"usage"' not in line or '"assistant"' not in line: + continue + try: + entry = json.loads(line) + except Exception: + continue + + message = entry.get("message") if isinstance(entry.get("message"), dict) else {} + if entry.get("type") != "message" or message.get("role") != "assistant": + continue + + usage = message.get("usage") or {} + if not isinstance(usage, dict): + continue + + unique_key = f"{path}:{entry.get('id') or line_number}" + if unique_key in seen: + continue + seen.add(unique_key) + + input_tokens = usage_token(usage, "input", "inputTokens") + output_tokens = usage_token(usage, "output", "outputTokens") + cache_read = usage_token(usage, "cacheRead", "cacheReadInputTokens") + cache_write = usage_token(usage, "cacheWrite", "cacheCreationInputTokens") + total = input_tokens + output_tokens + cache_read + cache_write + if total <= 0: + total = number(usage.get("totalTokens")) + input_tokens = total + if total <= 0: + continue + + model = str(message.get("model") or "pi") + day = local_date_from_timestamp(entry.get("timestamp") or message.get("timestamp")) + session_key = str(path) + sessions.add(session_key) + active_days.add(day) + prompts += 1 + + bucket = usage_by_model.setdefault(model, empty_bucket()) + bucket["inputTokens"] += input_tokens + bucket["outputTokens"] += output_tokens + bucket["cacheReadInputTokens"] += cache_read + bucket["cacheCreationInputTokens"] += cache_write + + if day in recent: + recent[day]["messageCount"] += total + if day == today: + today_prompt_count += 1 + today_sessions.add(session_key) + today_token_total += total + today_tokens[model] = today_tokens.get(model, 0) + total + except OSError: + continue + + if prompts <= 0: + return None + + return { + "todayPrompts": today_prompt_count, + "todaySessions": len(today_sessions), + "todayTotalTokens": today_token_total, + "todayTokensByModel": today_tokens, + "recentDays": [recent[day] for day in recent_dates], + "modelUsage": usage_by_model, + "totalPrompts": prompts, + "totalSessions": len(sessions), + "activeDays": len(active_days), + "activeDates": sorted(active_days), + } + + +def cached_scan(max_age_seconds: float) -> dict[str, Any] | None: + cache_file = cache_root() / "pi-sessions.json" + + cached = read_fresh_json(cache_file, max_age_seconds) + if cached is not None: + return cached.get("stats") + + stats = scan_sessions() + if stats is not None: + write_json(cache_file, {"stats": stats}) + return stats + + +def main() -> int: + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--force", action="store_true") + parser.add_argument("--limits-only", action="store_true") + parser.add_argument("--cache-seconds", type=float, default=20) + args = parser.parse_args() + + max_age = 0 if args.force else (LIMITS_ONLY_REUSE_SECONDS if args.limits_only else args.cache_seconds) + stats = cached_scan(max_age) + + record = { + "schemaVersion": 1, + "id": AGENT_ID, + "name": AGENT_NAME, + "updatedAt": dt.datetime.now(dt.timezone.utc).isoformat(), + "ready": True, + "hasLocalStats": True, + } + if stats is not None: + record.update(stats) + else: + record.update({ + "todayPrompts": 0, + "todaySessions": 0, + "todayTotalTokens": 0, + "todayTokensByModel": {}, + "recentDays": [{"date": day, "messageCount": 0} for day in recent_date_strings()], + "modelUsage": {}, + "totalPrompts": 0, + "totalSessions": 0, + "activeDays": 0, + "activeDates": [], + }) + + print(json.dumps(record, separators=(",", ":"), sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/test/shell.d/agent-usage-claude-scanner-test.sh b/test/shell.d/agent-usage-claude-scanner-test.sh index e1407f3cf2e2..884027d59414 100644 --- a/test/shell.d/agent-usage-claude-scanner-test.sh +++ b/test/shell.d/agent-usage-claude-scanner-test.sh @@ -121,11 +121,11 @@ EOF result=$(HOME="$PI_HOME" XDG_CACHE_HOME="$PI_HOME/.cache" XDG_DATA_HOME="$PI_HOME/.local/share" \ "$ROOT/bin/omarchy-agent-usage-claude" --force) -[[ $(jq -r '.todayTotalTokens' <<<"$result") == "49" ]] || - fail "Claude collector counts usage from pi and omp sessions" "$result" -[[ $(jq -c '.modelUsage' <<<"$result") == '{"claude-omp":{"cacheCreationInputTokens":1,"cacheReadInputTokens":4,"inputTokens":20,"outputTokens":5},"claude-pi":{"cacheCreationInputTokens":2,"cacheReadInputTokens":3,"inputTokens":10,"outputTokens":4}}' ]] || - fail "Claude collector filters pi and omp sessions to Anthropic providers" "$result" -pass "Claude collector counts pi and omp subscription usage" +[[ $(jq -r '.todayTotalTokens' <<<"$result") == "0" ]] || + fail "Claude collector no longer counts pi and omp sessions" "$result" +[[ $(jq -c '.modelUsage' <<<"$result") == '{}' ]] || + fail "Claude collector keeps pi and omp usage in the dedicated pi collector" "$result" +pass "Claude collector leaves pi and omp sessions to the pi collector" # Collectors overlap in practice: the update command backgrounds one per agent # while the panel refreshes on its own. Two writers aiming at one cache file diff --git a/test/shell.d/agent-usage-codex-scanner-test.sh b/test/shell.d/agent-usage-codex-scanner-test.sh index 3ce4883cdbfb..da31c997763b 100644 --- a/test/shell.d/agent-usage-codex-scanner-test.sh +++ b/test/shell.d/agent-usage-codex-scanner-test.sh @@ -85,11 +85,11 @@ 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}}' ]] || - fail "Codex collector filters pi and omp sessions to Codex providers" "$result" -pass "Codex collector counts pi and omp subscription usage" +[[ $(jq -r '.todayTotalTokens' <<<"$result") == "0" ]] || + fail "Codex collector no longer counts pi and omp sessions" "$result" +[[ $(jq -c '.modelUsage' <<<"$result") == '{}' ]] || + fail "Codex collector keeps pi and omp usage in the dedicated pi collector" "$result" +pass "Codex collector leaves pi and omp sessions to the pi collector" # A subscription burned entirely through opencode has no native session files; # usage must come from opencode's message database, filtered to OpenAI. diff --git a/test/shell.d/agent-usage-pi-scanner-test.sh b/test/shell.d/agent-usage-pi-scanner-test.sh new file mode 100755 index 000000000000..70615f2f6a17 --- /dev/null +++ b/test/shell.d/agent-usage-pi-scanner-test.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +source "$(dirname "$0")/base-test.sh" + +require_command jq +require_command python3 + +TEST_HOME=$(mktemp -d) +trap 'rm -rf "$TEST_HOME"' EXIT + +mkdir -p "$TEST_HOME/.pi/agent/sessions/project" "$TEST_HOME/.omp/agent/sessions/project" + +timestamp="$(date +%Y-%m-%d)T12:00:00Z" + +cat >"$TEST_HOME/.pi/agent/sessions/project/pi.jsonl" <"$TEST_HOME/.omp/agent/sessions/project/omp.jsonl" < Date: Tue, 8 Sep 2026 00:12:35 -0400 Subject: [PATCH 2/3] Keep Pi usage accurate across cache refreshes and session forks Make local usage caching date-aware, optional and safe after empty or failed refreshes. Validate transcript records, discover configured session roots and profiles, and deduplicate inherited responses without conflating independent short IDs or mutable billing fields. Invalidate pre-split Codex caches, label Pi as local usage, and cover the regressions in both UTC and UTC+14. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- bin/omarchy-agent-usage-claude | 2 +- bin/omarchy-agent-usage-codex | 14 +- bin/omarchy-agent-usage-pi | 409 +++++++++++++------- shell/plugins/agents/README.md | 11 +- shell/plugins/agents/manifest.json | 4 +- test/shell.d/agent-usage-pi-scanner-test.sh | 380 +++++++++++++++++- 6 files changed, 657 insertions(+), 163 deletions(-) diff --git a/bin/omarchy-agent-usage-claude b/bin/omarchy-agent-usage-claude index 00478f3b681b..2e8a3c31ce2c 100755 --- a/bin/omarchy-agent-usage-claude +++ b/bin/omarchy-agent-usage-claude @@ -6,7 +6,7 @@ Everything the agents panel shows for Claude comes from this one command: local transcript stats from ~/.claude/projects, the stats-cache and -history fallbacks for machines without transcripts, pi/omp and opencode +history fallbacks for machines without transcripts, opencode sessions that ran on an Anthropic provider, and the authoritative rate limits from Anthropic's OAuth usage endpoint. The panel itself only ever reads the JSON this prints; it never talks to disk formats or endpoints. diff --git a/bin/omarchy-agent-usage-codex b/bin/omarchy-agent-usage-codex index 65e040e8d0f0..20bccdbedd3c 100755 --- a/bin/omarchy-agent-usage-codex +++ b/bin/omarchy-agent-usage-codex @@ -4,10 +4,10 @@ # omarchy:hidden=true """Collect Codex usage into one display-ready JSON record. -Local stats come from native Codex CLI session files, pi/omp sessions that -ran through openai-codex, and opencode sessions that ran on an OpenAI -provider; rate limits and the plan come from the Codex app-server RPC. The agents -panel only ever reads the JSON this prints. +Local stats come from native Codex CLI session files and opencode sessions +that ran on an OpenAI provider; rate limits and the plan come from the Codex +app-server RPC. Pi/OMP local stats belong to the dedicated Pi collector. +The agents panel only ever reads the JSON this prints. """ import argparse @@ -346,9 +346,9 @@ def cache_root(): def scan_cache_paths(): codex_home = Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex")) db = Path(os.environ.get("XDG_DATA_HOME") or (Path.home() / ".local" / "share")) / "opencode" / "opencode.db" - # The digest covers every data path the scan reads: the codex session - # roots, the opencode DB, and (via Path.home()) the pi/omp session roots. - digest = hashlib.sha1((str(Path.home()) + "\n" + str(codex_home) + "\n" + str(db)).encode("utf-8")).hexdigest()[:16] + # The digest covers the codex session roots and the opencode DB; its + # namespace excludes caches from before Pi/OMP moved to their own collector. + digest = hashlib.sha1(("native-opencode\n" + str(Path.home()) + "\n" + str(codex_home) + "\n" + str(db)).encode("utf-8")).hexdigest()[:16] root = cache_root() return root / f"codex-scan-{digest}.json", root / f"codex-scan-{digest}.lock" diff --git a/bin/omarchy-agent-usage-pi b/bin/omarchy-agent-usage-pi index eaac3429ccad..c16374973703 100755 --- a/bin/omarchy-agent-usage-pi +++ b/bin/omarchy-agent-usage-pi @@ -4,18 +4,22 @@ # omarchy:hidden=true """Collect Pi and Oh My Pi usage into one display-ready JSON record. -Scans ~/.pi/agent/sessions and ~/.omp/agent/sessions for any provider that -writes provider, model, and token usage on assistant messages. This deliberately +Scans default and configured Pi/OMP session directories, including profiles, +for provider, model, and token usage on assistant messages. This deliberately does not filter by backend, so OpenRouter, Anthropic, OpenAI, and any other -configured provider all contribute to a single 'pi' record. +configured provider all contribute to a single local-only 'pi' record. """ import datetime as dt import fcntl +import hashlib import json +import math import os +import sys import tempfile import time +import uuid from pathlib import Path from typing import Any @@ -26,7 +30,7 @@ LIMITS_ONLY_REUSE_SECONDS = 900 def cache_root() -> Path: - root = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "omarchy" / "agent-usage" + root = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "omarchy" / "agent-usage" root.mkdir(parents=True, exist_ok=True) return root @@ -44,44 +48,33 @@ def local_date_string() -> str: return date_string(dt.datetime.now().date()) -def local_date_from_timestamp(value: Any) -> str: - if value is None: - return local_date_string() - - if isinstance(value, (int, float)): - try: - seconds = float(value) / 1000.0 if float(value) > 10_000_000_000 else float(value) +def local_date_from_timestamp(value: Any) -> str | None: + try: + if type(value) in (int, float): + if not math.isfinite(value) or value < 0: + return None + seconds = value / 1000.0 if value > 10_000_000_000 else value return date_string(dt.datetime.fromtimestamp(seconds).date()) - except Exception: - return local_date_string() + if isinstance(value, str) and value.strip(): + parsed = dt.datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + if parsed.tzinfo is not None: + parsed = parsed.astimezone() + return date_string(parsed.date()) + except (ValueError, OverflowError, OSError): + pass + return None - raw = str(value).strip() - if not raw: - return local_date_string() - try: - parsed = dt.datetime.fromisoformat(raw.replace("Z", "+00:00")) - if parsed.tzinfo is not None: - parsed = parsed.astimezone() - return date_string(parsed.date()) - except Exception: - return local_date_string() +def number(value: Any) -> int: + if type(value) not in (int, float) or value < 0: + raise ValueError("invalid token count") + if isinstance(value, float) and (not math.isfinite(value) or not value.is_integer()): + raise ValueError("invalid token count") + return int(value) def usage_token(usage: dict[str, Any], snake_key: str, camel_key: str) -> int: - value = usage.get(snake_key, usage.get(camel_key, 0)) - try: - return round(float(value or 0)) - except Exception: - return 0 - - -def number(value: Any) -> int: - try: - n = float(value or 0) - return round(n) if n == n else 0 - except Exception: - return 0 + return number(usage.get(snake_key, usage.get(camel_key, 0))) def empty_bucket() -> dict[str, int]: @@ -93,17 +86,67 @@ def empty_bucket() -> dict[str, int]: } +def empty_stats() -> dict[str, Any]: + return { + "todayPrompts": 0, + "todaySessions": 0, + "todayTotalTokens": 0, + "todayTokensByModel": {}, + "recentDays": [{"date": day, "messageCount": 0} for day in recent_date_strings()], + "modelUsage": {}, + "totalPrompts": 0, + "totalSessions": 0, + "activeDays": 0, + "activeDates": [], + } + + def read_fresh_json(path: Path, max_age_seconds: float) -> dict[str, Any] | None: - if max_age_seconds <= 0 or not path.exists(): + if max_age_seconds <= 0: return None try: - if time.time() - path.stat().st_mtime <= max_age_seconds: - return json.loads(path.read_text(encoding="utf-8")) - except Exception: - return None + age = time.time() - path.stat().st_mtime + if 0 <= age <= max_age_seconds: + payload = json.loads(path.read_text(encoding="utf-8")) + if isinstance(payload, dict): + return payload + except (OSError, ValueError): + pass return None +def read_cached_stats(path: Path, max_age_seconds: float, roots: list[Path]) -> dict[str, Any] | None: + cached = read_fresh_json(path, max_age_seconds) + if not cached or cached.get("schemaVersion") != 1 or cached.get("scanDate") != local_date_string(): + return None + if cached.get("roots") != [str(root) for root in roots]: + return None + stats = cached.get("stats") + template = empty_stats() + if not isinstance(stats, dict) or any(type(stats.get(key)) is not type(value) for key, value in template.items()): + return None + try: + for key, value in template.items(): + if isinstance(value, int): + number(stats[key]) + for value in stats["todayTokensByModel"].values(): + number(value) + for bucket in stats["modelUsage"].values(): + if not isinstance(bucket, dict) or set(bucket) != set(empty_bucket()): + return None + for value in bucket.values(): + number(value) + if [day.get("date") for day in stats["recentDays"]] != recent_date_strings(): + return None + for day in stats["recentDays"]: + number(day["messageCount"]) + if any(not isinstance(day, str) or dt.date.fromisoformat(day).isoformat() != day for day in stats["activeDates"]): + return None + except (ValueError, TypeError, KeyError, AttributeError): + return None + return {key: stats[key] for key in template} + + def write_json(path: Path, payload: dict[str, Any]) -> None: handle_fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp") tmp = Path(tmp_name) @@ -117,114 +160,196 @@ def write_json(path: Path, payload: dict[str, Any]) -> None: raise -def scan_sessions() -> dict[str, Any] | None: - roots = [ - Path.home() / ".pi" / "agent" / "sessions", - Path.home() / ".omp" / "agent" / "sessions", - ] - cache_file = cache_root() / "pi-sessions.json" - +def session_roots() -> list[Path]: + bases = {Path.home() / ".pi", Path.home() / ".omp"} + if os.environ.get("PI_CONFIG_DIR"): + bases.add(Path.home() / os.path.expanduser(os.environ["PI_CONFIG_DIR"])) + roots = [base / "agent" / "sessions" for base in bases] + if os.environ.get("PI_CODING_AGENT_DIR"): + roots.append(Path(os.path.expandvars(os.path.expanduser(os.environ["PI_CODING_AGENT_DIR"]))) / "sessions") + if os.environ.get("PI_CODING_AGENT_SESSION_DIR"): + roots.append(Path(os.path.expanduser(os.environ["PI_CODING_AGENT_SESSION_DIR"]))) + for base in bases: + roots.extend(base.glob("profiles/*/agent/sessions")) + if os.environ.get("XDG_DATA_HOME"): + omp_data = Path(os.environ["XDG_DATA_HOME"]) / "omp" + roots.append(omp_data / "sessions") + roots.extend(omp_data.glob("profiles/*/sessions")) + return sorted({root.resolve() for root in roots}) + + +def session_lineage(path: Path, parents: dict[Path, Path | uuid.UUID]) -> tuple[Path | uuid.UUID, int]: + visited: set[Path] = set() + current: Path | uuid.UUID = path + while isinstance(current, Path) and current in parents: + if current in visited: + return path, 0 + visited.add(current) + current = parents[current] + return current, len(visited) + + +def scan_sessions(roots: list[Path]) -> tuple[dict[str, Any], bool]: today = local_date_string() - recent_dates = recent_date_strings() - recent = {day: {"date": day, "messageCount": 0} for day in recent_dates} - sessions: set[str] = set() - active_days: set[str] = set() - today_sessions: set[str] = set() - today_tokens: dict[str, int] = {} - usage_by_model: dict[str, dict[str, int]] = {} - seen: set[str] = set() - prompts = 0 - today_prompt_count = 0 - today_token_total = 0 + stats = empty_stats() + recent = {day["date"]: day for day in stats["recentDays"]} + records: dict[Path, list] = {} + headers: dict[Path, dict] = {} + aliases: dict[Path, Path] = {} + physical_files: dict[tuple[int, int], Path] = {} + complete = True for root in roots: - files = root.rglob("*.jsonl") if root.is_dir() else [] - for path in files: + try: + candidates = sorted(root.rglob("*.jsonl")) + except OSError as exc: + print(f"omarchy-agent-usage-pi: incomplete scan of {root} ({exc})", file=sys.stderr) + complete = False + continue + for candidate in candidates: try: + path = candidate.resolve() + file_stat = path.stat() + physical_key = (file_stat.st_dev, file_stat.st_ino) + aliases[path] = physical_files.setdefault(physical_key, path) + if aliases[path] != path or path in records: + continue + records[path] = [] with path.open("r", encoding="utf-8", errors="replace") as handle: for line_number, line in enumerate(handle, 1): - if '"usage"' not in line or '"assistant"' not in line: + if '"session"' not in line and '"assistant"' not in line: continue try: entry = json.loads(line) - except Exception: + except ValueError: continue - - message = entry.get("message") if isinstance(entry.get("message"), dict) else {} - if entry.get("type") != "message" or message.get("role") != "assistant": + if not isinstance(entry, dict): continue - - usage = message.get("usage") or {} + if entry.get("type") == "session": + headers.setdefault(path, entry) + continue + message = entry.get("message") + if entry.get("type") != "message" or not isinstance(message, dict) or message.get("role") != "assistant": + continue + usage = message.get("usage") if not isinstance(usage, dict): continue - - unique_key = f"{path}:{entry.get('id') or line_number}" - if unique_key in seen: + try: + bucket = { + "inputTokens": usage_token(usage, "input", "inputTokens"), + "outputTokens": usage_token(usage, "output", "outputTokens"), + "cacheReadInputTokens": usage_token(usage, "cacheRead", "cacheReadInputTokens"), + "cacheCreationInputTokens": usage_token(usage, "cacheWrite", "cacheCreationInputTokens"), + } + total = sum(bucket.values()) + if total == 0: + total = number(usage.get("totalTokens", 0)) + bucket["inputTokens"] = total + except ValueError: continue - seen.add(unique_key) - - input_tokens = usage_token(usage, "input", "inputTokens") - output_tokens = usage_token(usage, "output", "outputTokens") - cache_read = usage_token(usage, "cacheRead", "cacheReadInputTokens") - cache_write = usage_token(usage, "cacheWrite", "cacheCreationInputTokens") - total = input_tokens + output_tokens + cache_read + cache_write - if total <= 0: - total = number(usage.get("totalTokens")) - input_tokens = total - if total <= 0: + if total == 0: continue - - model = str(message.get("model") or "pi") - day = local_date_from_timestamp(entry.get("timestamp") or message.get("timestamp")) - session_key = str(path) - sessions.add(session_key) - active_days.add(day) - prompts += 1 - - bucket = usage_by_model.setdefault(model, empty_bucket()) - bucket["inputTokens"] += input_tokens - bucket["outputTokens"] += output_tokens - bucket["cacheReadInputTokens"] += cache_read - bucket["cacheCreationInputTokens"] += cache_write - - if day in recent: - recent[day]["messageCount"] += total - if day == today: - today_prompt_count += 1 - today_sessions.add(session_key) - today_token_total += total - today_tokens[model] = today_tokens.get(model, 0) + total - except OSError: + model = message.get("model") or "pi" + day = local_date_from_timestamp(entry.get("timestamp")) or local_date_from_timestamp(message.get("timestamp")) + if not isinstance(model, str) or not day or day > today: + continue + entry_id = entry.get("id") + if not isinstance(entry_id, str) or not entry_id: + entry_id = f"{path}:{line_number}" + identity = [entry.get("timestamp"), message.get("timestamp"), message.get("provider"), + model, message.get("content"), bucket] + fingerprint = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).digest() + records[path].append((entry_id, fingerprint, model, day, bucket, total)) + except OSError as exc: + print(f"omarchy-agent-usage-pi: incomplete scan of {candidate} ({exc})", file=sys.stderr) + complete = False + + paths_by_id: dict[str, list[Path]] = {} + for path, header in headers.items(): + session_id = header.get("id") + if isinstance(session_id, str) and session_id: + paths_by_id.setdefault(session_id, []).append(path) + parents: dict[Path, Path | uuid.UUID] = {} + for path, header in headers.items(): + parent = header.get("parentSession") + if not isinstance(parent, str) or not parent: + continue + matches = paths_by_id.get(parent, []) + if len(matches) == 1: + parents[path] = matches[0] + elif parent.endswith(".jsonl") or Path(parent).is_absolute(): + try: + parent_path = (path.parent / parent).resolve() + parents[path] = aliases.get(parent_path, parent_path) + except (OSError, ValueError, RuntimeError): + continue + elif not matches: + try: + parent_id = uuid.UUID(parent) + if str(parent_id) == parent: + parents[path] = parent_id + except ValueError: continue - if prompts <= 0: - return None - - return { - "todayPrompts": today_prompt_count, - "todaySessions": len(today_sessions), - "todayTotalTokens": today_token_total, - "todayTokensByModel": today_tokens, - "recentDays": [recent[day] for day in recent_dates], - "modelUsage": usage_by_model, - "totalPrompts": prompts, - "totalSessions": len(sessions), - "activeDays": len(active_days), - "activeDates": sorted(active_days), - } - - -def cached_scan(max_age_seconds: float) -> dict[str, Any] | None: - cache_file = cache_root() / "pi-sessions.json" - - cached = read_fresh_json(cache_file, max_age_seconds) - if cached is not None: - return cached.get("stats") - - stats = scan_sessions() - if stats is not None: - write_json(cache_file, {"stats": stats}) - return stats + lineages = {path: session_lineage(path, parents) for path in records} + seen: set[tuple] = set() + sessions: set[Path] = set() + today_sessions: set[Path] = set() + active_days: set[str] = set() + for path in sorted(records, key=lambda path: (lineages[path][1], str(path))): + for entry_id, fingerprint, model, day, tokens, total in records[path]: + unique_key = (lineages[path][0], entry_id, fingerprint) + if unique_key in seen: + continue + seen.add(unique_key) + sessions.add(path) + active_days.add(day) + stats["totalPrompts"] += 1 + bucket = stats["modelUsage"].setdefault(model, empty_bucket()) + for key, value in tokens.items(): + bucket[key] += value + if day in recent: + recent[day]["messageCount"] += total + if day == today: + today_sessions.add(path) + stats["todayPrompts"] += 1 + stats["todayTotalTokens"] += total + today_tokens = stats["todayTokensByModel"] + today_tokens[model] = today_tokens.get(model, 0) + total + stats["todaySessions"] = len(today_sessions) + stats["totalSessions"] = len(sessions) + stats["activeDays"] = len(active_days) + stats["activeDates"] = sorted(active_days) + return stats, complete + + +def cached_scan(max_age_seconds: float) -> dict[str, Any]: + roots = session_roots() + try: + cache_file = cache_root() / "pi-sessions.json" + with cache_file.with_suffix(".lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + cached = read_cached_stats(cache_file, max_age_seconds, roots) + if cached is not None: + return cached + scan_date = local_date_string() + stats, complete = scan_sessions(roots) + try: + if complete: + write_json(cache_file, {"schemaVersion": 1, "scanDate": scan_date, + "roots": [str(root) for root in roots], "stats": stats}) + else: + cache_file.unlink(missing_ok=True) + except OSError as exc: + print(f"omarchy-agent-usage-pi: could not write usage cache ({exc})", file=sys.stderr) + try: + cache_file.unlink(missing_ok=True) + except OSError: + pass + return stats + except OSError as exc: + print(f"omarchy-agent-usage-pi: cache unavailable ({exc}); scanning directly", file=sys.stderr) + return scan_sessions(roots)[0] def main() -> int: @@ -232,7 +357,7 @@ def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--force", action="store_true") parser.add_argument("--limits-only", action="store_true") - parser.add_argument("--cache-seconds", type=float, default=20) + parser.add_argument("--cache-seconds", type=float, default=SCAN_REUSE_SECONDS) args = parser.parse_args() max_age = 0 if args.force else (LIMITS_ONLY_REUSE_SECONDS if args.limits_only else args.cache_seconds) @@ -245,23 +370,9 @@ def main() -> int: "updatedAt": dt.datetime.now(dt.timezone.utc).isoformat(), "ready": True, "hasLocalStats": True, + "tierLabel": "Local usage", } - if stats is not None: - record.update(stats) - else: - record.update({ - "todayPrompts": 0, - "todaySessions": 0, - "todayTotalTokens": 0, - "todayTokensByModel": {}, - "recentDays": [{"date": day, "messageCount": 0} for day in recent_date_strings()], - "modelUsage": {}, - "totalPrompts": 0, - "totalSessions": 0, - "activeDays": 0, - "activeDates": [], - }) - + record.update(stats) print(json.dumps(record, separators=(",", ":"), sort_keys=True)) return 0 diff --git a/shell/plugins/agents/README.md b/shell/plugins/agents/README.md index 51ad4e43c2d2..d655376a9c12 100644 --- a/shell/plugins/agents/README.md +++ b/shell/plugins/agents/README.md @@ -1,6 +1,6 @@ # Agents -One bar icon and one panel for every AI coding subscription on the machine. +One bar icon and one panel for AI coding subscriptions and local Pi/OMP usage on the machine. The panel is strictly a display: it watches the usage records that `omarchy-agent-usage-update` writes to `~/.local/state/omarchy/agents/usage/` and draws whatever appears there. `Panel.qml` owns the bar button and the @@ -53,8 +53,9 @@ light surfaces — and the bar glyph stands in when there is none. | Collector | Limits | Local stats | |---|---|---| | `claude` | Anthropic's OAuth usage endpoint (5-hour session + 7-day weekly) | `~/.claude/projects` transcripts, opencode sessions on an Anthropic provider, plus `stats-cache.json` and `history.jsonl` as fallback | -| `codex` | The Codex app-server RPC | native Codex CLI session files (plus pi and opencode sessions) | +| `codex` | The Codex app-server RPC | native Codex CLI session files and opencode sessions on an OpenAI provider | | `fireworks` | Estimated prepaid balance: configured funding minus rated account costs | Fireworks billing API, grouped by day and model for the last 30 days | +| `pi` | None; labeled Local usage | Pi and Oh My Pi assistant messages from every backend, with inherited fork responses counted once | Claude limits need a signed-in CLI; without credentials the panel says so and falls back to local stats only. A non-default Claude directory is honored via @@ -64,6 +65,10 @@ falls back to local stats only. A non-default Claude directory is honored via opencode stores in `~/.local/share/opencode/auth.json` when Fireworks is signed in there. +Pi scans `~/.pi/agent/sessions`, `~/.omp/agent/sessions`, existing `~/.pi/profiles/*/agent/sessions` and `~/.omp/profiles/*/agent/sessions`, and `PI_CODING_AGENT_DIR/sessions` and the explicit `PI_CODING_AGENT_SESSION_DIR` directory when configured. OMP's `PI_CONFIG_DIR` root and existing `$XDG_DATA_HOME/omp/sessions` and `$XDG_DATA_HOME/omp/profiles/*/sessions` are also included. Physical file aliases are counted once. Forks are deduplicated within their `parentSession` lineage using entry IDs and message fingerprints, not globally by Pi's short entry IDs; independent sessions remain separate. + +The Pi tab is local usage, not a subscription meter: it does not infer quota resets or costs from tokens. Today and the seven daily rows use local calendar dates; model totals cover all valid assistant usage still on disk. Prompt counts represent assistant responses, including tool-use turns. Invalid dates and negative, non-finite, or fractional token counters are skipped. Recent scans are cached for 20 seconds, or 15 minutes for `--limits-only`; `--force`, a different local date, or changed session roots triggers a fresh scan. The cache is optional and an empty forced scan clears old usage. + ### Fireworks balance The collector first asks the account's `:getBalance` endpoint for the real @@ -146,5 +151,5 @@ the same account synced from two machines is not counted twice. One caveat on "all-time": the Codex collector only reads native session files touched in the last 30 days, and Fireworks requests the last 30 days from its -billing API, so their totals and day counts cover that window. Claude's cover +billing API, so their totals and day counts cover that window. Claude and Pi cover every transcript still on disk. diff --git a/shell/plugins/agents/manifest.json b/shell/plugins/agents/manifest.json index 1743a7982141..f0c9f38fede7 100644 --- a/shell/plugins/agents/manifest.json +++ b/shell/plugins/agents/manifest.json @@ -5,7 +5,7 @@ "version": "1.0.0", "author": "Omarchy", "license": "MIT", - "description": "Claude Code, Codex, and Fireworks usage, limits, and pace in a native Omarchy bar panel.", + "description": "Claude Code, Codex, Fireworks, and Pi/OMP usage in a native Omarchy bar panel, with limits or balance when available.", "kinds": ["bar-widget"], "activation": "on-demand", "entryPoints": { @@ -13,7 +13,7 @@ }, "barWidget": { "displayName": "Agents", - "description": "One bar icon and one panel: rate-limit meters with pace, today, the last week, and the all-time model breakdown for every subscription.", + "description": "One bar icon and one panel: today, the last week, and the all-time model breakdown for every agent, with rate-limit meters when available.", "category": "AI", "aliases": ["agents", "model-usage"], "allowMultiple": false, diff --git a/test/shell.d/agent-usage-pi-scanner-test.sh b/test/shell.d/agent-usage-pi-scanner-test.sh index 70615f2f6a17..263918bbe107 100755 --- a/test/shell.d/agent-usage-pi-scanner-test.sh +++ b/test/shell.d/agent-usage-pi-scanner-test.sh @@ -1,7 +1,11 @@ #!/bin/bash +set -euo pipefail + source "$(dirname "$0")/base-test.sh" +unset PI_CODING_AGENT_DIR PI_CODING_AGENT_SESSION_DIR PI_CONFIG_DIR + require_command jq require_command python3 @@ -10,7 +14,7 @@ trap 'rm -rf "$TEST_HOME"' EXIT mkdir -p "$TEST_HOME/.pi/agent/sessions/project" "$TEST_HOME/.omp/agent/sessions/project" -timestamp="$(date +%Y-%m-%d)T12:00:00Z" +timestamp="$(date -u +%Y-%m-%dT%H:%M:%SZ)" cat >"$TEST_HOME/.pi/agent/sessions/project/pi.jsonl" < Date: Sat, 3 Oct 2026 01:40:56 +0000 Subject: [PATCH 3/3] Keep the upstream jq projection in the Codex limits test Co-Authored-By: Saurabh Suri --- test/shell.d/agent-usage-codex-scanner-test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/shell.d/agent-usage-codex-scanner-test.sh b/test/shell.d/agent-usage-codex-scanner-test.sh index 526ed8cd5b5a..f61f038a6891 100644 --- a/test/shell.d/agent-usage-codex-scanner-test.sh +++ b/test/shell.d/agent-usage-codex-scanner-test.sh @@ -618,7 +618,7 @@ result=$(HOME="$TEST_HOME" CODEX_HOME="$TEST_HOME/.codex" XDG_DATA_HOME="$TEST_H CODEX_ACCOUNT_READ_HANGS=1 CODEX_RATE_LIMITS='{"planType":"pro","primary":{"usedPercent":36,"windowDurationMins":10080}}' \ "$ROOT/bin/omarchy-agent-usage-codex" --limits-only) (( $(date +%s) - started < 4 )) || fail "Codex collector doesn't wait on account/read when the limits name the plan" -[[ $(jq -c '{tierLabel, usageStatusText, limits: [.limits[] | {label: .label, percent: .percent}]}' <<<"$result") == '{"tierLabel":"pro","usageStatusText":"","limits":[{"label":"Weekly (7-day)","percent":0.36}]}' ]] || +[[ $(jq -c '{tierLabel, usageStatusText, limits: [.limits[] | {label, percent}]}' <<<"$result") == '{"tierLabel":"pro","usageStatusText":"","limits":[{"label":"Weekly (7-day)","percent":0.36}]}' ]] || fail "Codex collector reads limits even when account/read never answers" "$result" pass "Codex collector reads limits even when account/read never answers"