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-usage-monitor

v3.1.0

Published

OpenCode v2 TUI sidebar plugin that displays API usage quotas for OpenAI, Z.AI (GLM), DeepSeek, and OpenCode Go providers

Readme

opencode-usage-monitor

English version

OpenCode TUI sidebar plugin, который показывает квоты и баланс OpenAI, Z.AI / GLM, DeepSeek и OpenCode Go без раскрытия provider credentials в UI.

Package Runtime Host License

| Поле | Значение | |---|---| | Статус | Активно поддерживаемый персональный OpenCode tool/plugin | | Тип | OpenCode TUI plugin / host extension | | Host app | OpenCode >=2.0.32; release smoke также проверен на текущей 2.1.2 | | Package | opencode-usage-monitor 3.1.0 | | Runtime | Bun >= 1.3.0 для локальной разработки | | Проверки maintainer | bun install --frozen-lockfile && bun run typecheck && bun run typecheck:host && bun test && bun run build:all && bun run verify:package |

Скриншоты

Plugin отображается внутри sidebar терминального UI OpenCode.

Collapsed sidebar view

Provider expanded view

Fully expanded view

Сводка

  • Показывает usage windows OpenAI ChatGPT, число доступных Codex reset credits и опционально ближайший срок их истечения.
  • Показывает quota windows Z.AI и GLM 5h/week/month со временем reset и опциональными деталями plan. Поддерживает enterprise/org coding plans через organization и project scoping.
  • Показывает баланс аккаунта DeepSeek в CNY с опциональной детализацией granted/topped-up.
  • Показывает usage windows OpenCode Go 5h/week/month со временем reset.
  • Стандартизирует provider output как explicit usage windows плюс typed provider-owned details; баланс DeepSeek отображается как balance detail, а не как fake reset window.
  • Находит credentials в OpenCode auth storage и поддерживаемых environment variables.
  • Редактирует secrets из error messages перед выводом в TUI.
  • Отклоняет raw provider attribute dumps в runtime snapshots; providers должны мапить safe attributes в ordered details.
  • Использует stale-data indicators и guarded refreshes, чтобы не запускать пересекающиеся API calls.
  • Поддерживает двухуровневое collapse/expand поведение: весь panel и детализация по provider.

Быстрый старт

opencode plugin add [email protected]

Установка

OpenCode v2

Установите release через v2 plugin manager:

opencode plugin add [email protected]

Эквивалентная явная конфигурация:

{
  "$schema": "https://opencode.ai/v2/cli.json",
  "plugins": ["[email protected]"]
}

Добавьте package один раз: в ~/.config/opencode/cli.json либо в v2-поле plugins файла opencode.json(c). Package экспортирует отдельные v2 server и TUI definitions.

Этот major не поддерживает OpenCode v1. Пользователям v1 нужно закрепить [email protected]; dual-runtime compatibility shim отсутствует.

Package для локальной разработки

bun add [email protected]

Локальный checkout

git clone https://github.com/Mark1708/opencode-usage-monitor.git
cd opencode-usage-monitor
bun install --frozen-lockfile
bun run build:all
bun run verify:package

Build создаёт server definition и TUI bundle в dist/; package verifier записывает release candidate в .artifacts/package.tgz. Root shims в репозитории намеренно отсутствуют.

Совместимость

| Компонент | Поддерживаемая версия | Источник | |---|---|---| | Host app | OpenCode >=2.0.32 (smoke на 2.0.32 и 2.1.2) | Release smoke contract | | Plugin API | @opencode/plugin 2.0.32 | dependency в package.json | | Theme API | @opencode/theme 2.0.32 | peer dependency в package.json | | TUI runtime | @opentui/core >=0.5.17, @opentui/solid >=0.5.17, solid-js 1.9.12 | peer dependencies в package.json | | Local runtime | Bun >=1.3.0 | engine в package.json | | TypeScript | ^5.5.0 | dev dependency в package.json |

Конфигурация

Version 2.0 поддерживает только versioned configuration contract. Legacy flat fields вроде show_openai, show_zai, show_deepseek и refresh_ms отклоняются с actionable configuration error в TUI вместо fallback-интерпретации.

