Skip to content

About

OpenCode 2 plugin for session-tree token usage, context window monitoring, estimated costs, and performance metrics (TPS, TTFT, run time).

Topics

Resources

Stars

10 stars

Watchers

0 watching

Forks

Repository files navigation

opencode-token-usage

Token usage, context window, estimated cost and live performance for OpenCode 2.

npm npm downloads OpenCode 2 CI MIT License

English | 简体中文

OpenCode Token Usage plugin preview

Installation

Requires OpenCode 2 and Node.js 22+. See Compatibility for verified host versions and the OpenTUI engine caveat.

opencode plugin add @chenlongapps/opencode-token-usage@latest

Overview

opencode-token-usage is a community plugin that brings token usage, context window occupancy, estimated cost and performance metrics into OpenCode 2's terminal interface.

Use it to see how many tokens a session and its subagents consume, how full the current context window is, and how estimated costs are distributed across models—without leaving your conversation.

Features

  • Session-tree totals: Track input, output, reasoning and cache tokens across the session tree, including unopened subagents, without double-counting inherited fork history.
  • Context visibility: See the viewed session's context usage, latest reported request and estimated prompt composition.
  • Estimated cost by model: Price recorded calls using their actual models, with one built-in official or reference price per model/SKU as a fallback. Estimates are not provider bills.
  • Performance at a glance: Monitor tokens per second (TPS), time to first token (TTFT) and the viewed session's own elapsed response time. TPS and elapsed-time estimates are marked with ~.
  • Native terminal UI: Keep a sidebar panel in the main session and a single-line summary in subagent views; open details only when needed.
  • On-demand details: Use /token-usage for compact or detailed statistics, including per-model usage and rates, without sending a prompt to the model.

Quick start

  1. View usage: Open a session. The Token Usage panel appears in the native sidebar when session.sidebar is set to auto and the terminal is wide enough.
  2. Explore details: Enter /token-usage or left-click the panel's Token Usage title. Press d to toggle compact/detailed mode and Escape to close. Opening details does not send a prompt to the model.
  3. Inspect subagents: In subagent views, click the live summary above the composer to open the full panel. Closing it does not interrupt the subagent.

For exact definitions and edge cases, see Detailed usage, Metrics and price sources and limitations.

Questions about setup, costs, subagents, reasoning speed or privacy? See the FAQ.

Other installation options

Instead of the command above, add the package to your project's opencode.json or opencode.jsonc:

{
  "$schema": "https://opencode.ai/config.json",
  "plugins": [
    "@chenlongapps/opencode-token-usage@latest"
  ]
}

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.

Compatibility

Requires Node.js 22+ (see the OpenTUI engine note under Development). With SDK 2.3.0, the full packaged integration suite has passed on the four pinned hosts: 2.0.28 (minimum), 2.1.4 and 2.2.7 (last stable release of each intervening minor line), and 2.3.0 (SDK-matched). CI also resolves the three newest stable npm hosts at run time (currently 2.4.1–2.4.3) and deduplicates them against the fixed set. Fixed hosts gate npm publication; latest-stable failures are reported separately and never block a release. Earlier SDK/release combinations were tested on 2.0.9–2.0.11, 2.0.22, 2.0.24, 2.0.26 and 2.1.2; those historical results do not establish compatibility with the current SDK. See the verification record for tested combinations and boundaries.

Since 0.4.24, the plugin uses /token-usage for details; /usage is reserved for OpenCode. Native first-token timestamps improve TTFT and historical TPS when available, with fallbacks for older hosts.

OpenCode 2.3.0 now passes the full suite, including plugin details alongside built-in /usage, native performance timing, history restoration, subagents, forks and compaction. The earlier 6,350 vs 5,080 mismatch was an outdated fixture assumption: background child completion triggers an additional parent model call. Smoke now independently reconciles totals against actual mock-provider requests.

Detailed usage

Enter /token-usage in a session or left-click the sidebar's Token Usage title to open the same centered native dialog with the session tree's token totals and estimated cost by recorded model. It opens in compact mode. Scroll with ↑/↓, Page Up/Down, Home/End, press d to switch between compact and detailed numbers and reveal model rates, and close with Escape or esc. Neither entry sends a prompt to the model. Other sidebar rows remain selectable; dragging to select text does not open the dialog.

The plugin command was renamed from /usage to /token-usage on all supported hosts to avoid OpenCode's built-in /usage command. The old name is not registered as an alias. The Token usage command-palette entry is also available.

