{"_id":"@ai-craft/tokentracker","name":"@ai-craft/tokentracker","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@ai-craft/tokentracker","version":"0.1.0","description":"See where your AI coding tokens go - by task, tool, model, and project","type":"module","main":"./cli.js","types":"./index.d.ts","exports":{".":{"import":"./index.js","types":"./index.d.ts"}},"bin":{"tokentracker":"cli.js"},"engines":{"node":">=22.0.0"},"license":"MIT","author":{"name":"AgentSeal","email":"hello@agentseal.org"},"keywords":["claude-code","cursor","codex","opencode","ai-coding","token-usage","cost-tracking","observability","developer-tools"],"publishConfig":{"access":"public"},"dependencies":{"chalk":"^5.4.1","commander":"^13.1.0","ink":"^7.0.0","react":"^19.2.5"},"devDependencies":{"@types/react":"^19.2.14"},"_id":"@ai-craft/tokentracker@0.1.0","_integrity":"sha512-MW1GCQ0aAG+ipXW1GMWeOEVnib6N+aW0wUutScCWNqlMxBl8QkcfAXkeM+mIB4KAKcwtQmP89Py6tqgET6ZT4Q==","_resolved":"/private/var/folders/_j/tzygz83s12v4rnxgchnxz55m0000gp/T/d94ae006ea5824b3d6f5d63f265d02b3/ai-craft-tokentracker-0.1.0.tgz","_from":"file:ai-craft-tokentracker-0.1.0.tgz","_nodeVersion":"22.14.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-MW1GCQ0aAG+ipXW1GMWeOEVnib6N+aW0wUutScCWNqlMxBl8QkcfAXkeM+mIB4KAKcwtQmP89Py6tqgET6ZT4Q==","shasum":"4efb2ef69f207f6402f34e53b8c6d197902d104c","tarball":"https://registry.npmjs.org/@ai-craft/tokentracker/-/tokentracker-0.1.0.tgz","fileCount":254,"unpackedSize":4715922,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDXN15y7lfjcXUJA6XFT9xzsS+EaOGrIhVYqI6sZgtIpAIgZD75wiVMisDrk0eFRNtizdeIKvAYIxmWbrBmmAD1Hhc="}]},"_npmUser":{"name":"volkz","email":"delacruzd93@gmail.com"},"directories":{},"maintainers":[{"name":"volkz","email":"delacruzd93@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/tokentracker_0.1.0_1784450393814_0.6680694793789579"},"_hasShrinkwrap":false}},"time":{"created":"2026-07-19T08:39:53.681Z","0.1.0":"2026-07-19T08:39:54.067Z","modified":"2026-07-19T08:39:54.263Z"},"maintainers":[{"name":"volkz","email":"delacruzd93@gmail.com"}],"description":"See where your AI coding tokens go - by task, tool, model, and project","keywords":["claude-code","cursor","codex","opencode","ai-coding","token-usage","cost-tracking","observability","developer-tools"],"author":{"name":"AgentSeal","email":"hello@agentseal.org"},"license":"MIT","readme":"<p align=\"center\">\n  <img src=\"https://cdn.jsdelivr.net/gh/getagentseal/tokentracker@main/assets/logo.png\" alt=\"TokenTracker\" width=\"120\" />\n</p>\n\n<h1 align=\"center\">TokenTracker</h1>\n\n<p align=\"center\">See where your AI coding tokens go.</p>\n\n<p align=\"center\">\n  <a href=\"https://www.npmjs.com/package/tokentracker\"><img src=\"https://img.shields.io/npm/v/tokentracker.svg\" alt=\"npm version\" /></a>\n  <a href=\"https://www.npmjs.com/package/tokentracker\"><img src=\"https://img.shields.io/npm/dt/tokentracker.svg\" alt=\"total downloads\" /></a>\n  <a href=\"https://github.com/getagentseal/tokentracker/blob/main/LICENSE\"><img src=\"https://img.shields.io/npm/l/tokentracker.svg\" alt=\"license\" /></a>\n  <a href=\"https://github.com/getagentseal/tokentracker\"><img src=\"https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg\" alt=\"node version\" /></a>\n  <a href=\"https://discord.gg/pJ2DMWvtAx\"><img src=\"https://img.shields.io/badge/discord-join-5865F2?logo=discord&logoColor=white\" alt=\"Discord\" /></a>\n</p>\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/getagentseal/tokentracker/main/assets/dashboard.jpg\" alt=\"TokenTracker TUI dashboard\" width=\"620\" />\n</p>\n\nBy task type, tool, model, MCP server, and project. Supports **Claude Code**, **Codex** (OpenAI), **Cursor**, **cursor-agent**, **OpenCode**, **Pi**, **[OMP](https://github.com/can1357/oh-my-pi)** (Oh My Pi), and **GitHub Copilot** with a provider plugin system. Tracks one-shot success rate per activity type so you can see where the AI nails it first try vs. burns tokens on edit/test/fix retries. Interactive TUI dashboard with gradient charts, responsive panels, and keyboard navigation. Native macOS menubar app in `mac/`. CSV/JSON export.\n\nWorks by reading session data directly from disk. No wrapper, no proxy, no API keys. Pricing from LiteLLM (auto-cached, all models supported).\n\n## Install\n\n```bash\nnpm install -g tokentracker\n```\n\nOr run without installing:\n\n```bash\nnpx tokentracker\n```\n\n### Requirements\n\n- Node.js 20+\n- Claude Code (`~/.claude/projects/`), Codex (`~/.codex/sessions/`), Cursor, OpenCode, Pi (`~/.pi/agent/sessions/`), OMP (`~/.omp/agent/sessions/`), and/or GitHub Copilot (`~/.copilot/session-state/`)\n- For Cursor/OpenCode support: `better-sqlite3` is installed automatically as an optional dependency\n\n## Usage\n\n```bash\ntokentracker                        # interactive dashboard (default: 7 days)\ntokentracker today                  # today's usage\ntokentracker month                  # this month's usage\ntokentracker report -p 30days       # rolling 30-day window\ntokentracker report -p all          # every recorded session\ntokentracker report --from 2026-04-01 --to 2026-04-10  # exact date range\ntokentracker report --format json   # full dashboard data as JSON\ntokentracker report --refresh 60    # auto-refresh every 60s (default: 30s)\ntokentracker status                 # compact one-liner (today + month)\ntokentracker status --format json\ntokentracker export                 # CSV with today, 7 days, 30 days\ntokentracker export -f json         # JSON export\ntokentracker optimize               # find waste, get copy-paste fixes\ntokentracker optimize -p week       # scope the scan to last 7 days\ntokentracker yield                  # track productive vs reverted/abandoned spend (experimental)\ntokentracker yield -p 30days        # yield analysis for last 30 days\ntokentracker top                    # live session monitor (active agents, burn rate, ctx%)\ntokentracker top --json             # JSON snapshot of active sessions\ntokentracker top --ports            # include live PortsPanel in the TUI\ntokentracker context                # show context usage breakdown (ring + category tray)\ntokentracker context --watch        # re-run every 5s; exits 2 if context was critical (≥90%)\ntokentracker context --watch 10     # re-run every 10s\ntokentracker context --json         # one-shot JSON output\ntokentracker ports                  # list orphan processes on non-privileged TCP ports\ntokentracker ports --json           # machine-readable port list\n```\n\nArrow keys switch between Today / 7 Days / 30 Days / Month / All Time. Press `q` to quit, `1` `2` `3` `4` `5` as shortcuts, `c` to open model comparison. The dashboard auto-refreshes every 30 seconds by default (`--refresh 0` to disable). The dashboard also shows average cost per session and the five most expensive sessions across all projects.\n\n### JSON output\n\n`report`, `today`, and `month` support `--format json` to output the full dashboard data as structured JSON to stdout:\n\n```bash\ntokentracker report --format json             # 7-day JSON report\ntokentracker today --format json              # today's data as JSON\ntokentracker month --format json              # this month as JSON\ntokentracker report -p 30days --format json   # 30-day window\n```\n\nThe JSON includes all dashboard panels: overview (cost, calls, sessions, cache hit %), daily breakdown, projects (with `avgCostPerSession`), models with token counts, activities with one-shot rates, core tools, MCP servers, and shell commands. Pipe to `jq` for filtering:\n\n```bash\ntokentracker report --format json | jq '.projects'\ntokentracker today --format json | jq '.overview.cost'\n```\n\nFor the lighter `status --format json` (today + month totals only) or file-based exports (`export -f json`), see above.\n\n## Providers\n\nTokenTracker auto-detects which AI coding tools you use. If multiple providers have session data on disk, press `p` in the dashboard to toggle between them.\n\n```bash\ntokentracker report                      # all providers combined (default)\ntokentracker report --provider claude    # Claude Code only\ntokentracker report --provider codex     # Codex only\ntokentracker report --provider cursor    # Cursor only\ntokentracker report --provider cursor-agent  # cursor-agent CLI only\ntokentracker report --provider opencode  # OpenCode only\ntokentracker report --provider pi        # Pi only\ntokentracker report --provider copilot   # GitHub Copilot only\ntokentracker report --provider omp        # OMP only\ntokentracker today --provider codex      # Codex today\ntokentracker export --provider claude    # export Claude data only\n```\n\nThe `--provider` flag works on all commands: `report`, `today`, `month`, `status`, `export`.\n\n### Project filtering\n\nFilter results by project name (case-insensitive substring match). Both flags are repeatable:\n\n```bash\ntokentracker report --project myapp                  # show only projects matching \"myapp\"\ntokentracker report --exclude myapp                  # show everything except \"myapp\"\ntokentracker report --exclude myapp --exclude tests  # exclude multiple projects\ntokentracker month --project api --project web       # include multiple projects\ntokentracker export --project inventory              # export only \"inventory\" project data\n```\n\nThe `--project` and `--exclude` flags work on all commands and can be combined with `--provider`.\n\n### Date range filtering\n\nBeyond the preset periods, specify an exact window with `--from` and `--to` (`YYYY-MM-DD`, local time):\n\n```bash\ntokentracker report --from 2026-04-01 --to 2026-04-10   # explicit window\ntokentracker report --from 2026-04-01                    # this date through today\ntokentracker report --to 2026-04-10                      # earliest data through this date\ntokentracker report --from 2026-04-01 --to 2026-04-10 --format json\n```\n\nEither flag alone is valid. Inverted or malformed dates exit with a clear error. In the TUI, the custom range sets the initial load only -- pressing `1`-`5` switches back to predefined periods.\n\n### Supported providers\n\n| Provider | Data location | Status |\n|----------|--------------|--------|\n| Claude Code | `~/.claude/projects/` | Supported |\n| Claude Desktop | `~/Library/Application Support/Claude/local-agent-mode-sessions/` | Supported |\n| Codex (OpenAI) | `~/.codex/sessions/` | Supported |\n| Cursor | `~/Library/Application Support/Cursor/User/globalStorage/state.vscdb` | Supported |\n| OpenCode | `~/.local/share/opencode/` (SQLite) | Supported |\n| Pi | `~/.pi/agent/sessions/` | Supported |\n| OMP | `~/.omp/agent/sessions/` | Supported |\n| GitHub Copilot | `~/.copilot/session-state/` | Supported (output tokens only) |\n| Amp | -- | Planned (provider plugin system) |\n\nCodex tool names are normalized to match Claude's conventions (`exec_command` shows as `Bash`, `read_file` as `Read`, etc.) so the activity classifier and tool breakdown work across providers.\n\nCursor reads token usage from its local SQLite database. Since Cursor's \"Auto\" mode hides the actual model used, costs are estimated using Sonnet pricing (labeled \"Auto (Sonnet est.)\" in the dashboard). The Cursor view shows a **Languages** panel (extracted from code blocks) instead of Core Tools/Shell/MCP panels, since Cursor does not log individual tool calls. First run on a large Cursor database may take up to a minute; results are cached and subsequent runs are instant.\n\nGitHub Copilot only logs output tokens in its session state, so Copilot cost rows sit below actual API cost. The model is tracked via `session.model_change` events; messages before the first model change are skipped to avoid silent misattribution.\n\n### Adding a provider\n\nThe provider plugin system makes adding a new provider a single file. Each provider implements session discovery, JSONL parsing, tool normalization, and model display names. See `src/providers/codex.ts` for an example.\n\n## Model aliases\n\nIf you see `$0.00` for some models, the model name reported by your provider doesn't match any entry in the LiteLLM pricing data. This commonly happens when using a proxy that rewrites model names.\n\nMap any model name to a canonical one:\n\n```bash\ntokentracker model-alias \"my-proxy-model\" \"claude-opus-4-6\"   # add alias\ntokentracker model-alias --list                                # show configured aliases\ntokentracker model-alias --remove \"my-proxy-model\"             # remove alias\n```\n\nAliases are stored in `~/.config/tokentracker/config.json` and applied at runtime before pricing lookup. The target name can be anything in the [LiteLLM model list](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json) or a canonical name from the fallback table (e.g. `claude-sonnet-4-6`, `claude-opus-4-5`, `gpt-4o`).\n\nBuilt-in aliases ship for known proxy model name variants (such as `anthropic--claude-4.6-opus`). User-configured aliases take precedence over built-ins.\n\n## Theme\n\nChange the dashboard color theme:\n\n```bash\ntokentracker theme                  # show current theme\ntokentracker theme default          # set theme to default\ntokentracker theme --list           # list available themes\n```\n\nTheme is stored in `~/.config/tokentracker/config.json`.\n\n## Currency\n\nBy default, costs are shown in USD. To display in a different currency:\n\n```bash\ntokentracker currency GBP          # set to British Pounds\ntokentracker currency AUD          # set to Australian Dollars\ntokentracker currency JPY          # set to Japanese Yen\ntokentracker currency              # show current setting\ntokentracker currency --reset      # back to USD\n```\n\nAny [ISO 4217 currency code](https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes) is supported (162 currencies). Exchange rates are fetched from [Frankfurter](https://www.frankfurter.app/) (European Central Bank data, free, no API key) and cached for 24 hours at `~/.cache/tokentracker/`. Config is stored at `~/.config/tokentracker/config.json`.\n\nThe currency setting applies everywhere: dashboard, status bar, menu bar widget, CSV/JSON exports, and JSON API output.\n\nThe menu bar widget includes a currency picker with 17 common currencies. For any currency not listed, use the CLI command above.\n\n## Plans (subscription tracking)\n\nIf you're on Claude Pro, Claude Max, or Cursor Pro, set your plan so the dashboard shows subscription-relative usage:\n\n```bash\ntokentracker plan set claude-max                                  # $200/month\ntokentracker plan set claude-pro                                  # $20/month\ntokentracker plan set cursor-pro                                  # $20/month\ntokentracker plan set custom --monthly-usd 150 --provider claude # custom\ntokentracker plan set none                                        # disable plan view\ntokentracker plan                                                 # show current\ntokentracker plan reset                                           # remove plan config\n```\n\nThe progress bar shows API-equivalent cost vs subscription price. Presets use publicly stated plan prices (as of April 2026); they do not model exact token allowances, because vendors do not publish precise consumer-plan limits.\n\n## Menu Bar\n\n<img src=\"https://cdn.jsdelivr.net/gh/getagentseal/tokentracker@main/assets/menubar-0.8.0.png\" alt=\"TokenTracker macOS menubar app\" width=\"420\" />\n\n```bash\nnpx tokentracker menubar\n```\n\nOne command: downloads the latest `.app`, installs into `~/Applications`, and launches it. Re-run with `--force` to reinstall. Native Swift + SwiftUI app lives in `mac/` (see `mac/README.md` for build details). The menubar icon always shows **today's spend** (so $0 is normal if you haven't used AI tools today). Click to open a popover with agent tabs, period switcher (Today / 7 Days / 30 Days / Month / All), Trend / Forecast / Pulse / Stats / Plan insights, activity and model breakdowns, optimize findings, and CSV/JSON export. Refreshes every 30 seconds.\n\n**Compact mode** shrinks the menubar item to fit the text, dropping decimals (e.g. `$110` instead of `$110.20`). Opt in with:\n\n```bash\ndefaults write org.agentseal.tokentracker-menubar TokenTrackerMenubarCompact -bool true\n```\n\nRelaunch the app to apply. To revert: `defaults delete org.agentseal.tokentracker-menubar TokenTrackerMenubarCompact`.\n\n## What it tracks\n\n**13 task categories** classified from tool usage patterns and user message keywords. No LLM calls, fully deterministic.\n\n| Category | What triggers it |\n|---|---|\n| Coding | Edit, Write tools |\n| Debugging | Error/fix keywords + tool usage |\n| Feature Dev | \"add\", \"create\", \"implement\" keywords |\n| Refactoring | \"refactor\", \"rename\", \"simplify\" |\n| Testing | pytest, vitest, jest in Bash |\n| Exploration | Read, Grep, WebSearch without edits |\n| Planning | EnterPlanMode, TaskCreate tools |\n| Delegation | Agent tool spawns |\n| Git Ops | git push/commit/merge in Bash |\n| Build/Deploy | npm build, docker, pm2 |\n| Brainstorming | \"brainstorm\", \"what if\", \"design\" |\n| Conversation | No tools, pure text exchange |\n| General | Skill tool, uncategorized |\n\n**Breakdowns**: daily cost chart, per-project, per-model (Opus/Sonnet/Haiku/GPT-5/GPT-4o/Gemini), per-activity with one-shot rate, core tools, shell commands, MCP servers.\n\n**One-shot rate**: For categories that involve code edits, TokenTracker detects edit/test/fix retry cycles (Edit -> Bash -> Edit patterns). The 1-shot column shows the percentage of edit turns that succeeded without retries. Coding at 90% means the AI got it right first try 9 out of 10 times.\n\n**Pricing**: Fetched from [LiteLLM](https://github.com/BerriAI/litellm) model prices (auto-cached 24h at `~/.cache/tokentracker/`). Handles input, output, cache write, cache read, and web search costs. Fast mode multiplier for Claude. Hardcoded fallbacks for all Claude and GPT-5 models to prevent fuzzy matching mispricing.\n\n## Reading the dashboard\n\nTokenTracker surfaces the data, you read the story. A few patterns worth knowing:\n\n| Signal you see | What it might mean |\n|---|---|\n| Cache hit < 80% | System prompt or context isn't stable, or caching not enabled |\n| Lots of `Read` calls per session | Agent re-reading same files, missing context |\n| Low 1-shot rate (Coding 30%) | Agent struggling with edits, retry loops |\n| Opus 4.6 dominating cost on small turns | Overpowered model for simple tasks |\n| `dispatch_agent` / `task` heavy | Sub-agent fan-out, expected or excessive |\n| No MCP usage shown | Either you don't use MCP servers, or your config is broken |\n| Bash dominated by `git status`, `ls` | Agent exploring instead of executing |\n| Conversation category dominant | Agent talking instead of doing |\n\nThese are starting points, not verdicts. A 60% cache hit on a single experimental session is fine. A persistent 60% cache hit across weeks of work is a config issue.\n\n## Optimize\n\nOnce you know what to look for, `tokentracker optimize` scans your sessions and your `~/.claude/` setup for the most common waste patterns and hands back exact, copy-paste fixes. It never writes to your files.\n\n<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/getagentseal/tokentracker/main/assets/optimize.jpg\" alt=\"TokenTracker optimize output\" width=\"720\" />\n</p>\n\n```bash\ntokentracker optimize                       # scan the last 30 days\ntokentracker optimize -p today              # today only\ntokentracker optimize -p week               # last 7 days\ntokentracker optimize --provider claude     # restrict to one provider\n```\n\n**What it detects**\n\n- Files Claude re-reads across sessions (same content, same context, over and over)\n- Low Read:Edit ratio (editing without reading leads to retries and wasted tokens)\n- Wasted bash output (uncapped `BASH_MAX_OUTPUT_LENGTH`, trailing noise)\n- Unused MCP servers still paying their tool-schema overhead every session\n- Ghost agents, skills, and slash commands defined in `~/.claude/` but never invoked\n- Bloated `CLAUDE.md` files (with `@-import` expansion counted)\n- Cache creation overhead and junk directory reads\n\nEach finding shows the estimated token and dollar savings plus a ready-to-paste fix: a `CLAUDE.md` line, an environment variable, or a `mv` command to archive unused items. Findings are ranked by urgency (impact weighted against observed waste) and rolled up into an A-F setup health grade. Repeat runs classify each finding as new, improving, or resolved against a 48-hour recent window.\n\nYou can also open it inline from the dashboard: press `o` when a finding count appears in the status bar, `b` to return.\n\n## Compare\n\nSide-by-side model comparison across any two models in your session data. Pick any pair and see how they stack up on real usage from your own sessions.\n\n```bash\ntokentracker compare                        # interactive model picker (default: all time)\ntokentracker compare -p week                # last 7 days\ntokentracker compare -p today               # today only\ntokentracker compare --provider claude      # Claude Code sessions only\n```\n\nOr press `c` in the dashboard to enter compare mode. Arrow keys switch periods, `b` to return.\n\n**Metrics compared**\n\n| Section | Metric | What it measures |\n|---------|--------|-----------------|\n| Performance | One-shot rate | Edits that succeed without retries |\n| Performance | Retry rate | Average retries per edit turn |\n| Performance | Self-correction | Turns where the model corrected its own mistake |\n| Efficiency | Cost / call | Average cost per API call |\n| Efficiency | Cost / edit | Average cost per edit turn |\n| Efficiency | Output tok / call | Average output tokens per call |\n| Efficiency | Cache hit rate | Proportion of input from cache |\n\n**Per-category one-shot rates.** Breaks down one-shot success by task category (Coding, Debugging, Feature Dev, etc.) so you can see where each model excels or struggles.\n\n**Working style.** Compares delegation rate (agent spawns), planning rate (TaskCreate, TaskUpdate, TodoWrite usage), average tools per turn, and fast mode usage.\n\nAll metrics are computed from your local session data. No LLM calls, fully deterministic.\n\n## Top (live session monitor)\n\nWatch active AI agent sessions in real time — token counts, burn rate, and context usage — in a unix-`top`-style TUI.\n\n```bash\ntokentracker top                    # live TUI — press q to quit\ntokentracker top --once             # render one snapshot and exit\ntokentracker top --json             # print JSON snapshot to stdout and exit\ntokentracker top --provider cursor  # filter to Cursor sessions only\ntokentracker top --refresh 5        # poll every 5s instead of adaptive default\n```\n\nThe TUI updates every 3 seconds when at least one session is live, and every 15 seconds otherwise (adaptive). Columns: STATUS (live / idle), PROJECT, MODEL, INPUT tokens, OUTPUT tokens, COST (USD), BURN/hr, CTX%.\n\n`--json` emits:\n```json\n{\n  \"sessions\": [{ \"sessionId\": \"...\", \"cwd\": \"...\", \"status\": \"live\", \"modelName\": \"...\",\n                 \"inputTokens\": 0, \"outputTokens\": 0, \"totalCostUsd\": 0,\n                 \"burnRateUsdPerHour\": 0, \"contextPct\": 0 }],\n  \"generatedAt\": \"2026-06-23T00:00:00.000Z\"\n}\n```\n\nA session is **live** if it received a token event within the last 10 minutes. Burn rate is computed over a rolling 30-minute window.\n\n## Context\n\nShow an 8-category context usage breakdown — system prompt, tools, rules, skills, MCP, subagents, summarized conversation, and conversation — with a fill ring colored by usage level.\n\n```bash\ntokentracker context                 # one-shot breakdown for the current project\ntokentracker context --project /path # scan a specific project directory\ntokentracker context --source claude # restrict to claude | agent-loop | all (default: all)\ntokentracker context --json          # output full ContextUsage object as JSON (one-shot, ignores --watch)\ntokentracker context --watch         # re-run every 5s (default interval)\ntokentracker context --watch 10      # re-run every 10s\n```\n\nThe ring color reflects usage level: yellow at ≥70% full, red at ≥90% (critical).\n\n**`--watch` exit codes**\n\n| Code | Meaning |\n|------|---------|\n| `0`  | Exited normally (Ctrl+C); context never reached critical (≥90%) during the session |\n| `2`  | Context crossed the critical threshold (≥90%) at least once during the watch session |\n\nExit code `2` makes `--watch` scriptable — wrap it in CI or a shell alias to alert when context is dangerously full. `--json` always exits `0` and ignores `--watch`.\n\n## Ports (orphan process detection)\n\nDetect processes listening on non-privileged TCP ports (`>1024`) — useful for spotting AI agent processes that are still running or occupying ports after a session ends.\n\n```bash\ntokentracker ports               # table: PID, port, command, working directory\ntokentracker ports --json        # machine-readable JSON array\n```\n\nThe `tt top` TUI also accepts `--ports` to show a live PortsPanel alongside the session list:\n\n```bash\ntokentracker top --ports\n```\n\nPort detection uses `lsof -nP -iTCP -sTCP:LISTEN` with a 5-second timeout. Ports ≤1024 are filtered out (system services). Gracefully degrades when `lsof` is unavailable or times out, and on Windows.\n\n## Yield (experimental)\n\nTrack whether your AI spend actually shipped to main or got reverted/abandoned.\n\n```bash\ntokentracker yield                  # last 7 days (default)\ntokentracker yield -p today         # today only\ntokentracker yield -p 30days        # last 30 days\ntokentracker yield -p month         # this calendar month\n```\n\nCorrelates AI sessions with git commits by timestamp. Sessions are categorized as:\n\n| Category | Meaning |\n|----------|---------|\n| Productive | Commits from this session landed in main |\n| Reverted | Commits were later reverted |\n| Abandoned | No commits near session, or commits never merged |\n\nRequires a git repository. Run from your project directory. Output shows cost and session count per category with percentages.\n\n## How it reads data\n\n**Claude Code** stores session transcripts as JSONL at `~/.claude/projects/<sanitized-path>/<session-id>.jsonl`. Each assistant entry contains model name, token usage (input, output, cache read, cache write), tool_use blocks, and timestamps.\n\n**Codex** stores sessions at `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` with `token_count` events containing per-call and cumulative token usage, and `function_call` entries for tool tracking.\n\n**Cursor** stores session data in a SQLite database at `~/Library/Application Support/Cursor/User/globalStorage/state.vscdb` (macOS), `~/.config/Cursor/User/globalStorage/state.vscdb` (Linux), or `%APPDATA%/Cursor/User/globalStorage/state.vscdb` (Windows). Token counts are in `cursorDiskKV` table entries with `bubbleId:` key prefix. Requires `better-sqlite3` (installed as optional dependency). Parsed results are cached at `~/.cache/tokentracker/cursor-results.json` and auto-invalidate when the database changes.\n\n**OpenCode** stores sessions in SQLite databases at `~/.local/share/opencode/opencode*.db`. TokenTracker queries the `session`, `message`, and `part` tables read-only, extracts token counts and tool usage, and recalculates cost using the LiteLLM pricing engine. Falls back to OpenCode's own cost field for models not in our pricing data. Subtask sessions (`parent_id IS NOT NULL`) are excluded to avoid double-counting. Supports multiple channel databases and respects `XDG_DATA_HOME`.\n\n**Pi / OMP** stores sessions as JSONL at `~/.pi/agent/sessions/<sanitized-cwd>/*.jsonl` (Pi) and `~/.omp/agent/sessions/<sanitized-cwd>/*.jsonl` (OMP). Each assistant message carries token usage (input, output, cacheRead, cacheWrite) plus inline `toolCall` content blocks. TokenTracker extracts token counts, normalizes tool names to the standard set (`bash` -> `Bash`, `dispatch_agent` -> `Agent`), and pulls bash commands from `toolCall.arguments.command` for the shell breakdown.\n\nTokenTracker reads these files, deduplicates messages (by API message ID for Claude, by cumulative token cross-check for Codex, by conversation/timestamp for Cursor, by session+message ID for OpenCode, by responseId for Pi/OMP), filters by date range per entry, and classifies each turn.\n\n## Environment variables\n\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_CONFIG_DIR` | Override Claude Code data directory (default: `~/.claude`) |\n| `CODEX_HOME` | Override Codex data directory (default: `~/.codex`) |\n\n## Project structure\n\n```\nsrc/\n  cli.ts          Commander.js entry point\n  dashboard.tsx   Ink TUI (React for terminals)\n  parser.ts       JSONL reader, dedup, date filter, provider orchestration\n  models.ts       LiteLLM pricing, cost calculation\n  classifier.ts   13-category task classifier\n  compare-stats.ts Model comparison engine (metrics, category breakdown, working style)\n  types.ts        Type definitions\n  format.ts       Text rendering (status bar)\n  menubar-json.ts Payload builder consumed by the native macOS menubar app in mac/\n  export.ts       CSV/JSON multi-period export\n  config.ts       Config file management (~/.config/tokentracker/)\n  currency.ts     Currency conversion, exchange rates, Intl formatting\n  dashboard/\n    theme.ts      Color theme definitions (DEFAULT_THEME, getTheme, THEMES)\n  live-sessions.ts Liveness logic (LIVE_THRESHOLD_MS, BURN_WINDOW_MS, buildTopSnapshot)\n  top.tsx         Ink TUI for tt top (live session monitor, adaptive refresh)\n  sqlite.ts       SQLite adapter (lazy-loads better-sqlite3)\n  cursor-cache.ts Cursor result cache (file-based, auto-invalidating)\n  providers/\n    types.ts      Provider interface definitions\n    index.ts      Provider registry (lazy-loads Cursor, OpenCode)\n    claude.ts     Claude Code session discovery\n    codex.ts      Codex session discovery and JSONL parsing\n    cursor.ts     Cursor SQLite parsing, language extraction\n    opencode.ts   OpenCode SQLite session discovery and parsing\n    pi.ts         Pi/OMP agent JSONL session discovery and parsing\n```\n\n## Star History\n\n<a href=\"https://www.star-history.com/?repos=getagentseal%2Ftokentracker&type=date&legend=top-left\">\n <picture>\n   <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://api.star-history.com/chart?repos=getagentseal/tokentracker&type=date&theme=dark&legend=top-left\" />\n   <source media=\"(prefers-color-scheme: light)\" srcset=\"https://api.star-history.com/chart?repos=getagentseal/tokentracker&type=date&legend=top-left\" />\n   <img alt=\"Star History Chart\" src=\"https://api.star-history.com/chart?repos=getagentseal/tokentracker&type=date&legend=top-left\" />\n </picture>\n</a>\n\n## License\n\nMIT\n\n## Credits\n\nInspired by [ccusage](https://github.com/ryoppippi/ccusage) and [CodexBar](https://github.com/nicklama/codexbar). Pricing data from [LiteLLM](https://github.com/BerriAI/litellm). Exchange rates from [Frankfurter](https://www.frankfurter.app/).\n\nBuilt by [AgentSeal](https://agentseal.org).\n","readmeFilename":"README.md","_rev":"1-176f57396ff4c1006db6223c7e87f39b"}