TokenTrace

io.github.abhiyoheswaran1由 GitHub 账号 abhiyoheswaran1 发布v0.21.2更新于 Oct 24, 2026

Local-first AI CLI usage analytics for agents.

概览

AI 生成的概览

本地优先的 AI CLI 用量分析工具:扫描 Claude Code、Codex 等日志,向助手提供 token 数、成本、置信度与修复建议。

可以做什么
  • 在再次运行编码代理前用预检给出继续、谨慎或阻止的判断
  • 查看本地用量状态、能力清单与扫描健康状况
  • 通过证据链把指标追溯到源文件、解析器状态与模型价格
  • 列出未知成本的修复分组,并生成报告或摘要
  • 执行显式本地扫描,需传入 confirmLocalScan=true 才会读取用量文件并写入本地数据库
适用场景
适合在本机使用 Claude Code、Codex 等 AI 命令行工具,并希望助手在开始下一次高成本运行前核查 token 与成本证据、发现异常或未知成本缺口、判断本地用量数据是否可信的场景。
运行要求
通过 npx 以本地 stdio 进程运行 npm 包 tokentrace(命令 tokentrace mcp)。需要 Node.js 20 或更高版本;better-sqlite3 可能需要构建工具或联网下载预编译二进制。未声明云账号、API 密钥或环境变量。默认面向 macOS,仅限桌面端。
安装前请注意
扫描工具会读取 ~/.claude、~/.codex、~/.openai 等目录下的本地用量文件并写入本地 SQLite 数据库,需 confirmLocalScan=true。原始提示词默认隐藏,但会保存简短文本预览,设置中可开启保存完整消息内容。除非设置 TOKENTRACE_DISABLE_PRICE_REFRESH,否则可能下载公开的模型价格清单。成本数字为估算值,不应视为财务事实。

安装

在 SourceWeft 中

  1. 打开 控制台中的 TokenTrace,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

[TokenTrace logo]

TokenTrace CLI

Local-first AI CLI usage analytics for developers and coding agents.

TokenTrace answers one practical question before the next expensive AI CLI run: is your local usage evidence ready to trust? It scans local Claude Code, Codex, structured usage logs, and usage-shaped local databases, then labels token and cost data as exact, estimated, unknown, cached, or non-cache. The dashboard opens on Today, with direct paths into Sessions, Evidence, and Fix Data.

TokenTrace is designed for local development machines first, with macOS-oriented defaults. It does not require a cloud account and does not send telemetry or logs anywhere.

Website · Source

[TokenTrace Today dashboard]

What TokenTrace Helps You Do

  • Check readiness before another coding-agent run with tokentrace preflight --json or MCP get_preflight.
  • See today’s local cost, tokens, sessions, confidence, anomalies, and repair signals in one first screen.
  • Trace every important number back to local files, parser state, sessions, model rates, and confidence labels.
  • Fix missing cost data through a guided repair queue without uploading prompts or message bodies.

Start In Seconds

Run without installing:

bash
npx tokentrace

Or install globally:

bash
npm install -g tokentracetokentrace

The command starts the local dashboard, chooses an available localhost port starting at 3030, opens your default browser, and keeps the server running until you press Ctrl+C.

CLI commands:

bash
tokentrace              # Start local dashboardtokentrace serve        # Start local dashboardtokentrace serve --port 3210 --no-open                        # Start on a fixed port without opening a browsertokentrace agent --json # Print machine-readable agent discovery manifesttokentrace capabilities --json                        # Alias for agent discovery manifesttokentrace roadmap --json                        # Print release status handofftokentrace mcp          # Start the local stdio MCP servertokentrace scan         # Scan local AI CLI usage logstokentrace doctor --json                        # Inspect scan health and repair recommendationstokentrace preflight --json                        # Check readiness before another coding-agent runtokentrace evidence --json                        # Print metric evidence trails as JSONtokentrace repair --json                        # Print unknown-cost repair groups as JSONtokentrace digest --json                        # Print current-month local usage digesttokentrace digest --since yesterday                        # Print a scoped local usage digesttokentrace report --markdown                        # Print a deterministic Markdown reporttokentrace review --json                        # Print post-session scan and review movementtokentrace insights --json                        # Print local recommendations as JSONtokentrace status --json                        # Print local usage status as JSONtokentrace statusline claude                        # Render a Claude Code status line from stdintokentrace statusline claude --compact                        # Render a shorter Claude Code status linetokentrace statusline setup claude                        # Print Claude Code statusLine setup JSONtokentrace watch --session                        # Watch local usage status in a terminal splittokentrace watch --session --compact                        # Watch a compact live status linetokentrace pricing refresh                        # Refresh public model pricestokentrace run <cmd>    # Optional wrapper mode for command runtime diagnosticstokentrace reset        # Reset imported local datatokentrace reset --yes  # Reset without confirmationtokentrace --help       # Print helptokentrace --version    # Print version