The subagent picker keeps the summary in the form Token Usage · Context … · Total … · Cost … · Time … · TPS …. Time sums the viewed subagent's own native per-turn response durations; token totals and cost still cover the whole tree. Narrow terminals omit lower-priority fields, keeping Time visible when present without adding a second line. 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, TTFT and Run Time) without reserving space for the full panel while closed. When shown, Run Time is the last row in both the sidebar and this dialog.

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); a separate Run Time (this session) row sums only the viewed session's native per-turn response durations
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 Window requires reported usage and a valid active-model context limit. Last Request shows the selected assistant call's reported tokens even when that limit is unknown or source estimates are unavailable. Its timestamp comes from that same message: stream end, completion, then creation time, using the first valid value and hiding the timestamp if none is available. Request selection follows the viewed session's revert cutoff and most recent completed compaction boundary.

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. Its timestamp is the estimate's own capture time, which may refer to a different request than Last Request. 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
Run Time The viewed session's cumulative native per-turn response duration; while running, includes a display-only estimate of the current turn's elapsed time marked with ~; never adds child-session durations
TPS Tree-wide throughput from reported Output + Reasoning and OpenCode timing. While streaming, a valid estimate from delivered text, full reasoning traces and tool input (UTF-8 bytes / 4) takes precedence; provider-declared reasoning summaries are excluded. ~ marks only the live streaming estimate; completed historical TPS is a final value. TPS is hidden when unavailable
TTFT Average time to first token across measurable assistant steps in the tree, preferring OpenCode's native first-token timestamp

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.
  • Context only searches messages after the most recent compaction with status === "completed" and is hidden when reliable usage or a model context limit is unavailable.
  • Steps counts 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.
  • Run Time follows OpenCode 2.0.26's native response footer: assistant completion time minus the first user/synthetic input's creation time after the previous idle marker. A new session whose native time metadata records no previous idle uses the first input even before its first idle marker: synthetic deliveries and steers do not reset that turn. Older histories without idle markers use the nearest input; missing session metadata preserves this legacy fallback. Without any input, it uses the assistant's creation time. Each turn contributes only its final completed response duration, not the overlapping duration of every assistant step. Model calls, tools, retries and foreground waits within that span are included; idle time between turns is not. Waiting for a subagent is already part of the parent's span and is never added separately.
  • While the viewed session is running, Run Time estimates elapsed time so far, not final or remaining time, and prefixes the cumulative display with ~ (for example, ~42.5s). A shared 500 ms clock replaces the current turn's already-counted duration rather than adding an overlapping steer/retry duration. Clock ticks only update memory: history reads remain event-driven. One optional read-only server-plugin clock RPC at startup/reconnection supplies a server-time anchor, with timestamped live events as a fallback; local monotonic time advances it without assuming that a remote server shares the client's clock. Opening an already-running session restores the turn's start from history. A reconnect history refresh arriving before clock resynchronization keeps the last trusted display for the same retained open turn and unchanged historical subtotal, rather than dropping it to zero. Without a trusted anchor or valid timing, native totals remain unchanged.
  • Completion, failure or interruption stops projection; reported native completion timing replaces the estimate and removes ~, so a small downward correction is possible. Only native completed durations enter the historical subtotal. Totals use unrounded milliseconds before formatting (milliseconds below one second, one decimal below one minute, then minutes/hours), so they need not equal the sum of rounded footer labels. The existing message-history read restores totals after restarts, including sessions predating installation; no experimental execution-log API or server plugin is required. Missing historical timing data displays —, not zero. Read failures freeze the last displayed value and mark it Not updated (stale in the short summary).
  • Run Time / Time shows the duration and its estimate/freshness markers, without running-status text or animation. An idle parent's time never advances just because a child is active. Closing or switching views cleans up their estimates, and the shared elapsed-time ticker stops when no view needs it. Unavailable/stale timing keeps its own marker.
  • A confirmed zero Run Time / Time is hidden in the sidebar, subagent summary/dialog and both /token-usage modes, without leaving an empty row or field. A nonzero live estimate makes the first turn visible even before any response has completed. Nonzero millisecond durations, unavailable values and stale timing remain visible.
  • Runtime follows retained history: agent/model switches and compaction preserve past turns; fork copies never contribute to the fork's own time. A staged revert does not remove turns, but a committed revert deleting messages also removes their durations. Deleted historical timing cannot be reconstructed.
  • Est. Cost prices each message with its recorded model. Complete non-zero OpenCode prices take precedence. A verified Free SKU contributes the estimate at its paid counterpart's rate when that rate covers the call; By Model labels this Free usage reference, not a charge. Otherwise keep valid zero rates (except reviewed billing exceptions). Fallbacks replace the whole schedule without mixing rates or filling in missing categories.
  • The offline snapshot is generated from models.dev using verified LAB/model identities. It keeps one schedule per model or billing SKU: official non-zero prices first, then OpenRouter, Vercel AI Gateway, Amazon Bedrock and LLM Gateway in order, then the lowest other non-zero base Input + Output rate, and finally explicit zero prices. Reviewed overrides replace entire schedules. Free references are exact SKU links to existing rates, not duplicated quotes or guesses based on a suffix. No prices are downloaded or compared across providers at runtime.
  • Confirmed free usage displays $0.00; positive estimates below $0.001 display <$0.001, estimates through and including $0.01 use three decimal places, and larger estimates use two. Unavailable prices display —; known subtotals with unpriced messages are marked partial. 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 TPS merges deliveries within 100 ms and samples each response independently. The fast path keeps the 2s window, requires at least 80 UTF-8 bytes over the response and at least three batches spanning 500 ms in the window, and smooths by elapsed time. The first batch counts toward readiness but only sets the baseline; its bytes do not enter the speed calculation. OpenCode's provider-native metadata separates a full reasoning trace from an encrypted/redacted chain or provider thought summary; summary bytes never enter the response total, baseline, sampling window or smoothing. They still supply TTFT and activity, matching the previous TTFT behavior.
  • When the fast estimate is unavailable, the sparse fallback averages a contiguous span of up to 30s. It needs at least 12 UTF-8 bytes in that span (including the baseline) and at least three batches spanning 3s. The two most recent batch intervals must be at least 500 ms and within a factor of three of each other. A single batch of at least 80 bytes that contributes more than 75% of the measured bytes becomes a new baseline instead of producing a spike. Fast output takes priority again as soon as it qualifies, without inheriting the slow average.
  • A fast estimate expires after 2s of silence. Sparse estimates expire after three times the lower median of up to five recent qualifying intervals, bounded to 6–30s. A shared in-memory timeout uses a local monotonic clock for expiry and never reads history. Short fast expiry does not discard sparse candidates; expired slow samples and tool or retry boundaries require a fresh baseline without resetting response-wide byte counts or ending the step. Without a valid estimate the display uses historical TPS or hides it if unavailable. Positive estimates below 0.1 display as ~<0.1 tok/s.
  • Reconnection resets live TPS windows and reconciles all tracked sessions, including offscreen sessions, with the server's active-session set. Quiet unfinished streams get a shared activity check after 60s, without reading message history. Confirmed inactive streams and their TTFT observations expire after a further 60s. Running tools, retries and pre-first-token waits have no hard lifetime; failed activity reads retain state and retry. Provider streamed metadata alone never means that tools have finished. Checks stop when no unfinished streams remain.
  • Historical TPS divides the sum of Output + Reasoning by the sum of accepted assistant spans in seconds across the tree. A valid time.streamed − time.firstToken of at least 100 ms uses the same per-step span as the OpenCode footer when the step exposes a full reasoning trace (or has no reasoning). This measures throughput over the server-observed delivery span; it cannot recover the model's internal generation speed. Responses bursts, done-only content and transport buffering can compress delivery, and saved timestamps do not reveal batching within a longer span.
  • When the provider reports reasoning tokens but the step exposes only an encrypted/redacted chain, a reasoning summary, an unclassified reasoning trace, or no visible trace, TPS uses time.streamed − time.created even if the summary delivery span exceeds 100 ms. This includes hidden reasoning before the first visible token and measures effective request throughput. The same fallback applies when the native delivery span is shorter than one OpenCode delivery batch (100 ms), or the first-token timestamp is missing or invalid. Completed historical TPS is a final value and is not prefixed with ~; only live streaming estimates use that marker. Steps without usable timing contribute neither tokens nor time to TPS; with no usable steps, the TPS row is hidden. time.completed is not a fallback because it can include tool settlement. No model-specific multipliers or TPS caps are applied.
  • TTFT prefers native time.firstToken − time.created in history and session.step.first-token during streaming. A buffered delta cannot overwrite native timing. Older hosts fall back to the first nonempty text/reasoning/tool-input delta, or historical reasoning/tool creation times when measurable; text-only history without a native first-token timestamp has no recoverable TTFT. Native timing survives reopening and live-observation expiry. Retries reusing a message ID replace the previous attempt's sample. TTFT remains the average across measurable steps in the whole tree, whereas OpenCode's footer uses the first measurable step in the current turn, so multi-step/subagent values need not match.
  • Sidebar cumulative numbers (Steps, Input, Output, Reasoning, Cache Read, Cache Write, Total, Context used/limit/percent and Est. Cost) roll from the value already on screen to the new value. The first complete snapshot, newly appearing rows and session switches display directly; the final frame is exactly the reported value. This is display-only and changes no statistics, pricing, controller behavior or history reads. TPS, TTFT and Run Time are not tweened because they refresh every few hundred milliseconds and a 180 ms chase would lag continuously. Hosts whose OpenTUI has no frame-tick binding (OpenCode 2.0.x) show every value directly; only the roll is skipped.
  • Initial read failures display Unavailable. Later failures retain the last complete snapshot, display Not updated, and retry automatically.

