npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opencode-token-tracker-tui

v2.0.2

Published

Token usage and cost tracking for OpenCode 2 with CLI stats and a compact sidebar summary

Downloads

353

Readme

opencode-token-tracker-tui

面向 OpenCode 2 的 token 用量与成本追踪:服务端插件 + CLI 统计 + TUI sidebar 实时摘要。

English | 简体中文

本仓库是 tongsh6/opencode-token-tracker 的维护 fork,因原始包名在 npm 上已被占用,以 opencode-token-tracker-tui 重新发布。原作者与版权仍为 tongsh6(MIT,详见 LICENSE)。本 fork 由 EightDoor 维护。

你能得到什么

  • OpenCode 2 服务端插件:监听 session.step.ended、session.step.failed、session.status 事件,将每个可计费的 step 写入本地 JSONL 日志(含 model、provider、tokens、cost、timestamp)。
  • 配套 CLI:opencode-tokens 提供临时查询 —— today/week/month 汇总,按 model/agent/provider/daily/session 分组,成本趋势图,CSV/JSON 导出,定价诊断,config get/set/unset。
  • TUI sidebar 摘要:./tui 子路径导出一个轻量 block,追加到 OpenCode 2 的 sidebar(sidebar.content slot)。内容包含 today/week/month 三行(tokens、cost、messages)、今日 cache 命中率、今日 cost 最高的 5 个模型。不会触碰右侧 content 面板 —— 你的会话视图保持不变。

安装

npm 包名为 opencode-token-tracker-tui。OpenCode 2 会从一个 npm 安装中自动发现 ./tui 子路径。

{
  "$schema": "https://opencode.ai/config.json",
  "plugins": ["opencode-token-tracker-tui"]
}

重启 OpenCode,服务端追踪与 sidebar 摘要会同时激活。

这一步不会把 opencode-tokens CLI 安装到你的 shell PATH。如需 CLI 访问,请任选其一:

# 临时运行,无需安装
npx -y --package opencode-token-tracker-tui opencode-tokens today
npm exec --yes --package opencode-token-tracker-tui -- opencode-tokens today

# 全局安装
npm install -g opencode-token-tracker-tui
opencode-tokens today

数据保存位置

| 类型 | 路径 | | --- | --- | | 配置 | ~/.config/opencode/token-tracker.json | | Token 日志 | ~/.config/opencode/logs/token-tracker/tokens.jsonl |

可通过环境变量覆盖:TOKEN_TRACKER_CONFIG_FILE、TOKEN_TRACKER_LOG_FILE。

每条 JSONL 记录对应一次可计费 step:

{
  "type": "tokens",
  "sessionId": "ses_xxx",
  "messageId": "msg_xxx",
  "agent": "build",
  "model": "claude-opus-4.5",
  "provider": "github-copilot",
  "input": 1500,
  "output": 350,
  "reasoning": 0,
  "cacheRead": 5000,
  "cacheWrite": 0,
  "cost": 0.0234,
  "_ts": 1716000000000
}

TUI sidebar

TUI 插件只贡献一个 slot:append: "sidebar.content"。sidebar 内呈现的内容类似:

Token Tracker · 3s ago
────────────────────────────────────
today       1.20M tok   $4.2130    42 msgs
week        6.40M tok  $21.4520   188 msgs
month      22.10M tok  $74.3300   612 msgs

cache hit 78%
top models (today)
  1. claude-opus-4.5 $3.12 (74%)
  2. deepseek-chat   $0.55 (13%)
  3. gpt-5.2         $0.41 (10%)
  …+2 more — run `opencode-tokens today --by model`
  • 按 panel.refreshSeconds(默认 5s)周期刷新,并在每次 session.step.ended / session.step.failed 事件时立即刷新。
  • 配置中 panel.enabled: false 可关闭 sidebar,不影响服务端追踪与 CLI。
  • 插件不会调用 ui.panel.open —— 那会替换右侧 content 面板,覆盖你的会话视图。追加到 sidebar 才能保留其他内容。

预算控制

opencode-tokens budget
  Budget Status
  ══════════════════════════════════════════════════════════════════

  🟢 Daily
    $3.50 / $10.00  [███████░░░░░░░░░░░░░] 35%
    Remaining: $6.50

  🟡 Weekly
    $42.00 / $50.00  [████████████████░░░░] 84%
    Remaining: $8.00

  🟢 Monthly
    $120.00 / $200.00  [████████████░░░░░░░░] 60%
    Remaining: $80.00

  Legend: 🟢 OK  🟡 Warning (>80%)  🔴 Exceeded

在 ~/.config/opencode/token-tracker.json 中配置:

{
  "budget": {
    "daily": 10,
    "weekly": 50,
    "monthly": 200,
    "warnAt": 0.8
  }
}

预算仅为警告,不会阻断请求或中断会话。

CLI 统计

# 全量汇总
opencode-tokens

# today / week / month
opencode-tokens today
opencode-tokens week
opencode-tokens month

# 分组
opencode-tokens today --by model
opencode-tokens month --by provider
opencode-tokens --by daily
opencode-tokens today --by session
opencode-tokens today --by all

--by 可选:model、agent、provider、daily、session、all。