For Coding Agents

Agents should start with the read-only discovery manifest:

bash
tokentrace agent --json

The alias below returns the same manifest:

bash
tokentrace capabilities --json

The manifest describes TokenTrace's local-first privacy model, safe JSON commands, common workflows, Claude Code status-line setup, Codex sidecar fallback, and guardrails such as never running tokentrace reset without explicit human approval. The discovery command does not scan files, initialize the database, or start the dashboard.

Package-level agent references are included for agents that inspect repository or npm package contents before invoking commands:

MCP-capable clients can start the local stdio server after installing or using the npm package:

bash
tokentrace mcp

Registry name: io.github.abhiyoheswaran1/tokentrace.

First MCP call for agents: get_agent_guide.

Self-test the local MCP entrypoint without scanning files:

bash
tokentrace mcp selftest --json

The MCP server exposes the same local-first surfaces as tools: capabilities, preflight, status, Scan Health, evidence, repair queue, reports, and an explicit scan tool. It does not scan files on startup, and its scan tool requires confirmLocalScan=true before reading local usage files or writing the local database.

Before starting another long coding-agent run, use preflight:

bash
tokentrace preflight --json

In MCP clients, call get_preflight for the same proceed, caution, or blocked decision with local scan freshness, confidence, guardrail, anomaly, and repair findings. Preflight does not scan files or inspect raw prompts.

When the local dashboard is already running, agents can fetch the same manifest over localhost:

bash
curl http://127.0.0.1:3030/api/agentcurl http://127.0.0.1:3030/api/capabilities

The Local Sources & Trust release handoff is also machine-readable:

bash
tokentrace roadmap --jsoncurl http://127.0.0.1:3030/api/roadmap

Run From Source

bash
npm installnpm run db:migratenpm run db:seednpm run dev

Open http://localhost:3000.

Useful source commands:

bash
npm run dev          # Start the Next.js dev servernpm run build        # Build the production appnpm run start        # Serve the production buildnpm run scan         # Scan default and configured foldersnpm run db:migrate   # Create/update local SQLite tablesnpm run db:seed      # Seed editable provider/model pricesnpm run screenshots:seed                    # Seed a guarded public-safe screenshot databasenpm run reset        # Clear imported data and scan historynpm test             # Run parser and cost testsnpm run verify       # Run Vitest, TypeScript, and ESLint checksnpm run package:test # Verify, build, and dry-run the npm packagenpm run package:inspect                    # Check package transparency guardrailsnpm run security:ioc                    # Scan lockfiles, workflows, and local AI-tool hooks for supply-chain IOCsnpm run smoke:packed                    # Inspect packed tarball and smoke test packed CLItokentrace roadmap --json                    # Inspect roadmap handoff, action recipes, and release status

Daily Loop And Trust

TokenTrace now organizes the product around the daily loop:

  1. Preflight: decide whether local evidence is ready before another agent run.
  2. Today: review cost, token, session, confidence, anomaly, and repair signals.
  3. Evidence: trace numbers back to source files, parser confidence, sessions, and model-rate state.
  4. Fix Data: resolve unknown cost, parser review, and model-rate gaps.
  5. Advanced: inspect Scan Health, Discovery, Parsers, Raw Data, Query, and Model Rates when you need the full diagnostic surface.