Plugin сначала читает отдельный config-файл:

~/.config/opencode/usage-monitor.json

Минимальная полезная конфигурация:

{
  "version": 2,
  "providers": {
    "openai": {},
    "zai": {},
    "deepseek": {},
    "opencode-go": {}
  }
}

Полная документированная форма:

{
  "version": 2,
  "enabled": true,
  "keybindings": {
    "refresh_all": "<leader>q",
    "refresh_provider": null
  },
  "ui": {
    "width": 34,
    "symbols": "unicode",
    "panel_initial_state": "expanded",
    "provider_initial_state": "collapsed"
  },
  "refresh": {
    "mode": "automatic",
    "interval_ms": 300000,
    "timeout_ms": 15000,
    "stale_after_ms": 600000
  },
  "diagnostics": {
    "debug": false
  },
  "providers": {
    "openai": {
      "credential": { "source": "opencode", "entry": "openai" },
      "options": {
        "show_resets": true,
        "show_reset_expiry": false
      }
    },
    "zai": {
      "credential": { "source": "opencode", "entry": "zai-coding-plan" },
      "options": { "plan": "personal" }
    },
    "deepseek": {
      "credential": { "source": "opencode", "entry": "deepseek" }
    },
    "opencode-go": {
      "credential": { "source": "opencode", "entry": "opencode-go" }
    }
  }
}

Объект providers управляет provider activation. Наличие provider включает его; отсутствие отключает и предотвращает credential, cache и network work для этого provider. Provider-specific refresh policies намеренно не поддерживаются.

Альтернативно можно добавить секцию usage_monitor в oh-my-openagent.json. Значения из отдельного usage-monitor.json имеют приоритет.

Credentials

OpenAI

OpenAI показывает ChatGPT/Codex subscription quota windows из активного OpenCode OAuth credential, а не из OpenAI Platform API keys. Plugin вызывает v2 credential client и сохраняет только нормализованную проекцию access token, expiry и metadata.accountID/metadata.accountId, необходимую provider.

Plugin никогда не читает auth.json, не использует inactive credentials и не сохраняет refresh tokens, labels, произвольные metadata или raw host credential records. OPENAI_API_KEY и OPENAI_ADMIN_KEY не используются для subscription quota.

Число доступных Codex reset credits по умолчанию берётся из основного usage response. Чтобы скрыть его, задайте show_resets: false в providers.openai.options. Опция show_reset_expiry: true включает условный дополнительный request и показывает ближайший срок истечения доступного credit. Этот request выполняется только когда resets отображаются и доступен хотя бы один credit; при его ошибке usage windows и число resets остаются видимыми без expiry.

Z.AI и GLM

Plugin поддерживает Z.AI и Zhipu / GLM credentials из OpenCode auth storage или environment variables:

export ZAI_API_KEY="your-zai-key"
export ZAI_CODING_PLAN_API_KEY="your-coding-plan-key"
export ZHIPU_API_KEY="your-zhipu-key"
export ZHIPUAI_API_KEY="your-zhipuai-key"

Enterprise / organization coding plan

Enterprise (organization-scoped) GLM coding plans требуют organization id и project id. Когда оба значения заданы, plugin запрашивает {baseUrl}/api/monitor/usage/quota/limit?type=2 с headers Bigmodel-Organization и Bigmodel-Project; иначе используется personal plan endpoint.

Настройка в usage-monitor.json:

{
  "version": 2,
  "providers": {
    "zai": {
      "options": {
        "plan": "enterprise",
        "organization_id": "your-org-id",
        "project_id": "your-project-id"
      }
    }
  }
}

Или через environment variables, если provider options не заданы:

export ZHIPU_ORGANIZATION_ID="your-org-id"
export ZHIPU_PROJECT_ID="your-project-id"

DeepSeek

Plugin показывает баланс аккаунта DeepSeek в CNY из balance endpoint. Настройте API key через OpenCode auth storage или:

export DEEPSEEK_API_KEY="your-deepseek-key"

Balance row показывает общий CNY amount; раскрытие provider показывает granted (promotional) и topped-up (paid) breakdown.