today --by model 示例:

  Today's Usage
  ──────────────────────────────────────────────────
  Total Tokens:           2.81M
    Input:                2.74M
    Output:               72.9K
    Reasoning:             7.1K
  Cache Read:            12.62M
  Total Cost:            $32.93
  Messages:                 230

  By Model
  ─────────────────────────────────────────────────────
  Model                Tokens        Cost    Msgs
  ---------------  ----------  ----------  ------
  claude-opus-4.5       2.70M      $32.93     206
  deepseek-chat         23.4K     $0.0025       6
  gpt-5.2               86.9K     $0.0000      18

趋势图

opencode-tokens trend                       # 30 天成本
opencode-tokens trend --days 7 --metric tokens
opencode-tokens trend --width 40            # 紧凑图

参数:--days N(默认 30)、--metric cost|tokens|messages(默认 cost)、--width W(默认 60)。

数据导出

opencode-tokens export                              # CSV 到 stdout
opencode-tokens export --format json --period month
opencode-tokens export --format csv --output usage.csv

参数:--format csv|json(默认 csv)、--period today|week|month|all(默认 all)、--output FILE。

配置管理

opencode-tokens config                            # 显示当前配置
opencode-tokens config set budget.daily 10        # 设置值
opencode-tokens config get budget.warnAt          # 读取值
opencode-tokens config unset budget.daily         # 恢复默认

config set 会校验输入值,写入磁盘前先备份已有配置到 token-tracker.json.bak。

定价诊断

opencode-tokens doctor     # 只读检查(配置、日志、定价回退)
opencode-tokens pricing    # 完整内置定价表
opencode-tokens models     # 你实际使用的模型 + 定价来源

models 会标记疑似零成本 provider(Copilot、Cursor、Ollama 等),便于追加正确的 provider 覆盖。

config init 把示例 JSON 输出到 stdout(适合管道)。config generate 把同样的内容写入 ~/.config/opencode/token-tracker.json,并预填疑似零成本 provider,覆盖前会备份已有配置。

配置参考

{
  "providers": {
    "github-copilot": { "input": 0, "output": 0 }
  },
  "models": {
    "my-custom-model": { "input": 1, "output": 2 },
    "deepseek/deepseek-v4-flash": {
      "openrouter":  { "input": 0.14, "output": 0.28, "cacheRead": 0.0028 },
      "siliconflow": { "input": 0.2,  "output": 0.4 }
    }
  },
  "budget": {
    "daily": 10,
    "weekly": 50,
    "monthly": 200,
    "warnAt": 0.8
  },
  "panel": {
    "enabled": true,
    "refreshSeconds": 5
  }
}

定价字段(USD / 1M tokens)

| 字段 | 含义 | | --- | --- | | input | 输入 / 提示 token | | output | 输出 / 补全 token | | cacheRead | 缓存命中 token(可选) | | cacheWrite | 缓存写入 token(可选) |

定价解析顺序(命中即止)

  1. providers[<provider>] 覆盖
  2. models[<model>] 精确匹配(用户配置)
  3. 内置定价表精确匹配
  4. 内置定价表部分匹配(key 最长优先)
  5. 用户 models 部分匹配(key 最长优先)
  6. 默认回退:$1 input / $4 output(每 1M)

精确用户配置优先于内置;宽泛用户部分匹配排在内置匹配之后,避免 "claude" 这类泛 key 意外覆盖精确的内置价格。

常见场景

| 场景 | 覆盖方式 | | --- | --- | | 订阅制(Copilot、Cursor) | Provider 覆盖:{ "input": 0, "output": 0 } | | 本地免费(Ollama、LM Studio) | Provider 覆盖:{ "input": 0, "output": 0 } | | 付费 provider 下的本地模型 | Model 覆盖:{ "input": 0, "output": 0 } |

内置定价支持的模型

| Provider | Models | | --- | --- | | Anthropic | Claude Opus 4.x、Sonnet 4 / 4.5、Haiku 4 / 4.5 | | OpenAI | GPT-5.x、GPT-4.1、GPT-4o、o1 / o3 / o4 | | DeepSeek | deepseek-chat、deepseek-reasoner、deepseek-v4-pro | | Google | Gemini 2.5 / 3 / 3.1 / 3.5 |

未知模型使用默认定价估算。执行 opencode-tokens models 可查看哪些模型正在 fallback。

准确性与限制

  • 成本均为估算值,由本地 token 日志及内置(或用户配置)的定价表计算得出。这可能与 Provider 官方账单存在差异 —— 例如使用促销额度、企业折扣或特定定价优惠时。
  • 预算提醒仅为警告,不会阻断 API 调用、节流请求或中断会话。
  • 订阅制 / 打包 / 本地 provider(Copilot、Cursor、Ollama、LM Studio)应在配置中覆写为 0。用 opencode-tokens models 来识别它们。
  • 定价数据时效性:内置表为手动维护。运行 opencode-tokens pricing 查看并在价格过时处追加覆盖。

开发

git clone https://github.com/EightDoor/opencode-token-tracker.git
cd opencode-token-tracker-tui
npm install
npm run build
npm test

# 真实本机 OpenCode CLI dogfood
node scripts/real-opencode-cli-smoke.mjs --use-temporary-link --model deepseek/deepseek-chat

dogfood 脚本仅在仓库内使用(不发布为 npm 命令),验证真实 opencode run 路径,运行结束后恢复临时 package link。

License

MIT © tongsh6(原作者与版权持有者)。

由 EightDoor 维护的 fork —— 使用相同 MIT 条款发布;任何再分发都必须保留原作者归属。完整文本见 LICENSE。

Related