Development

npm ci
npm run lint
npm run typecheck
npm test
npm run build
npm run test:smoke

Lint uses ESLint 10 Flat Config with the JavaScript/TypeScript recommended rules, without formatting or React rules. It covers source, tests, scripts, and root JavaScript files, excluding build output, dependencies, temporary directories, and the generated price snapshot. Use npm run lint:fix for supported automatic fixes. On Node 22, ESLint requires >=22.13; Node >=24 is also supported. This development-tool requirement does not change the plugin's Node.js 22+ runtime minimum.

For native TTFT/TPS checks on a host with time.firstToken, run npm run test:smoke -- --performance-only. This targeted lane verifies streaming timing, the native footer, the historical fallback for concentrated and done-only Responses delivery, and history restoration after reopening; it does not replace the full integration suite.

The OpenCode SDK packages are pinned to 2.3.0, with OpenTUI 0.8.4 and Solid/compiler 1.9.16. OpenTUI declares Node.js >=26.4.0 for its native Node runtime, so npm reports EBADENGINE on Node 22; engine-strict installations require a Node version meeting that dependency's engine requirement. The plugin's TUI runs inside OpenCode, not as a standalone Node 22 renderer. The project's Node.js 22+ minimum is unchanged; see the verification record for checks of this dependency set.

