opencode-usage-insights 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +66 -542
  2. package/dist/core.d.ts +15 -1
  3. package/dist/gui-experimental.cjs +3 -3
  4. package/dist/index.d.ts +0 -47
  5. package/dist/index.js +1715 -1195
  6. package/dist/index.js.map +23 -16
  7. package/dist/line.d.ts +1 -0
  8. package/dist/panel-data.d.ts +8 -1
  9. package/dist/recorder.d.ts +1 -0
  10. package/dist/rpc.d.ts +4 -4
  11. package/dist/rpc.js +5 -5
  12. package/dist/rpc.js.map +3 -3
  13. package/dist/settings-client.d.ts +29 -0
  14. package/dist/settings-rpc.d.ts +746 -0
  15. package/dist/settings.d.ts +114 -0
  16. package/dist/sidebar.d.ts +3 -3
  17. package/dist/stats/aggregates.d.ts +15 -3
  18. package/dist/stats/constants.d.ts +7 -0
  19. package/dist/stats/db.d.ts +8 -128
  20. package/dist/stats/legacy.d.ts +25 -0
  21. package/dist/stats/maintenance.d.ts +1 -1
  22. package/dist/stats/migrate.d.ts +7 -0
  23. package/dist/stats/ndjson.d.ts +16 -0
  24. package/dist/stats/open.d.ts +15 -0
  25. package/dist/stats/paths.d.ts +5 -4
  26. package/dist/stats/queries.d.ts +25 -31
  27. package/dist/stats/records.d.ts +94 -0
  28. package/dist/stats/schema.d.ts +26 -0
  29. package/dist/stats-client.d.ts +9 -0
  30. package/dist/stats-worker.js +577 -352
  31. package/dist/stats-worker.js.map +17 -12
  32. package/dist/text.d.ts +2 -0
  33. package/dist/tui-settings.d.ts +18 -0
  34. package/dist/tui.d.ts +1 -57
  35. package/dist/tui.js +954 -144
  36. package/dist/tui.js.map +17 -13
  37. package/docs/cli.md +24 -0
  38. package/docs/configuration.md +108 -0
  39. package/docs/costs.md +44 -0
  40. package/docs/demo.md +94 -68
  41. package/docs/desktop.md +91 -0
  42. package/docs/images/desktop-overview-annotated.png +0 -0
  43. package/docs/images/desktop-overview.png +0 -0
  44. package/docs/images/desktop-settings.png +0 -0
  45. package/docs/images/desktop-turns-go-annotated.png +0 -0
  46. package/docs/images/desktop-turns.png +0 -0
  47. package/docs/images/line.png +0 -0
  48. package/docs/images/panel-cache.png +0 -0
  49. package/docs/images/panel-help.png +0 -0
  50. package/docs/images/panel-latency.png +0 -0
  51. package/docs/images/panel-overview.png +0 -0
  52. package/docs/images/panel-providers.png +0 -0
  53. package/docs/images/sidebar.png +0 -0
  54. package/docs/internals.md +87 -36
  55. package/docs/privacy.md +60 -0
  56. package/docs/tui.md +175 -0
  57. package/package.json +2 -1
package/README.md CHANGED
@@ -5,585 +5,109 @@
5
5
  [![Lint](https://img.shields.io/github/actions/workflow/status/hugobatista/opencode-usage-insights/lint.yml?label=Lint)](https://github.com/hugobatista/opencode-usage-insights/actions/workflows/lint.yml)
6
6
  [![npm](https://img.shields.io/npm/v/opencode-usage-insights.svg)](https://www.npmjs.com/package/opencode-usage-insights)
7
7
 
8
- **See what each turn costs.** OpenCode reports the cost of each request, but the
9
- TUI no longer shows it. This plugin puts cost back in view in the **TUI** and in
10
- **OpenCode Desktop**: a telemetry line after every turn, the session's running
11
- spend and turn history, and an interactive `/usage-insights` panel with charged cost,
12
- list-price estimates, tokens, prompt-cache reuse and latency.
8
+ **See what each turn costs.** OpenCode knows the price of every request; this
9
+ plugin keeps it in view. A telemetry line after each turn, the session's running
10
+ spend, and a `/usage-insights` panel for cost, tokens, prompt-cache reuse and
11
+ latency — in the TUI and in OpenCode Desktop.
13
12
 
14
- ![The telemetry line after a turn](docs/images/line.png)
15
-
16
- Everything stays in your OpenCode server: no prompts or responses are stored,
17
- and the plugin sends nothing to a third party. The Go view reads the usage
18
- limits the host already fetched from the OpenCode Console; the plugin never
19
- sees the API key. The TUI and Desktop both read the
20
- same recorder through an authenticated server RPC, so a client connected to a
21
- remote server shows that server's data.
22
-
23
- ## What it does
24
-
25
- - **The line** (`session.composer.top`): what the turn cost, the tokens and
26
- prompt cache behind it, when it ended, the gap since the previous prompt, the
27
- model and configured provider, and warnings when the prompt cache or the
28
- provider changed. It belongs to finished work, so it stays hidden while a
29
- turn is running.
30
- - **The `/usage-insights` panel**: ten views — `overview`, `models`,
31
- `providers`, `cache`, `periods`, `latency`, `sessions`, `turns`, `db`, `go` —
32
- over five ranges (`session`, `today`, `7d`, `30d`, `all`), with drill-downs,
33
- sorting, filters and remembered state. Keyboard-driven in the TUI; the same
34
- views with desktop controls in OpenCode Desktop. `/usage-insights models 7d`,
35
- `/usage-insights go`.
36
- - **The Desktop header badge and panels**: a spend badge in the session header,
37
- next to the peak/off-peak badge; clicking it opens **Turns insights**, the
38
- session history. **Usage insights** holds the ten views and opens from
39
- `/usage-insights`. The Desktop window never opens SQLite: the server's worker serves
40
- the panels and history over RPC.
41
- - **The TUI sidebar**: the session's spend and last turns, in the same buckets
42
- as the line — time, provider, wall duration, prompt volumes, then
43
- `hit · tok/s · cost`. When OpenCode Go is active, a compact block above the
44
- summary names the subscription and shows the 5-hour/weekly/monthly
45
- percentages, the monthly forecast and the renewal date. The duration is
46
- first request to last completion: tool waits inside the turn count, idle gaps
47
- do not.
48
- - **The record** (server): every step with tokens, charged cost, the list-price
49
- estimate for `$0`, timings, finish reason and provider/model IDs; prompts,
50
- lifecycle, compaction and `session.usage.recorded` events too.
51
- - **Portable data** (from a checkout): `bun run report --ndjson` exports the
52
- whole database, and `--import` merges it back on another machine.
53
- - **Observational by design**: the plugin never rewrites prompts, requests or
54
- responses, and a failure inside the recorder is swallowed — telemetry can
55
- never interrupt a session.
56
-
57
- ## Requirements
58
-
59
- - **OpenCode V2** (`>=2.4.2`). The Desktop GUI part uses the V2 GUI plugin API
60
- (`./gui-experimental`), introduced in the 2.4 line. The server and TUI parts
61
- run on the same server that records the sessions.
62
- - [Bun](https://bun.sh) to install dependencies (development only).
63
-
64
- | | |
65
- | --- | --- |
66
- | **OS** | Linux, macOS and Windows. The database lives in the per-user state directory of each (table below). `bun run check:platform` exercises the data layer on the host OS; CI runs the full suite, including the TUI render tests, on Linux. |
67
- | **Runtime** | Bun, the runtime OpenCode ships with. SQLite comes from `bun:sqlite`: there is no native module to build and nothing to compile on install. |
68
- | **Desktop** | OpenCode Desktop 2.4+. The GUI is one CommonJS bundle (`dist/gui-experimental.cjs`) that uses the app's shared Solid, Effect and OpenCode client modules; it never opens SQLite. |
69
-
70
- ## Install
71
-
72
- The plugin is published on npm as `opencode-usage-insights`.
13
+ ![Annotated Overview: turn spend, Usage insights, session totals and data coverage](docs/images/desktop-overview-annotated.png)
73
14
 
74
15
  ```sh
75
16
  opencode plugin add opencode-usage-insights
76
17
  ```
77
18
 
78
- This adds one entry to the global `opencode.json(c)`. That entry loads every
79
- part of the package: the server recorder and RPC, the TUI contributions, and the
80
- Desktop GUI. A TUI-only package goes in `~/.config/opencode/cli.json`; this
81
- plugin has a server part, so `opencode.json(c)` is enough.
82
-
83
- > **Desktop reads only `opencode.json(c)`.** If the plugin is in
84
- > `~/.config/opencode/cli.json`, move that entry to `opencode.json(c)` and
85
- > remove it from `cli.json`. One entry in `opencode.json(c)` covers the TUI and
86
- > the Desktop; keeping both loads the TUI part twice.
87
-
88
- If you prefer to edit the configuration yourself:
19
+ Restart OpenCode and send a prompt: the line appears above the composer.
20
+ `/usage-insights` opens the panel. Settings are shared by every TUI and Desktop
21
+ window connected to the server. Manual config and local checkout are in
22
+ [docs/configuration.md](docs/configuration.md#install).
89
23
 
90
- ```jsonc
91
- // ~/.config/opencode/opencode.jsonc
92
- {
93
- "$schema": "https://opencode.ai/config.json",
94
- "plugins": ["opencode-usage-insights"]
95
- }
96
- ```
24
+ ## What you get
97
25
 
98
- To pass [options](#configuration), use the object form:
26
+ - **Cost per turn and session.** What the host charged; list-price estimates,
27
+ marked `≈`, when a Go subscription covers a paid model.
28
+ - **Prompt cache, explained.** Reuse, expiry and the cache a provider switch
29
+ costs.
30
+ - **Latency you can compare.** TPS, request TPS and TTFT (p50/p90/p99) by model
31
+ and provider.
32
+ - **OpenCode Go allowance.** 5-hour, weekly and monthly meters, a monthly
33
+ forecast and the exact renewal time.
34
+ - **Ten views, five ranges.** Overview, models, providers, cache, periods,
35
+ latency, sessions, turns, database and Go — with drill-downs and filters.
36
+ - **Private by design.** SQLite on your server, no prompts or responses stored,
37
+ no third-party requests. TUI and Desktop, local or remote.
99
38
 
100
- ```jsonc
101
- {
102
- "plugins": [
103
- { "package": "opencode-usage-insights", "options": { "sidebarTurns": 8 } }
104
- ]
105
- }
106
- ```
39
+ ## See it in action
107
40
 
108
- Or register a local checkout. Point at the **package root**, not `src/`: the
109
- loader reads the package `exports`, which resolve the server, TUI, RPC and GUI
110
- parts. Build once before loading it, and rebuild after source changes:
41
+ ![Annotated Turns insights: Go forecast and renewal, request TPS/TTFT/spend and one line per turn](docs/images/desktop-turns-go-annotated.png)
111
42
 
112
- ```sh
113
- cd /home/you/code/projects/opencode-usage-insights
114
- bun install
115
- bun run build
116
- ```
43
+ *Turns insights: the Go forecast and renewal, the session rates, then one line
44
+ per turn with tokens, cache hit, TPS, TTFT and cost.*
117
45
 
118
- ```jsonc
119
- // ~/.config/opencode/opencode.jsonc
120
- { "plugins": [{ "package": "/home/you/code/projects/opencode-usage-insights" }] }
121
- ```
46
+ ![The TUI overview: steps, tokens, cache hit rate, TPS, TTFT and cost](docs/images/panel-overview.png)
122
47
 
123
- For GUI development, keep `bun run dev:gui` running in another terminal; each
124
- rebuild reloads the Desktop GUI in every window without restarting the server.
125
- Configuration changes reload on their own; after changing server or TUI source,
126
- restart the background service with `opencode service restart`. The host's own
127
- `/usage` command remains the place for the Console budget details; the plugin's
128
- command is `/usage-insights`.
48
+ *The TUI overview: cost, cache and rates at a glance.*
129
49
 
130
- Send a prompt to verify: the TUI line appears above the composer when the turn
131
- finishes, the Desktop badge appears in the session header, and `/usage-insights`
132
- (alias `/insights`) opens the panel.
50
+ [More screenshots →](docs/demo.md)
133
51
 
134
- ## The TUI line
52
+ ## The line
135
53
 
136
54
  ```text
137
55
  14:32:07 · Δ 3m12s · opencode-go/deepseek-v4.1-flash max · in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21 · sess in 2.1M (14.5M), cached 12.4M, out 88k, cost $1.90 · ⚠ cache expired (−11.7k)
138
56
  ```
139
57
 
140
- | Segment | Meaning |
141
- | --- | --- |
142
- | `14:32:07` | When the response ended (`completed`, else `streamed`, else `created`). |
143
- | `Δ 3m12s` | Time since the previous prompt of the same session. |
144
- | `opencode-go/deepseek-v4.1-flash max` | The identity of the turn: the configured provider the model ran through and the model (the variant as a trailing word; `fields.model`/`fields.variant` hide either). Yellow with `changed` when the provider differs from the previous prompt, `model changed` when only the model does. |
145
- | `in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21` | `in` is the uncached prompt; the parenthesised value is the whole prompt (only when different); `cached` its cached part; `out` generated tokens (visible + reasoning); `cost` the bill. Several steps read `3 steps · …` and report the last step's tokens (`latest`); cost sums the turn. `turnTotals: "sum"` sums every step. |
146
- | `cost $0.21` | Money, not tokens: a turn sums every step's cost whatever the token view shows. A cost of zero is left out, so a free model reads as free. `fields.cost: false` hides it. |
147
- | `cost ≈ $0.21` | A **list-price estimate**, not money charged. When the host reports `cost: 0` for a paid model (OpenCode 2.2.0+ with an OpenCode Go subscription), the plugin prices the step from the host's model list. A turn mixing covered and paid steps keeps both parts visible: `cost $0.12 + ≈ $3.40`. `pricing: "off"` hides estimates everywhere; `fields.cost: false` hides both. |
148
- | `sess in 2.1M (14.5M), cached 12.4M, out 88k, cost $1.90` | The session totals: tokens and charged money come from the host (including its compaction and title generations), and the list estimate comes from the steps the plugin recorded. A Go session reads `cost ≈ $3.40`; a session mixing charged and covered steps keeps both parts, `cost $0.12 + ≈ $3.40`. |
149
- | `⚠ cache expired (−11.7k)` | Yellow. The prompt cache read fell by that many tokens against a comparable previous step; `×N` when several steps in the turn lost cache. |
150
-
151
- The turn segment carries no label by default — the numbers are the turn's, and
152
- `sess` marks the session's; `labels.turn` (e.g. `"turn"`) brings a prefix back.
153
-
154
- `≈` marks a **list-price estimate**, never a charge. It appears when the host
155
- reports `$0` for a model the catalog still prices; a known free model has no
156
- estimate. The `sess` segment and historical views use the stored per-step
157
- estimate, so they agree across clients; a live turn uses the client's current
158
- catalog and can differ after a price change. The `db` view counts unpriced `$0`
159
- steps and can backfill them (`e` in the TUI, **Backfill** in the Desktop panel).
160
-
161
- A turn is every consecutive assistant step after a prompt. Compaction, shell,
162
- `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
163
- messages do. From a checkout, `bun run demo` prints one example per case,
164
- including the streaming one and both turn-total views.
165
-
166
- ## OpenCode Desktop
167
-
168
- The Desktop app loads the package's `./gui-experimental` bundle in every window.
169
- The GUI plugin API is experimental in the 2.4 line; the bundle is tested against
170
- OpenCode Desktop 2.4.2. The window is Electron/Chromium: it has no Bun, no
171
- `bun:sqlite` and no Node filesystem.
172
-
173
- If the plugin was already installed before it gained the GUI part, restart the
174
- background service once (`opencode service restart`) and reopen the Desktop
175
- window. The plugin inventory caches the package's parts; a config reload may
176
- reload the server entry without noticing the new `./gui-experimental` export.
177
-
178
- The recorder, the database and the worker stay in the server; the window reads
179
- them through the same RPC the TUI uses.
180
-
181
- ### The cost badge
182
-
183
- In the session header, next to the peak/off-peak badge, the usage insights badge
184
- shows the finished turn's spend (`$0.0210` or `≈$0.0210`):
185
-
186
- ```text
187
- $0.0210
188
- ```
189
-
190
- Hovering shows the full telemetry line. While a turn runs the badge shows the
191
- session's accumulated spend instead (`≈$1.90`) and returns to the turn's
192
- spend when it ends. Clicking it opens **Turns insights**. The `fields`, `labels`,
193
- `turnTotals` and `pricing` options apply to the line, badge tooltip and panel;
194
- `fields.cost: false` hides the badge, and `fields.session: false` keeps it
195
- hidden while a turn runs.
196
-
197
- ### Usage insights and Turns insights
198
-
199
- `/usage-insights` (and the hidden `/insights` alias) opens the **Usage
200
- insights** panel in the side region. It has the same ten views, five ranges,
201
- drill-downs, sorting and filters as the TUI, plus the database view's
202
- maintenance buttons. The Desktop view menu lists **OpenCode Go** immediately
203
- after **Overview**. The **Turns insights** tab shows the current session's
204
- history. `/usage-insights turns` opens the same history inside **Usage insights**,
205
- where the session/all-sessions scope is available. Both panels have the inverse shortcut: **Usage insights**
206
- has an **Open turns insights** footer button, and **Turns insights** has
207
- **Open usage insights**.
208
-
209
- The TUI's always-visible sidebar has no Desktop slot. The Desktop equivalents
210
- are:
211
-
212
- | Where | What it shows |
213
- | --- | --- |
214
- | Session header badge | The turn spend and the full line on hover; click opens Turns insights. |
215
- | Turns insights tab | The current session's complete history, with the same compact Go forecast block as the TUI sidebar. `/usage-insights turns` adds the session/all-sessions scope. |
216
- | Side panel `+` menu | **Usage insights** and **Turns insights** launchers. |
217
-
218
- The panel state is stored separately from the TUI: opening the Desktop panel
219
- does not move the TUI panel, and vice versa.
220
-
221
- ### The server side
222
-
223
- The server part registers the usage RPC and starts a **database worker**. The worker owns a read-only SQLite connection for the panel and the
224
- turn history, and opens a short write connection for `prune`, `wipe`, `vacuum`
225
- and `backfill`. Panel queries therefore never block the agent's event loop, and
226
- the TUI does not open SQLite either: it works against a local or a remote server.
227
-
228
- The worker starts lazily on the first usage request (the panel, the history or
229
- the header badge estimate). If it cannot start (for example in a development
230
- runtime), the server falls back to an in-process service and logs it; the
231
- plugin still works, but the fallback shares the server's event loop.
232
-
233
- ### Desktop options
234
-
235
- All options are in [Configuration](#configuration). The two security-relevant
236
- ones are `maintenance` (default `true`; set `false` on a server reachable from
237
- other machines) and `exposePaths` (default `false`; keeps the absolute database
238
- path out of the `db` view).
239
-
240
- ### Remote servers
241
-
242
- The TUI and Desktop call the RPC on the server that owns the session. A TUI
243
- connected to a remote server shows that server's usage; the Desktop GUI is
244
- loaded from its own background server, but the panel targets the session's
245
- server. The plugin's server part must be installed and enabled on that server.
246
- If it is not, the panel explains that usage data is unavailable.
247
-
248
- ## How costs are calculated
249
-
250
- **Charged money is never recalculated.** `steps.cost` is what the host reports.
251
- When it is `0` or missing and the model has a price in the host's model list, the
252
- plugin stores a **list-price estimate** in `steps.list_cost` (USD per 1M tokens).
253
- `≈` marks an estimate, never a charge.
254
-
255
- | Surface | Price source |
256
- | --- | --- |
257
- | Server recorder and backfill | `ctx.model.list()` |
258
- | Live line (TUI/Desktop) | `data.location.model.list(location)` |
259
- | Panel, sidebar, NDJSON, CLI | stored `steps.list_cost` |
260
- | `sess` segment | `SUM(list_cost)` over the RPC |
261
-
262
- The host resolves provider config/overrides. The plugin does not read
263
- `~/.cache/opencode/models.json`, does not use `opencode models` for prices, and
264
- makes no network call. `list_cost` is `NULL` for charged/unknown, `0` for a known
265
- free model, and positive for an estimate. An unknown or inapplicable price means
266
- no estimate; an all-zero price means free. The formula, context tiers and worked
267
- example are in [docs/internals.md](docs/internals.md#list-price-estimates).
268
-
269
- The host also reports compaction and title usage with no assistant step. It is
270
- stored in `usage`, keyed by the host event ID, and included in the overview,
271
- periods and sessions totals; it is not attributed to a model because the host
272
- record carries none. See [docs/internals.md](docs/internals.md#non-step-usage).
273
-
274
- The live line's turn estimate uses the client's current model list; the `sess`
275
- segment and historical views use the stored estimate, which freezes the price at
276
- recording time. If the plugin started mid-session, the estimate covers only the
277
- recorded steps; the charged total still follows the host. `pricing: "off"` hides
278
- estimates and disables the backfill without deleting data.
279
-
280
- | Situation | Line | Panel |
281
- | --- | --- | --- |
282
- | Charged | `cost $0.12` | `$0.12` |
283
- | Covered (host `0`, price known) | `cost ≈ $3.40` | `≈$3.40` |
284
- | Mixed | `cost $0.12 + ≈ $3.40` | `$0.12 + ≈ $3.40`; table `≈$3.52` |
285
- | Compaction/title | in the host `sess` total | overview `other`; session/period cost |
286
- | Known free / price unknown | cost omitted | `$0` |
287
-
288
- ## The TUI panel
289
-
290
- `/usage-insights [view] [range]` opens the panel (`/usage-insights` alone opens
291
- the last view, or `overview` over `all` the first time). While the panel is open
292
- it owns input, so the prompt cannot take the command again: `escape` closes it,
293
- `f` toggles full screen, and the palette entry (`ctrl+p` → "Usage insights")
294
- toggles it closed. With the composer focused, `/usage-insights` with no
295
- arguments also toggles it closed, and any argument — including an unknown token,
296
- which is ignored — keeps it open. `/usage` stays the host's native usage-limits
297
- dialog.
298
- There is no default key binding — the command is palette-only, so it never
299
- shadows a key you use.
300
-
301
- ![The /usage-insights providers view](docs/images/panel-providers.png)
302
-
303
- The view bar at the top names every view and brackets the active one; `?` opens
304
- a help overlay that repeats the keys and defines every number.
305
-
306
- ### Keys
307
-
308
- | Key | Does |
309
- | --- | --- |
310
- | `↑` `↓` / `j` `k` | Move the cursor; the row under it is highlighted. |
311
- | `pageup` `pagedown` / `home` `end` | Move by ten rows / to the first or last row. |
312
- | `enter` | Drill into the row: a model → the providers it ran through and their latency; a provider → the models it served and its latency; a session → its turns; a period → the providers of the period. In `db`, prune the steps recorded before the selected retention's cutoff date, or wipe every recorded step, session and event from the last row (asks first). |
313
- | `backspace` | Go back from a drill-down. |
314
- | `1`–`9` `0` / `[` `]` | Pick a view (`9` is `db`, `0` is `go`) / cycle views. |
315
- | `t` / `shift+t` | Next / previous range. |
316
- | `s` / `shift+s` | Cycle the sort column / reverse it. |
317
- | `b` | `periods` bucket: day → week → month. |
318
- | `a` | `turns` scope: this session ↔ every session. |
319
- | `m` `p` | Filter by model or by **provider** (a picker of the values actually observed). |
320
- | `x` | Clear the filters. |
321
- | `r` | Re-read the database; in `go`, refresh the live allowance. |
322
- | `e` | `db`: backfill list-price estimates for the `$0` steps that have none (asks first; uses today's model list). |
323
- | `v` | `db`: compact the file, giving the space of deleted rows back. |
324
- | `?` | Help overlay. |
325
- | `f` / `escape` | Full screen / close. |
326
-
327
- The view, range, sort, bucket, scope and filters are stored through the host's
328
- durable storage, so the panel reopens where it was left.
329
-
330
- ### Views
331
-
332
- | View | Answers |
333
- | --- | --- |
334
- | `overview` | Steps, sessions, prompts, `in`/`cached`/`write`/`out`, `hit`, cost (with an `other` row naming the compaction/title part), an activity sparkline, a `this session` block and a **data coverage** block (how many models and providers were observed, and how many steps lack a model or a completion — a zero elsewhere is only trustworthy when this is complete). |
335
- | `models` | Every model with its cache (`hit` and the per-step `hit p50`), tokens, cost, the **providers it ran through** and how often it switched model or provider — with the cache a provider switch cost. Cost is assistant steps only; `enter` opens the per-provider detail. |
336
- | `providers` | **Which configured provider ran each model**: one row per provider, with the models it served, steps, share, prompt, cached, `hit`, p50 throughput, wall time and cost. Cost is assistant steps only. `enter` lists every model it served. Steps recorded without a provider (a model that was never observed) are dimmed and cannot be drilled into. |
337
- | `cache` | Reuse by model, losses grouped by reason (`expired`, `compaction`, `unknown`), **cache survival against idle time**, reuse kept per provider, the observed TTL bounds (`hits up to` / `drops from`) and the most recent losses. |
338
- | `periods` | Day, week or month totals — steps, sessions, `in`, `cached`, `write`, `hit`, `out`, cost (including compaction/title usage) — with a sparkline per metric and a totals row. `enter` lists the providers of a period. |
339
- | `latency` | Wall time, streaming window and throughput as p50/p90/p99 overall and per model (per provider when a model is filtered). `n < 5` is dimmed. |
340
- | `sessions` | Each session with steps, prompts, tokens, `hit`, cost (including compaction/title usage, named on the detail line), its directory and how many models it used; subagent sessions are indented under their parent and rolled up. |
341
- | `turns` | The per-prompt history: one line per finished turn, rendered exactly like the live line. Cost is assistant steps only. `a` widens it to every session, titled. |
342
- | `db` | File name (full path with `exposePaths: true`), contents and age. The retention table lists `30`/`90`/`365`-day prunes with step counts and cutoff; `↑`/`↓` + `enter` prunes from a cutoff, and the row below the table wipes every recorded step, session and event (both ask first). `v` reclaims space. It counts `$0` steps without an estimate; `e` backfills at today's list price. |
343
- | `go` | Live **OpenCode Go** allowance: the 5-hour (`rolling`), weekly and monthly meters, their reset countdowns, and a forecast of the monthly percentage at its renewal from the cycle's average pace. It also names the exact renewal instant. Read by the client from the host's usage-limits endpoint; no database rows. The TUI sidebar and the Desktop Turns insights tab carry the compact form, and the Desktop view draws the current-versus-forecast bars. |
344
-
345
- The panel sums the stored per-step buckets over the selected range, so a number
346
- read in one place means the same in the other: `prompt` is everything the
347
- provider saw (`cached + fresh + writes`), `in` the uncached part, `hit` is
348
- `cached / prompt`, and `out` everything generated (visible output + reasoning).
349
- A `cost` cell marked `≈` includes list-price estimates for steps the host
350
- reported as `$0`; the overview and the sidebar keep a mixed total in two parts
351
- (`$0.12 + ≈ $3.40`) so charged money is never mistaken for the estimate.
352
-
353
- The identity of a step is the **configured provider** the model ran through —
354
- `opencode`, `opencode-go`, `deepseek`, whatever the provider is called in the
355
- OpenCode configuration — and the model itself. That is what every view groups
356
- by. A gateway may route a request to another operator, but that upstream is not
357
- observable, so it is not guessed. The same model through `deepseek` and through
358
- `opencode-go` is two rows, two caches and two latency profiles, and a switch
359
- between them forfeits the cache the previous one held (the switch counts and the
360
- cache losses in the `models` view count exactly that).
361
-
362
- `tps`/`wall`/`stream` are produced tokens per streaming second / request to
363
- completed step / request to the last chunk. The sidebar's turn header shows the
364
- turn's wall time — the first request to the last completed step, so any tool
365
- wait inside the turn counts — while its rate is only the streaming window. The
366
- sidebar's rate (per turn, and the session average on its totals) is the
367
- **weighted** one — produced tokens divided by the summed streaming windows — so
368
- it answers "how fast did this produce"; the `latency` view reports the p50 of
369
- the per-step rates instead, which answers "how fast is a typical step". A
370
- switch from one step to the next is not by itself a fault — moving to another
371
- model or provider is a deliberate choice — so the `models` view pairs the count
372
- with the cache the switch actually cost, which only a provider switch can: two
373
- models never share a cache to lose. The panel's `?` overlay defines every
374
- number in place.
375
-
376
- ### The Go forecast
377
-
378
- OpenCode 2.4 already has a native **Usage** dialog: the Desktop command
379
- **View usage** lists the Go rolling/weekly/monthly meters and the Console
380
- budgets; the TUI `/usage` dialog lists the Console budgets and the remaining
381
- allowance per model. The plugin's `go` view adds what that dialog does not
382
- show: the monthly **forecast**, the exact renewal instant, and a chart in the
383
- Desktop panel. `/usage` remains the host's command; the plugin command is
384
- `/usage-insights`.
385
-
386
- The forecast uses the average pace of the current monthly cycle:
387
-
388
- ```text
389
- start = monthly resetsAt - 1 calendar month (inferred)
390
- elapsed = now - start
391
- rate = percent / elapsedDays
392
- projected = percent + rate * remainingDays
393
- exhaustAt = now + (100 - percent) / rate
394
- ```
395
-
396
- It is a percentage projection, not a dollar amount or a token estimate. The
397
- host exposes whole-number percentages and the reset instant, but not the start
398
- of the cycle, so the start is inferred. When nothing has been used yet it reads
399
- `no monthly usage yet`; when the cycle is younger than 30 minutes it says it is
400
- too early to project. The `renews` line below the forecast is the exact
401
- `monthly.resetsAt` in local time, with its countdown.
58
+ Time, the gap since the previous prompt, the provider and model, the turn's
59
+ tokens and cost, the session totals, and a warning when the cache or provider
60
+ changed. A cost of `$0` is left out, so a free model reads as free. `≈` marks a
61
+ list-price estimate, never a charge. [Every segment →](docs/tui.md#the-line)
402
62
 
403
- The TUI sidebar and the Desktop **Turns insights** tab show the compact form:
63
+ ## Settings
404
64
 
405
- ```text
406
- OpenCode Go
407
- 5h 2% · week 9% · month 40%
408
- forecast ~77% at reset
409
- renews 15 Dec 22:06
410
- ```
411
-
412
- The values come from the host's local usage-limits endpoint. The plugin never
413
- reads the Console API key and makes no external request; `quota: "off"` hides
414
- the view, the TUI sidebar block and the Desktop Turns block, and stops the poll.
415
-
416
- The host payload names the meters but not the paid plan (Go, Go Plus or Go
417
- Teams); the UI therefore uses the provider display name or `quotaName`, and
418
- falls back to the full `OpenCode Go`. Set `quotaName` to your plan name if you
419
- want Go Plus/Teams reflected. The name line is shown above the numbers in both
420
- sidebars and in the `go` view header.
421
-
422
- ## Configuration
65
+ Shared by every TUI and Desktop window on the server. Open **Settings → Usage
66
+ insights** in the Desktop, or run `/insights-settings` in the TUI. [All settings
67
+ →](docs/configuration.md#settings)
423
68
 
424
- Options apply to all three parts (each side reads the ones it needs):
69
+ ## Documentation
425
70
 
426
- | Option | Default | Meaning |
427
- | --- | --- | --- |
428
- | `enabled` | `true` | `false` disables that side completely — no line, no panel, no recording. |
429
- | `db` | per-OS state path | SQLite path override, resolved by the **server**. The TUI and Desktop read it through the RPC and never open the file. |
430
- | `turnTotals` | `"latest"` | How the turn segment counts prompt usage: `latest` shows the prompt size the turn ended with; `sum` adds every step of the turn. |
431
- | `pricing` | `"auto"` | `"off"` disables list-price estimates everywhere: no new `list_cost` records, no `≈` on the line, badge, panel or sidebar, and no historical backfill. Charged money is unaffected. |
432
- | `sidebar` | `true` | TUI-only: show the session summary and the per-prompt history in the session sidebar. The Desktop history is the Turns insights tab. |
433
- | `sidebarTurns` | `8` | How many turns the TUI sidebar and the Desktop Turns insights tab show (`1`–`50`; values outside are clamped). |
434
- | `panel` | `true` | Show the `/usage-insights` statistics panel and its command in the TUI and Desktop. `false` keeps the line and the history. |
435
- | `quota` | `"auto"` | Client-side OpenCode Go allowance. `"off"` hides the `go` view, the TUI sidebar and Desktop Turns blocks, and makes no usage-limits request. |
436
- | `quotaName` | `"OpenCode Go"` | Full subscription label shown in the `go` view and compact blocks. Set `"OpenCode Go Plus"` (or your Go Teams/Plus name) when the plan is not the standard Go; the host usage payload does not carry `planType`. |
437
- | `maintenance` | `true` | Allow the RPC to prune, wipe, vacuum and backfill. Set `false` on servers reachable from other machines. |
438
- | `exposePaths` | `false` | Return the absolute database path in the `db` view; the default returns only the file name. |
439
- | `fields` | see below | Toggle line segments. |
440
- | `labels` | see below | Override line labels (the plugin is English-only by default). |
441
-
442
- ### Fields and labels
443
-
444
- ```jsonc
445
- {
446
- "options": {
447
- "fields": { "clock": true, "delta": true, "model": true, "variant": true, "turn": true, "session": true, "reasoning": false, "cost": true, "cacheExpiry": true },
448
- "turnTotals": "latest",
449
- "labels": { "delta": "Δ", "turn": "", "session": "sess", "step": "step", "steps": "steps", "input": "in", "cached": "cached", "output": "out", "reasoning": "reason", "cost": "cost", "estimate": "≈", "cacheExpired": "cache expired", "providerChanged": "changed", "modelChanged": "model changed" }
450
- }
451
- }
452
- ```
453
-
454
- `fields: { "clock": false, "delta": false, "session": false }` turns the line
455
- into a pure `provider/model · turn …` reading.
456
-
457
- ## Database and privacy
458
-
459
- The recorder writes to the per-user state directory:
460
-
461
- | OS | Path |
71
+ | | |
462
72
  | --- | --- |
463
- | Linux / other | `$XDG_STATE_HOME/opencode/opencode-usage-insights/usage.db` (default `~/.local/state/opencode/opencode-usage-insights/usage.db`) |
464
- | macOS | `~/Library/Application Support/opencode/opencode-usage-insights/usage.db` |
465
- | Windows | `%LOCALAPPDATA%\opencode\opencode-usage-insights\usage.db` |
466
-
467
- `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the `db`
468
- option overrides both. The file is private to the user: its directory is created
469
- `0700` and the file `0600` (POSIX), re-applied on every open. The TUI and the
470
- Desktop GUI never open the file. They call the usage RPC; the server's worker
471
- holds a read-only connection for the panel and the history, so a view can never
472
- write, migrate or take the recorder's lock. Prune, backfill and compact use a
473
- separate short-lived writer inside the worker. The server part applies schema
474
- migrations on open; after an upgrade, start it once before opening the panel if
475
- the file predates the new schema.
73
+ | [TUI line and panel](docs/tui.md) | Every segment, key, view and rate |
74
+ | [OpenCode Desktop](docs/desktop.md) | Badge, panels, settings, remote servers |
75
+ | [Settings and server policy](docs/configuration.md) | Shared settings, install variants, environment |
76
+ | [Costs and estimates](docs/costs.md) | Charged vs list-price, backfill, non-step usage |
77
+ | [Privacy and security](docs/privacy.md) | What is stored, database path, RPC surface |
78
+ | [CLI report](docs/cli.md) | `report`, JSON, NDJSON export/import |
79
+ | [Internals](docs/internals.md) | Schema, performance, testing |
476
80
 
477
- Per step the database holds tokens, charged cost, the list-price estimate when
478
- the host reported `$0`, timings, finish reason, the configured provider and the
479
- model it ran through, and the session title and working directory. **Prompts and
480
- responses are not stored**, and the plugin sends nothing to a third party; a
481
- remote client reads the server's data over the authenticated RPC. The schema,
482
- indexes, identity rules and security notes live in
483
- [docs/internals.md](docs/internals.md).
484
-
485
- ### Security and remote servers
486
-
487
- The usage RPC is served by the OpenCode server and inherits its authentication.
488
- It is not a new unauthenticated endpoint, but it is a new authenticated surface:
489
- any client that can call the server API can call it, and the RPC handler has no
490
- caller identity (`RpcCallContext` exposes only cancellation and declared
491
- errors). The plugin therefore applies least privilege at the surface:
492
-
493
- - **Read-only by default for queries.** `panel`, `turns`, `listCost`, `filters`
494
- and `dbInfo` run on the worker's read-only SQLite connection. The only writes
495
- are `prune`, `wipe`, `vacuum` and `backfill`, gated by `maintenance` and an
496
- explicit confirmation.
497
- - **No free-form access.** There is no SQL, path, import or export method. Inputs
498
- are validated by JSON Schema with closed objects, enums, length limits and
499
- numeric clamps; the service validates them again. SQL is parameterized.
500
- - **Minimal output.** The RPC returns usage metadata — session titles,
501
- directories, models, providers, tokens, costs and the database shape — never
502
- prompts or responses. Database paths are returned as a file name unless
503
- `exposePaths: true`.
504
- - **Availability.** The worker keeps panel queries off the server's event loop;
505
- the client queue is bounded while the worker is in use. Reads have a 10 s
506
- watchdog; maintenance gets five minutes. Generic errors are returned; details
507
- stay in the server log.
508
-
509
- For a server reachable from another machine, set `maintenance: false` unless you
510
- need the maintenance buttons there. The RPC is only as protected as the server:
511
- do not expose an OpenCode server without its password/auth. The usage database
512
- is per server user; every authenticated client on that server sees the same
513
- sessions and aggregates. If you need per-user or per-tenant isolation, do not
514
- expose the RPC until the database carries that dimension.
515
-
516
- ## CLI report
517
-
518
- From a checkout, the database can be read without opening the TUI:
519
-
520
- ```sh
521
- bun run report # overview over all time
522
- bun run report models 7d # one view, one range
523
- bun run report all # every view
524
- bun run report providers --model deepseek-v4.1-flash
525
- bun run report periods --granularity month
526
- bun run report models --provider opencode-go
527
- bun run report --no-estimates # charged money only, like pricing: "off"
528
- bun run report --json # raw rows and every analysis, for scripting
529
- bun run report --ndjson > backup.jsonl # export the whole database
530
- bun run report --import backup.jsonl # merge an export (idempotent)
531
- bun run report --help
532
- ```
81
+ ## Requirements
533
82
 
534
- The views come from the same `buildPanel` the TUI and the Desktop render, so the
535
- terminal and the panels never drift apart. Run this on the server that owns the
536
- database; it is the local CLI counterpart to the RPC. `--width`,
537
- `--granularity`, `--model`, `--provider`, `--sort` and `--asc` mirror what the
538
- panel's controls do.
83
+ - **OpenCode V2** `>=2.4.2`; OpenCode Desktop 2.4+ for the GUI part.
84
+ - **Bun** only for development. SQLite comes from `bun:sqlite`: nothing to
85
+ compile on install.
86
+ - Linux, macOS and Windows. The database lives in the per-user state directory.
539
87
 
540
88
  ## Development
541
89
 
542
90
  ```sh
543
91
  bun install
544
- bun run typecheck # server, TUI and the separate Desktop DOM typecheck
545
- bun run build # dist/index.js, tui.js, rpc.js, stats-worker.js, gui-experimental.cjs
546
- bun test # pure logic + database + TUI harness + worker/RPC tests
92
+ bun run typecheck
93
+ bun run build
94
+ bun test
547
95
  bun run check:package
548
- bun run bench # query budgets at 20k steps (--full for 120k)
549
- bun run check:platform
550
96
  bun run demo # print the line and every view from a seeded database
551
- bun run docs:images # re-render docs/images/*.png (needs ImageMagick)
552
- bun run dev:gui # vite build --watch for the Desktop part
97
+ bun run docs:images # re-render the TUI screenshots (needs ImageMagick)
98
+ bun run docs:annotate # add callouts to the Desktop/sidebar captures (needs Pillow)
99
+ bun run dev:gui # rebuild the Desktop part on change
553
100
  ```
554
101
 
555
- For the Desktop development loop, point the local plugin at the package root
556
- (built once) and keep `bun run dev:gui` running: each GUI rebuild reloads the
557
- bundle in every Desktop window. Server or TUI source changes still need
558
- `opencode service restart`.
559
-
560
- - `src/core.ts`, `src/line.ts`, `src/panel-data.ts` and `src/stats/` are pure:
561
- turn accounting, the host-shape adapter, the view models, and the database,
562
- queries and analysis layer. No host imports, so they are unit-testable without
563
- a TUI runtime.
564
- - `src/text.ts` — text hygiene and the token shape a provider id is validated
565
- against.
566
- - `src/recorder.ts` — the event-stream state machine that fills the database.
567
- - `src/quota.ts`, `src/quota-client.ts` — the OpenCode Go meter types, the
568
- monthly forecast, formatting, and the local usage-limits read. No Console
569
- credentials and no external request.
570
- - `src/rpc.ts`, `src/rpc-client.ts` — the shared RPC contract and its typed
571
- client wrapper.
572
- - `src/service.ts`, `src/stats-worker.ts`, `src/stats-client.ts` — the database
573
- service, the worker that runs it off the server's event loop, and the bounded
574
- server-side client with its in-process fallback.
575
- - `src/panel-build.ts`, `src/panel.tsx`, `src/sidebar.tsx` — server-side panel
576
- assembly, the TUI panel component, and the TUI sidebar contribution.
577
- - `src/gui.tsx`, `src/gui/` — the Desktop entry, header badge, panels, line
578
- helpers, CSS, icon and copy.
579
- - `src/index.ts`, `src/tui.tsx` — the server (recorder + RPC + worker) and TUI
580
- parts.
581
- - `scripts/` — the demo, report, bench, platform-check, package-check and
582
- documentation-image CLIs, plus the Bun/Vite build.
102
+ The pure layers (`src/core.ts`, `src/line.ts`, `src/panel-data.ts`, `src/stats/`)
103
+ have no host imports. The recorder is `src/recorder.ts`; the RPC, service and
104
+ worker are `src/rpc*.ts`, `src/service.ts`, `src/stats-worker.ts` and
105
+ `src/stats-client.ts`; the TUI is `src/tui.tsx`, `src/panel.tsx` and
106
+ `src/sidebar.tsx`; the Desktop is `src/gui.tsx` and `src/gui/`.
583
107
 
584
- See [CONTRIBUTING.md](CONTRIBUTING.md) for the ground rules and review
585
- expectations, and [docs/internals.md](docs/internals.md) for the database
586
- design, performance rules and how the clients are tested.
108
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the ground rules and
109
+ [docs/internals.md](docs/internals.md) for the schema, performance rules and
110
+ client tests.
587
111
 
588
112
  ## License
589
113