Trust surfaces include:

  • native structured usage log and Cursor-style chat export ingestion
  • Source Coverage in Scan Health for native, profile-assisted, fallback, and unsupported files
  • privacy-safe Evidence Packs as JSON or Markdown
  • local scan scheduling: manual, on-open, hourly, or daily
  • project/model/tool scoped guardrails with warning thresholds
  • Import Profile preview before saving matchers
  • saved report exports for weekly usage, source coverage, guardrails, unknown cost, high-cost sessions, and confidence trends
  • operating metadata export without raw usage records

Accuracy And Evidence

TokenTrace labels the trust level behind imported numbers:

  • exact provider token counts
  • tokenizer estimates for recognized OpenAI/Codex and Claude-family model names
  • simple estimates when only text-like content is available
  • source-provided costs from local SQLite histories
  • unknown cost repair groups when model, token, or rate evidence is missing

The dashboard surfaces a Data Confidence score on Today, Projects, Sessions, and Session Timeline pages. Scan Health also includes a supply-chain IOC check so package trust is visible in the product, not only in release scripts.

Public releases require maintainer approval. See docs/RELEASE_CHECKLIST.md before bumping versions, tagging, creating GitHub releases, or publishing npm.

In local development, the SQLite database defaults to .tokentrace/tokentrace.db. Override it with:

bash
TOKENTRACE_DB=/absolute/path/tokentrace.db npm run dev

Data Location

When installed from npm, TokenTrace stores runtime data outside the package folder:

  • macOS: ~/Library/Application Support/TokenTrace/
  • Linux: ~/.local/share/tokentrace/
  • Windows: %APPDATA%/TokenTrace/

The CLI sets TOKENTRACE_DB and DATABASE_URL automatically. You can override the base directory with:

bash
TOKENTRACE_HOME=/custom/path tokentrace

Where TokenTrace Looks

Default discovery checks these locations when present:

  • ~/.claude/
  • ~/.config/claude/
  • ~/.codex/
  • ~/.config/codex/
  • ~/.openai/
  • Project-level hidden folders such as .claude, .codex, .openai, and .ai in the directory where tokentrace was invoked
  • TokenTrace wrapper logs in the local app-data directory
  • Any custom folders configured in Settings

Use Settings to add custom folders, toggle raw message storage, and trigger scans. Use Scan Health, Discovery, Parsers, and Raw Data to inspect discovered files, parser decisions, warnings, failures, extracted metadata, and confidence levels.

Settings also supports optional local monthly usage guardrails. Set a cost limit, token limit, or both, and Today will show month-to-date progress from imported local CLI usage.

Sessions includes built-in and local saved views for recurring review paths: unknown cost, high-cost sessions, Claude/Codex this month, estimated tokens, guardrail review, and parser review. Open a session's Timeline link to see ordered interactions, model changes, token spikes, cache activity, tool calls, parser confidence, and unknown-cost events. Raw prompts and message bodies stay hidden by default.

Ingestion Architecture

TokenTrace's primary ingestion architecture is direct local filesystem ingestion:

  1. Discover local AI CLI artifacts.
  2. Parse supported formats through adapters.
  3. Normalize sessions, interactions, token usage, models, projects, and tool calls.
  4. Store normalized records locally in SQLite.
  5. Visualize analytics in the local dashboard.

TokenTrace does not use MITM proxies, packet sniffing, browser extensions, traffic interception, or cloud telemetry.

Each adapter detects compatibility, parses partial metadata where possible, and fails safely when a file format is unsupported. Imported interactions carry token confidence metadata:

  • exact
  • high-confidence estimate
  • low-confidence estimate
  • unknown

Exact and estimated token values are never mixed silently.

Optional Wrapper Mode

Filesystem ingestion is the primary product path. Wrapper mode is secondary and optional:

bash
tokentrace run claude-codetokentrace run codextokentrace run npm test

Wrapper mode launches the subprocess, measures duration, counts stdout/stderr bytes, detects structured JSON output when available, and writes a local JSONL diagnostic log under the app-data directory. It does not intercept network traffic.

Claude Code Status Line

Claude Code can run a local status-line command at the bottom of its terminal UI. TokenTrace supports that path directly:

bash
tokentrace statusline setup claude

Add the printed statusLine block to ~/.claude/settings.json. It points Claude Code at:

bash
tokentrace statusline claude