After CI passes on main, Auto release checks for a version bump and dispatches publish.yml with the exact CI commit and tarball. Every pinned-fixed OpenCode compatibility job tests that same tarball; the dynamically resolved latest-stable jobs report separately and are isolated from the publish gate. The publisher uses npm Trusted Publishing/OIDC, verifies the registry contents, and then confirms the vX.Y.Z tag and GitHub Release. An ordinary push does not publish. Retry an incomplete release with the original CI run or commit, without a new version bump. Normally you only need npm version patch --no-git-tag-version, commit, and push; see the release guide.

The price update workflow checks models.dev every 4 hours (or on demand via Run workflow on main). When the snapshot changes, it bumps the patch version, fast-forwards main with the snapshot and package files, and explicitly requests CI for that commit. The same CI and npm release gates apply. Incomplete price releases retry the original commit; unpublished manual releases defer price updates. GitHub Actions must be allowed to push to main and create tags, and npm must trust publish.yml with permission to run npm publish.

Failed validation never bumps the version. An unfinished tagged price release is retried with the same version before checking new prices; registry outages are not treated as missing versions. Publishing skips versions already on npm, prevents moving latest backwards, and polls registry visibility for up to 10 minutes after publication, logging progress. A verification timeout is not proof that npm publish failed: check the registry and retry the same tag without bumping the version; already-published versions are not republished. Exceptional LAB-to-Provider links, exact aliases and manual price overrides require review; ordinary new models no longer need allowlist entries. See the release guide for setup, verification timing, and retries.

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, /token-usage, sidebar title clicks, subagent aggregation, per-message pricing, first-party price fallback, model switching, TPS, TTFT, Responses summary bursts/done-only summaries/quiet expiry, and session-local native turn durations (unfinished responses, first-turn synthetic continuations, reopening a running TUI, terminal focus events, idle gaps, interruption, message-history restoration, forks and narrow child views) against an isolated OpenCode instance and local mock providers. On OpenCode 2.3+, it also checks that built-in /usage opens the host's own dialog. It requires Python 3, an available local port, and npm network access. It never modifies your existing OpenCode configuration or calls paid models. Terminal focus checks do not establish physical macOS multi-display, App Nap or sleep/wake behavior.

Performance lifecycle checks also use the real host's active-session API, with ending events withheld from an offscreen monitor, injected reconnect handshakes and an accelerated 25-hour tool/child wait. They verify preservation while running and reclamation after completion without history reads.

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.

CI configures full packaged smoke jobs for the fixed hosts 2.0.28, 2.1.4, 2.2.7 and 2.3.0, plus the three newest stable npm hosts resolved at run time. All jobs share one tarball, use isolated local mock providers, record the actually installed host version and upload per-version diagnostic artifacts. Fixed-host failures fail CI and block publication; latest-stable failures are non-blocking and summarized by compatibility-report. A scheduled Latest compatibility workflow checks the latest three stable hosts daily and can be dispatched manually; failures open or reuse a GitHub issue and appear as run annotations. Tree totals are checked against actual mock-provider requests: background child-completion notifications can trigger an additional parent call on newer hosts.

To reproduce a baseline with a separately installed binary, without downgrading your normal installation:

OPENCODE_BIN=/absolute/path/to/opencode-2.0.28 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

MIT

About

OpenCode 2 plugin for session-tree token usage, context window monitoring, estimated costs, and performance metrics (TPS, TTFT, run time).

Topics

Resources

Stars

10 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages