Token Usage
Session-tree token usage, live performance, context window and estimated cost for OpenCode 2
1
2,217
近 7 天 439
43.0
生态多维模型
1 天前
2026-10-03
快速安装与配置
opencode.json写入当前项目的 opencode.json,只对这个仓库生效。
opencode.json
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["@chenlongapps/opencode-token-usage@0.4.4"]
}写入 ~/.config/opencode/opencode.json,对所有项目生效。
~/.config/opencode/opencode.json
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["@chenlongapps/opencode-token-usage@0.4.4"]
}若你要在本地改造这个插件,先装到项目里再从本地路径引用。
shell
pnpm add -D @chenlongapps/opencode-token-usageOpenCode 启动时会通过内嵌运行时自动加载 npm 依赖并缓存至本地目录,无需手动在全局环境执行安装。
opencode-token-usage
A session-tree token usage monitor for OpenCode 2.
English | 简体中文
Installation
opencode plugin add @chenlongapps/opencode-token-usage
Alternatively, add the package to your project's opencode.json or opencode.jsonc:
{
"plugins": ["@chenlongapps/opencode-token-usage"]
}
[!NOTE] Requires Node.js 22+. OpenCode 2.0.9, 2.0.10, and 2.0.11 have been verified across project releases. The current SDK 2.0.11 build has been reverified on OpenCode 2.0.11 and 2.0.22.
Restart OpenCode after installation. The panel appears in the native sidebar when session.sidebar is set to auto and the terminal is wide enough. OpenCode hides the sidebar in subagent views, so the plugin keeps one live summary line above the composer with Context, Total, Cost, and TPS. Click the line to open the full statistics in a centered dialog. Press Escape or click esc to close it; closing the dialog does not interrupt the subagent.
For remote sessions, add the package name to plugins in your local ~/.config/opencode/cli.json to load only the terminal entry point. The configuration path follows XDG_CONFIG_HOME.
Detailed usage
Enter /usage in a session to open a native dialog with the session tree's token totals and estimated cost by recorded model. Scroll with ↑/↓, Page Up/Down, Home/End, press d to switch between compact and detailed numbers and reveal model rates, and close with Escape. The command does not send a prompt to the model.
The subagent picker keeps the summary in the form Token Usage · Context … · Total … · Cost … · TPS …. Missing values remain unavailable rather than becoming zero, and the line does not advertise a keyboard shortcut. Clicking it opens a smaller dialog with the sidebar's exact rows (including Steps, TPS and TTFT) without reserving space for the full panel while closed.
The dialog is split into five sections with separate statistics:
| Section | Contents |
|---|---|
| Context Window | Used / limit and a percentage of the active model's context limit, with a usage bar |
| Last Request | The five token categories and cache rate of the viewed session's most recent reported call |
| Context Breakdown | Estimated prompt composition, largest first, with bars |
| Session | Tree totals: steps, calls, tokens, cache rate, cost (single line, or per-category rows in detailed mode) |
| By Model | Tokens, calls and cost per recorded model, highest cost first; detailed mode shows the rates used for each model's cost estimate |
One line under the title names the session and its active model, and the body never repeats the model name. Compact mode uses K/M abbreviations (812, 139.4K, 3.70M), hides empty rows and merges the two tool families in Context Breakdown into a single Tools row. Detailed mode shows exact numbers, empty rows, and the System Tools / MCP Tools split. The sidebar keeps exact numbers and its own layout.
Costs follow the sidebar's pricing and partial/unavailable/free conventions. In detailed mode, By Model shows the applied Input, Output, Reasoning, Cache Read and Cache Write rates in USD per million text tokens. Each rate group names its source (OpenCode or the built-in snapshot), incoming-token tier and call count; a model can have multiple groups. Incoming means Input + Cache Read + Cache Write. Missing rates show —, confirmed free rates show $0.00, and unpriced calls are counted separately. These are the current rates used to estimate recorded calls, not historical provider bills. Context sections are unavailable until the viewed session has reported usage and a known context limit.
Context Breakdown separates Messages, System Tools, System Prompt, Skills, MCP Tools, and Other. It estimates the text and tool definitions in the viewed session's latest assembled model request; its percentages use the sum of those estimates. These are not provider-reported token counts and do not add up to the measured context window, which also includes output and reasoning. Media and provider-specific framing cannot be measured from the request. A server plugin records only aggregate estimates (not prompt text); sessions without a captured request or an available server RPC show “Source estimates unavailable”.
Metrics
| Metric | Definition |
|---|---|
Input |
Input tokens, excluding cache reads and writes |
Output |
Output tokens, excluding reasoning tokens |
Reasoning |
Reasoning tokens |
Cache Rate |
Cache Read ÷ (Input + Cache Read + Cache Write) |
Total |
Sum of all five token categories |
Context |
Latest context usage after the most recent completed compaction in the viewed session; not aggregated across the subtree |
Steps |
Assistant message count across the session tree, including subagents; follows OpenCode's own stats definition, so compaction and user messages are not steps |
Est. Cost |
Estimated cost across the tree, pricing each assistant and compaction call with its actual model |
TPS |
Generation throughput for Output + Reasoning across the tree. While streaming, it estimates recent observable text, reasoning-summary and tool-input deltas (UTF-8 bytes / 4) over a short sliding window after the first delta, excluding pre-first-token waiting, and marks the value with ~. APIs such as OpenAI Responses do not expose complete hidden reasoning tokens in real time, so live values cannot represent hidden reasoning throughput. After completion it uses provider-reported Output and Reasoning tokens and removes ~ |
TTFT |
Average time to first token across measurable assistant steps in the tree |
Behavior
- Usage includes server-reported assistant and compaction messages throughout the session tree, including unopened subagents. Token counts are never inferred from text length.
- A fork is a separate session tree. Inherited message copies are attributed only to their original source to prevent double counting.
Contextonly searches messages after the most recent compaction withstatus === "completed"and is hidden when reliable usage or a model context limit is unavailable.Stepscounts every assistant message in the tree, whether or not it reported usage, and reuses the fork-copy de-duplication so inherited history is never counted twice.Est. Costprices every message with its recorded model. A complete non-zero price resolved by OpenCode takes precedence. If OpenCode reports a complete zero price, a complete first-party snapshot price overrides it; incomplete prices fall back for the whole message without mixing rates.- The checked-in fallback snapshot is generated from models.dev using only reviewed first-party provider/model families; a small set of manufacturer-verified exceptions is kept separately. It covers priced text models, without downloading prices while the plugin runs. Gateway models match exact manufacturer IDs, documented aliases, and known wrappers; only a terminal
-freeor:freecan be removed for a second exact lookup. - Confirmed free usage displays
$0.00; unavailable prices display—; known subtotals with unpriced messages are markedpartial. The snapshot excludes gateway markups, regional premiums, unlisted discounts, non-text billing, tool fees, and taxes, so Est. Cost is not a provider bill. See price sources and limitations. - Live
TPSwith~is an estimate from recent observable deltas after the first delta over a ~2s sliding window with light smoothing; it excludes TTFT and hidden-reasoning waits. Without~it is exact provider-reportedOutput + Reasoningthroughput. No model-specific multipliers or hidden-reasoning guesses are applied. - Initial read failures display
Unavailable. Later failures retain the last complete snapshot, displayNot updated, and retry automatically.
Development
npm ci
npm run typecheck
npm test
npm run build
npm run test:smoke
The price update workflow checks models.dev every day at 03:17 UTC (or on demand via Run workflow). No snapshot diff means no pull request; a diff that passes typecheck, tests, build, and pack validation opens or updates one review-only PR containing src/prices.generated.ts. Enable Allow GitHub Actions to create and approve pull requests under repository Actions settings. PRs created with GITHUB_TOKEN do not trigger a second CI run, so the update workflow runs the checks before opening the PR. Nothing is merged or published automatically.
For a manual refresh, run npm run prices:update in a networked environment, review the generated diff and exceptions, then run the checks above. Builds and plugin refreshes do not contact models.dev.
test:smoke packages the real artifact and validates loading, refreshes, /usage, subagent aggregation, per-message pricing, first-party price fallback, model switching, TPS, and TTFT against an isolated OpenCode instance and a local mock provider. It requires Python 3, an available local port, and npm network access. It never modifies your existing OpenCode configuration or calls paid models.
By default, smoke uses opencode from PATH. Stable OpenCode 2 versions from 2.0.9 onward can run; a host not yet verified with the current SDK prints a warning and continues through the actual compatibility checks. Passing the version check alone does not establish compatibility. The SDK dependencies remain pinned independently of your local CLI updates.
To reproduce a baseline with a separately installed binary, without downgrading your normal installation:
OPENCODE_BIN=/absolute/path/to/opencode-2.0.11 npm run test:smoke
OPENCODE_BIN selects the same executable for the version check, isolated server, and TUI. Relative paths resolve from the directory where you run the command. The host version and selected binary are recorded in the smoke output and result.json; see the verification record for tested combinations.
To load the plugin from source, build the project and add the repository's absolute path to plugins in the target project.
Documentation
The implementation follows OpenCode's TokenUsage schema, cost calculation, and fork history projection.
Disclaimer
This is an independent community plugin. It is not built, maintained, or endorsed by the OpenCode team.
License
同类生态推荐
Okf Context
opencode-okf-context
OpenCode plugin: progressive disclosure + auto-unload for OKF (Open Knowledge Format) knowledge bundles. Inspired by DCP's outbound-only context transformation.
Total Session Cost
opencode-total-session-cost
Real-time cumulative cost tracker for Opencode sessions, aggregating costs from parent sessions, archived messages, and all child sub-agent tasks.
Oc Usage
@taraksh011/oc-usage
OpenCode plugin — live token usage, cost, and TPS display