Claude Code sends session JSON to the command on stdin. TokenTrace reads the transcript path, model, context usage, and session cost, then prints one compact local line:

text
TokenTrace | Opus | ctx 7% | cost $0.1235 | processed 3.3K tokens | cache 2.0K | priced

Do not set the Claude Code statusLine.command to plain tokentrace. Plain tokentrace starts the dashboard, while tokentrace statusline claude prints exactly one status-line response.

[TokenTrace Claude Code status line]

You can also inspect the same local status outside Claude Code:

bash
tokentrace status --jsontokentrace watch --session

Daily reporting commands stay deterministic and local:

bash
tokentrace digest --since last-scantokentrace digest --since 2026-05-01 --jsontokentrace report --markdown --since yesterdaytokentrace review --json

Codex CLI status-line integration is intentionally deferred until its status-line and hook contracts are stable enough to support without fragile terminal output parsing. Use tokentrace watch --session --compact in a terminal split or tmux pane as the current fallback. See docs/CODEX_INTEGRATION_SPIKE.md for the current decision.

Screenshots

Dashboard views:

[TokenTrace Today dashboard]

[TokenTrace unknown cost evidence trail]

[TokenTrace Fix Data queue]

[TokenTrace Scan Health parser review]

CLI startup and help:

[TokenTrace CLI help]

Local scan output:

[TokenTrace scan command]

Optional wrapper diagnostics:

[TokenTrace wrapper command]

Privacy Model

  • All processing runs locally on your machine.
  • No external telemetry is included. Next.js telemetry is disabled by the CLI.
  • No cloud account is required.
  • Raw full prompts and responses are not stored by default.
  • TokenTrace stores short text previews for debugging and analytics context.
  • TokenTrace may download a public model-pricing manifest so cost estimates stay useful. It does not send usage logs, prompts, file paths, or analytics data with that request. Set TOKENTRACE_DISABLE_PRICE_REFRESH=1 to use only bundled prices.
  • Turn on Store raw message content in Settings only if you want full local message text preserved in SQLite.

Stop the server with Ctrl+C in the terminal where tokentrace is running.

Package Trust

  • The TokenTrace npm package has no preinstall, install, or postinstall scripts.
  • The published package ships readable application source and the compiled CLI runtime, not generated .next/server route bundles.
  • tokentrace serve prepares the local dashboard build in the user's TokenTrace app-data directory the first time it is needed.
  • npm run package:inspect fails if generated Next.js build output appears in the published tarball.
  • npm run security:ioc scans lockfiles, workflows, and local Claude/VS Code hook files for high-signal supply-chain compromise indicators.
  • Public npm publishing is configured through GitHub Actions Trusted Publishing and provenance from version tags.
  • Socket GitHub checks and ProjScan are used as release guardrails, alongside npm audit --audit-level=moderate.
  • npm run release:check fails when a gate command exits non-zero. The import graph is expected to remain free of circular dependencies; tests/import-boundaries.test.ts protects shared type/helper modules from importing higher-level orchestration barrels.
  • Release notes are published directly in GitHub Releases from the relevant changelog section, not as a link-only summary.

See SECURITY.md for the full security and privacy model.

Model Rates

Model prices change. TokenTrace ships with bundled public list prices and can refresh them from a public TokenTrace model-rate manifest. Manual edits made in Model Rates are preserved by future refreshes.

The bundled catalog includes common OpenAI, Anthropic, Google Gemini, xAI, DeepSeek, Mistral, and Cohere models, checked on May 8, 2026.

Seed sources:

Review and update rates in Model Rates before treating cost estimates as financial truth, especially if you use batch processing, priority/flex modes, data residency, long-context surcharges, subscriptions, or provider-specific discounts.

Refresh from the dashboard or from the CLI:

bash
tokentrace pricing refresh

Cost is calculated per interaction:

text
inputTokens * inputPricePer1M / 1,000,000+ outputTokens * outputPricePer1M / 1,000,000+ cacheReadTokens * cachedInputPricePer1M / 1,000,000+ cacheWriteTokens * cacheWritePricePer1M / 1,000,000

Cache read and cache write prices fall back to input price when a model has no separate cache rate. Anthropic seed rows use the 5-minute prompt cache write price by default. Rows are marked exact, estimated, or unknown depending on token availability and pricing configuration.