OpenCode Go

OpenCode Go показывает rolling 5h, weekly и monthly usage через GET https://opencode.ai/zen/go/v1/usage. Сначала используется сохранённый OpenCode credential opencode-go. Для явного environment fallback задайте:

export OPENCODE_GO_API_KEY="your-opencode-go-key"

Endpoint read-only и используется клиентами OpenCode Go, но пока не документирован как стабильный public API. Изменение response contract может потребовать обновления plugin.

Использование

  • Нажмите на основной usage header, чтобы свернуть или раскрыть весь panel.
  • Нажмите на строки providers, чтобы независимо переключать provider details.
  • Используйте /usage-refresh или настроенный refresh keybind, по умолчанию <leader>q, для ручного refresh.
  • Runtime refreshes используют account-safe provider cache в /tmp/opencode-usage-monitor-v2/.
  • Render errors перехватываются и отображаются внутри error boundary.

Структура проекта

.
├── assets/                    # Local screenshots для README
├── dist/                      # Собранный package output
├── src/
│   ├── auth.ts                # OpenCode auth и environment credential discovery
│   ├── provider-cache.ts      # Account-safe provider cache
│   ├── runtime-config.ts      # Versioned runtime config parsing and validation
│   ├── credentials.ts         # Credential resolver for provider registrations
│   ├── index.ts               # OpenCode plugin entry
│   ├── refresh*.ts            # Runtime refresh coordinator modules
│   ├── sanitize.ts            # Helpers для secret redaction
│   ├── snapshot-validation.ts # Snapshot validation before publication/cache
│   ├── tui.ts                 # TUI plugin module
│   ├── providers/             # OpenAI, Z.AI / GLM, DeepSeek и OpenCode Go clients
│   └── views/                 # Helpers для TUI view rendering
├── package.json               # Package metadata, scripts, peer dependencies
├── tsconfig.json              # Strict TypeScript config
└── LICENSE

Устранение неполадок

  • Если OpenAI показывает auth missing, oauth missing, oauth expired или account id missing, выполните opencode providers login для OpenAI и проверьте, что OpenCode auth entry содержит non-expired OAuth openai.access, openai.accountId, openai.expires и openai.type: "oauth".
  • Если Z.AI показывает auth missing, настройте поддерживаемую Z.AI или Zhipu environment variable либо OpenCode auth entry.
  • Если Z.AI показывает partial на enterprise/org account, задайте providers.zai.options.organization_id и providers.zai.options.project_id или ZHIPU_ORGANIZATION_ID / ZHIPU_PROJECT_ID, чтобы использовался endpoint ?type=2.
  • Если DeepSeek показывает auth missing, задайте DEEPSEEK_API_KEY или активируйте DeepSeek credential в OpenCode.
  • Если OpenCode Go показывает auth missing, выполните /connect, выберите OpenCode Go и введите его API key либо задайте OPENCODE_GO_API_KEY.
  • Если panel показывает config error, мигрируйте usage-monitor.json на version: 2 shape и задайте хотя бы один provider в providers.
  • Если panel слишком широкий или узкий, измените ui.width в usage-monitor.json.
  • Если refresh выглядит устаревшим, уменьшите refresh.interval_ms или проверьте provider API connectivity.
  • Если build output отсутствует, выполните bun run build:all и проверьте наличие dist/index.js и dist/tui.js.
  • Если cached data выглядит устаревшей, проверьте /tmp/opencode-usage-monitor-v2/.

Ограничения / безопасность

  • Plugin читает локальные OpenCode auth metadata и поддерживаемые environment variables, но примеры в README используют только placeholders.
  • Secrets редактируются из rendered error messages до попадания в TUI.
  • Provider data зависит от доступности внешних API OpenAI, Z.AI, Zhipu, DeepSeek и OpenCode Go, а также от credential permissions.
  • Package является host extension; runtime-поведение зависит от совместимых OpenCode и OpenTUI APIs.

Статус

Активно поддерживаемый персональный OpenCode tool/plugin. Public issues и improvements приветствуются, но проект в первую очередь поддерживается под workflow автора.

Ссылки / лицензия