Supported Inputs

Adapters live under src/ingestion/adapters/:

  • claude-code.ts
  • codex-cli.ts
  • structured-usage-log.ts
  • cursor-chat.ts
  • sqlite-history.ts
  • generic-jsonl.ts
  • generic-json.ts
  • generic-log.ts

Formats for Claude Code and Codex CLI can vary across versions, so these adapters are defensive and best-effort. Unknown files fail safely and show warnings in the Raw Data page.

Support Matrix

TokenTrace keeps a visible support contract so daily scans are easier to trust:

SurfaceSupport levelNotes
Claude Code project transcriptsStablePrimary local CLI ingestion source.
Codex CLI session artifactsBest-effortParsed defensively while CLI formats evolve.
Structured usage JSONL/NDJSONStableLocal wrapper and team logs with session, model, token, and source-cost fields.
Cursor-style chat exportsBest-effortImports local editor chat/composer exports without storing raw prompt text by default.
Usage-shaped SQLite historiesBest-effortReads local databases that expose session, model, token, or cost-like columns.
Generic JSONL, JSON, and text logsBest-effortConservative usage-shaped records only.
Claude/Codex cache, plugin, todo, config, and support filesIgnoredTracked as non-usage files, not parser failures.
Editable model pricingStableLocal pricing rows drive costs and unknown-cost repair queues.
Claude Code status lineStableUses Claude Code's documented statusLine stdin contract.
Codex sticky status lineBest-effort fallbackUse tokentrace watch --session --compact in a split or tmux pane.
Desktop app scraping, browser extensions, proxying, packet capture, telemetryUnsupportedOutside TokenTrace's product boundary.

Extending Parsers

Example generic JSONL fixtures are in fixtures/generic-jsonl/.

The ingestion system is intentionally pluggable:

  1. Add an adapter implementing IngestionAdapter.
  2. Register it in src/ingestion/adapters/index.ts.
  3. Add parser tests under tests/.

Contributing

Contributions are welcome. See CONTRIBUTING.md for local setup, parser guidelines, pricing update notes, and the release policy.

Troubleshooting

prebuild-install deprecation warning during install

npm warn deprecated [email protected]: No longer maintained...

This is a transitive dependency of better-sqlite3 (the native SQLite driver TokenTrace uses to store local data). The warning is harmless — the install completes normally and TokenTrace runs as expected. It will go away once better-sqlite3 upstream migrates to a different prebuilt binary loader; there is nothing to fix on the TokenTrace side.

Native build errors on better-sqlite3

If the prebuilt binary cannot be downloaded (offline machine, restrictive proxy, unsupported Node ABI), better-sqlite3 will try to compile from source and may fail. Workarounds:

  • Ensure Node.js is a supported LTS (TokenTrace requires >= 20.0.0; Node 20 or 22 LTS is recommended).
  • Install build tools: Xcode Command Line Tools on macOS, build-essential and python3 on Linux, or the "Desktop development with C++" workload on Windows.
  • Retry the install with network access to github.com so the prebuilt binary can be fetched.

EBADENGINE warnings

These appear when your local Node version is older than the engines field of a transitive dependency. They are warnings, not errors. Upgrading to the latest Node LTS resolves them.

Known Limitations

  • Claude Code and Codex CLI log formats are inferred defensively and may need refinement with real sample logs.
  • Tokenizer-backed estimates are available for recognized OpenAI/Codex and Claude-family model names. Unrecognized text-only records still fall back to a conservative simple estimate.
  • SQLite-history ingestion expects usage-shaped local tables and skips arbitrary databases that do not expose session, model, token, or cost-like fields.
  • Seed prices are editable and should be verified manually for your account, region, and provider plan.

License

Open source by Abhi Yoheswaran. Released under the MIT License. See LICENSE.

Next Improvements

  • Expand first-class native adapters for more local AI tools and editor histories.
  • Add provider-specific tokenizer refinements where public tokenizer behavior is stable enough to label clearly.
  • Make Import Profile preview more interactive for teams with custom wrapper logs.
  • Stream scan progress into the UI for very large local folders.

来源:README.md,提交 39622df

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v0.21.2最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分