opencode-usage-insights 0.3.1 → 0.4.1

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 +67 -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 +1734 -1209
  6. package/dist/index.js.map +23 -16
  7. package/dist/line.d.ts +1 -0
  8. package/dist/panel-data.d.ts +9 -2
  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 +30 -35
  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 +597 -367
  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 +974 -158
  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 +8 -7
package/docs/internals.md CHANGED
@@ -15,31 +15,38 @@ The recorder writes to the per-user state directory of the current OS:
15
15
  | macOS | `~/Library/Application Support/opencode/opencode-usage-insights/usage.db` |
16
16
  | Windows | `%LOCALAPPDATA%\opencode\opencode-usage-insights\usage.db` |
17
17
 
18
- `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the
19
- `db` option overrides both. The database is opened with `journal_mode = WAL`, so
20
- the worker's reader and the server's writer never block each other. The TUI and
21
- the Desktop GUI never open the file: they call the server's usage RPC.
18
+ `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path. The database
19
+ is opened with `journal_mode = WAL`, so the worker's reader and the server's
20
+ writer never block each other. The TUI and the Desktop GUI never open the file:
21
+ they call the server's usage RPC.
22
22
  Every write is an upsert keyed by message id, which makes recording idempotent:
23
23
  replayed events, restarts and re-imports never duplicate rows.
24
24
 
25
- Tables: `sessions`, `prompts`, `steps`, `events`, `usage` and `meta` (the
25
+ Tables: `sessions`, `prompts`, `steps`, `compactions`, `usage` and `meta` (the
26
26
  schema version). The `steps` table is the interesting one: `message_id` (primary key),
27
- `session_id`, `parent_id`, provider/model/variant, input/output/reasoning and
27
+ `session_id`, provider/model/variant, input/output/reasoning and
28
28
  cache-read/cache-write tokens, charged `cost`, list-price `list_cost`,
29
- `created_at`, `streamed_at`, `completed_at`, `finish` and `recorded_at`.
29
+ `created_at`, `first_token_at`, `streamed_at`, `completed_at`, `finish` and
30
+ `recorded_at`. `compactions` is only the compaction timeline (session, host
31
+ event ID and time); the cost and tokens of non-step usage live in `usage`.
30
32
  `list_cost` is nullable on purpose: `NULL` means the step was charged or its
31
33
  price was unknown; `0` means the host's model list knows the model is free; a
32
34
  positive value is an estimate for a step the host reported as `$0`. Storing zero for a
33
35
  free model keeps it out of the backfill's "needs an estimate" set without
34
36
  inventing money.
35
37
 
36
- Throughput is not stored: `tps` is everything the model generated
37
- (`output + reasoning`) over the streaming window (`created → streamed`), and the
38
- `latency` view computes it from the timings and reports its p50/p90/p99. The
39
- window is the streaming one on purpose — `streamed` marks the end of streaming
40
- and `completed` the end of the step, which for a tool-call step happens after
41
- the tool calls were handled — so a step whose window or produced tokens are
42
- unknown has no throughput and is left out of the percentiles.
38
+ The rates are not stored: two are derived from the timings. `tps` is
39
+ everything the model generated (`output + reasoning`) over the decode window
40
+ (`firstToken → streamed`), the same definition OpenCode's TUI and Desktop use;
41
+ `rtps` is the same tokens over the request window (`created → streamed`), which
42
+ includes TTFT and queueing. `ttft` is `firstToken − created`. A step recorded
43
+ before the host exposed `firstToken` falls back to `created` for `tps`, exactly
44
+ as the host does. With hidden reasoning, `firstToken` is the first visible
45
+ token, so `tps` can overstate; `rtps` is the conservative rate. The `latency`
46
+ view computes the p50/p90/p99 of all three from the timings; `streamed` marks
47
+ the end of streaming and `completed` the end of the step, which for a tool-call
48
+ step happens after the tool calls were handled. A step whose window or produced
49
+ tokens are unknown has no rate and is left out of the percentiles.
43
50
 
44
51
  Two expression indexes carry every ranged view: `steps_at` on
45
52
  `COALESCE(created_at, recorded_at)` (the step's own clock, falling back to the
@@ -56,6 +63,45 @@ the writer's lock — and prune, wipe, the list-price backfill and compact use a
56
63
  separate short-lived writer inside the worker with a 250 ms busy timeout, so
57
64
  maintenance fails fast with a message instead of stalling the recorder.
58
65
 
66
+ ## Settings
67
+
68
+ The server owns the canonical settings object in the plugin's KV
69
+ (`ctx.storage`, key `settings`). A separate RPC (`usage-insights.settings`)
70
+ provides `get`, a partial `set`, `reset` and an `updated` event. It is
71
+ deliberately independent of the usage-data RPC: a database that cannot open must
72
+ not take the settings editors with it, so the user can still change the line or
73
+ turn the panels off while the panel data itself reports why it is unavailable.
74
+
75
+ Both clients use `src/settings-client.ts`. A save is optimistic in the UI and
76
+ sends only the changed patch; the server merges it, sanitizes the result, writes
77
+ the full object and emits the canonical envelope. The TUI and the Desktop ignore
78
+ an event while they have an edit in flight and compare their own echo, so a
79
+ remote update cannot overwrite text a user is typing. `server.connected`
80
+ reconnects the event subscription after a server restart.
81
+
82
+ The first `get` is a load barrier. Neither the TUI nor the Desktop starts the Go
83
+ poll against the built-in defaults while the server's value is in flight, and
84
+ the initial value does not bump the panel refresh: the first real write event
85
+ must not be throttled by the load.
86
+
87
+ Settings are **per server**. The TUI reads the server it is connected to; the
88
+ Desktop follows the routed session's server and falls back to its built-in
89
+ server on Home.
90
+
91
+ Three values are server policy, not shared settings, and come from the
92
+ environment at startup: `OPENCODE_USAGE_INSIGHTS_DB`,
93
+ `OPENCODE_USAGE_INSIGHTS_MAINTENANCE` and
94
+ `OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS`. `maintenance` is a safety switch for a
95
+ server reachable from another machine and `exposePaths` controls whether
96
+ filesystem paths leave the server at all, so neither is editable over the RPC.
97
+ A pricing or format change reconfigures the worker; the recorder's price
98
+ function reads the current settings on every step, so a live toggle needs no
99
+ rebuild of the event stream. The database path is fixed for the life of the
100
+ server process; change it with the environment and restart. If the database is
101
+ unavailable at startup, the event stream stays alive and the next data request
102
+ retries the open; only events after that open are recorded, because the host
103
+ event stream is not replayed.
104
+
59
105
  ## The identity of a step
60
106
 
61
107
  Every view groups a step by one thing: the **provider the model ran through**,
@@ -217,8 +263,9 @@ line falls back to the host total with no estimate.
217
263
  The backfill only considers steps with a provider, a model and at least one
218
264
  token; it prices free models as `0` and leaves models the host's current model
219
265
  list no longer contains as `NULL`, so `e` can be retried after the list changes.
220
- `pricing: "off"` stops new estimates, hides stored ones in the line, panel and
221
- sidebar, and disables the backfill. It does not delete the column.
266
+ Turning **List-price estimates** off stops new estimates, hides stored ones in
267
+ the line, panel and sidebar, and disables the backfill. It does not delete the
268
+ column.
222
269
 
223
270
  ## Non-step usage
224
271
 
@@ -226,8 +273,9 @@ The host also publishes `session.usage.recorded` with `source: "compaction"` or
226
273
  `source: "title"` for generation that has no assistant step of its own. The
227
274
  recorder stores it in the `usage` table (`id` = host event ID, `session_id`,
228
275
  `source`, `at`, `cost`, and the token buckets). The primary key makes a
229
- replayed event a no-op; the compaction event itself is stored in `events` for
230
- the cache-loss reason and keyed by its own host ID.
276
+ replayed event a no-op. The compaction timeline is kept in `compactions` for
277
+ the cache-loss reason, keyed by its own host ID; only the session and time are
278
+ read, so its payload is not stored.
231
279
 
232
280
  The host includes this usage in the session's own `cost` and token totals, so
233
281
  the views that claim to describe a whole selection include its cost: the
@@ -244,20 +292,20 @@ unaffected: it already reads the host's session total, which includes this
244
292
  usage; the estimate half is still `SUM(list_cost)` over steps, so nothing is
245
293
  added twice.
246
294
 
247
- This is host money, not a list-price estimate, so `pricing: "off"` does not hide
248
- it. A database written by an older plugin is healed at open: the stored
295
+ This is host money, not a list-price estimate, so turning estimates off does
296
+ not hide it. A database written by an older plugin is healed at open: the stored
249
297
  compaction events already carry `cost` and `tokens`, so a migration recovers
250
298
  them with a stable synthetic ID. Title usage was never stored anywhere before
251
299
  the upgrade and stays missing; the line keeps showing the host's whole session
252
300
  total meanwhile.
253
301
 
254
- ### Event idempotency
302
+ ### Compaction idempotency
255
303
 
256
- An event with a host ID is stored with `message_id`; a partial unique index
257
- (`kind, message_id`) turns a replay into `INSERT OR IGNORE`. A migration
304
+ A compaction with a host ID is stored with `message_id`; a partial unique index
305
+ on `message_id` turns a replay into `INSERT OR IGNORE`. A migration
258
306
  deduplicates compaction rows an older recorder inserted on every delivery
259
- before the index is created, so the event count and any cost read from the
260
- table stay honest.
307
+ before the index is created, so the timeline count and the usage recovered
308
+ from their payload stay honest.
261
309
 
262
310
  ## OpenCode Go allowance
263
311
 
@@ -284,10 +332,10 @@ The payload has one meter per window:
284
332
  is the window's reset. The monthly reset is also the paid-period renewal; the UI
285
333
  calls it `renews` and prints the exact local date and time. The payload carries
286
334
  neither a cycle start nor a plan type: Go, Go Plus and Go Teams share the same
287
- meters. The UI therefore shows `quotaName` when configured, else the host
288
- provider name, else the full `OpenCode Go`; a Go Plus/Teams user can set
289
- `quotaName` to their plan name. The compact blocks show that name before the
290
- numbers.
335
+ meters. The UI therefore shows the **Allowance label** setting when configured,
336
+ else the host provider name, else the full `OpenCode Go`; a Go Plus/Teams user
337
+ can set the label to their plan name. The compact blocks show that name before
338
+ the numbers.
291
339
 
292
340
  The payload carries no cycle start, so the forecast infers it as one calendar
293
341
  month before the reset:
@@ -323,13 +371,15 @@ subprocess, no credentials, no telemetry. Everything it records stays in the
323
371
  SQLite file in the user's own state directory. The one extra call is local: the
324
372
  `go` view asks the OpenCode server for the allowance the host already fetched
325
373
  from the OpenCode Console. The plugin never sees the Console API key and never
326
- contacts the Console itself; `quota: "off"` stops that read.
374
+ contacts the Console itself; turning the **Allowance view** setting off stops
375
+ that read.
327
376
 
328
377
  **What is stored.** Per step: timings, token counts, charged cost and the
329
378
  list-price estimate when the host reported `$0`, the provider/model/variant it
330
- ran as, the finish reason, the session and parent ids, and the session's title
331
- and working directory as the host reports them. Per compaction or title
332
- generation: the host event ID, its source, time, cost and token counts. Prompt
379
+ ran as, the finish reason, the session id and the parent session id, and the
380
+ session's title and working directory as the host reports them. Per compaction
381
+ or title generation: the host event ID, its source, time, cost and token
382
+ counts. Prompt
333
383
  text and generated text are never stored, including for those records.
334
384
  **Prompts and responses are not stored**: the recorder reads event payloads for
335
385
  numbers and identifiers and keeps nothing else — no message text, no tool
@@ -351,9 +401,10 @@ arguments, no file contents, no environment variables.
351
401
  - **A bounded, validated RPC.** The TUI and the Desktop GUI read the worker
352
402
  through JSON-Schema-validated methods with closed objects, enums and clamps.
353
403
  There is no SQL, path, import or export method. Maintenance is gated by the
354
- `maintenance` option and an explicit confirmation; the worker runs every query
355
- off the server's event loop and the client queue is bounded while the worker
356
- is in use. Reads have a 10 s watchdog; prune, wipe, vacuum and backfill get
404
+ `OPENCODE_USAGE_INSIGHTS_MAINTENANCE` server policy and an explicit
405
+ confirmation; the worker runs every query off the server's event loop and the
406
+ client queue is bounded while the worker is in use. Reads have a 10 s
407
+ watchdog; prune, wipe, vacuum and backfill get
357
408
  five minutes because rewriting a large file is legitimately slower. The
358
409
  in-process fallback shares the server's event loop and has no separate queue.
359
410
  - **Validated input.** Anything that reaches the database from outside — a
@@ -0,0 +1,60 @@
1
+ # Privacy and security
2
+
3
+ The recorder writes to the per-user state directory:
4
+
5
+ | OS | Path |
6
+ | --- | --- |
7
+ | Linux / other | `$XDG_STATE_HOME/opencode/opencode-usage-insights/usage.db` (default `~/.local/state/opencode/opencode-usage-insights/usage.db`) |
8
+ | macOS | `~/Library/Application Support/opencode/opencode-usage-insights/usage.db` |
9
+ | Windows | `%LOCALAPPDATA%\opencode\opencode-usage-insights\usage.db` |
10
+
11
+ `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path. The directory
12
+ is created `0700` and the file `0600` (POSIX), re-applied on every open.
13
+
14
+ Per step the database holds tokens, charged cost, the list-price estimate when
15
+ the host reported `$0`, timings, finish reason, the configured provider and the
16
+ model it ran through, and the session title and working directory. **Prompts and
17
+ responses are not stored**, and the plugin sends nothing to a third party. The
18
+ Go view reads the usage limits the host already fetched from the OpenCode
19
+ Console; the plugin never sees the API key.
20
+
21
+ The TUI and the Desktop GUI never open the file. They call the usage RPC; the
22
+ server's worker holds a read-only connection for the panel and the history, so a
23
+ view can never write, migrate or take the recorder's lock. Prune, backfill and
24
+ compact use a separate short-lived writer inside the worker. The server applies
25
+ schema migrations on open; after an upgrade, start it once before opening the
26
+ panel if the file predates the new schema.
27
+
28
+ ## RPC surface
29
+
30
+ The usage and settings RPCs are served by the OpenCode server and inherit its
31
+ authentication. They are not new unauthenticated endpoints, but they are a new
32
+ authenticated surface: any client that can call the server API can call them,
33
+ and the RPC handler has no caller identity.
34
+
35
+ - **Read-only by default for queries.** `panel`, `turns`, `listCost`, `filters`
36
+ and `dbInfo` run on the worker's read-only SQLite connection. The only writes
37
+ are `prune`, `wipe`, `vacuum` and `backfill`, gated by the maintenance policy
38
+ and an explicit confirmation.
39
+ - **No free-form access.** There is no SQL, path, import or export method.
40
+ Inputs are validated by JSON Schema with closed objects, enums, length limits
41
+ and numeric clamps; the service validates them again. SQL is parameterized.
42
+ - **Minimal output.** The RPC returns usage metadata — session titles,
43
+ directories, models, providers, tokens, costs and the database shape — never
44
+ prompts or responses. Database paths are returned as a file name unless
45
+ `OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS=1`.
46
+ - **Availability.** The worker keeps panel queries off the server's event loop;
47
+ the client queue is bounded while the worker is in use. Reads have a 10 s
48
+ watchdog; maintenance gets five minutes. Generic errors are returned; details
49
+ stay in the server log.
50
+
51
+ For a server reachable from another machine, set
52
+ `OPENCODE_USAGE_INSIGHTS_MAINTENANCE=0` unless you need the maintenance buttons
53
+ there. The RPC is only as protected as the server: do not expose an OpenCode
54
+ server without its password/auth. The usage database is per server user; every
55
+ authenticated client on that server sees the same sessions and aggregates. If
56
+ you need per-user or per-tenant isolation, do not expose the RPC until the
57
+ database carries that dimension.
58
+
59
+ The schema, indexes, identity rules and more security notes are in
60
+ [internals.md](internals.md#privacy-and-security).
package/docs/tui.md ADDED
@@ -0,0 +1,175 @@
1
+ # TUI
2
+
3
+ The plugin adds a line above the composer, a session sidebar and the
4
+ `/usage-insights` panel. They read the same recorded steps, so a number in one
5
+ place means the same in the others. More screenshots in [demo.md](demo.md).
6
+
7
+ ## The line
8
+
9
+ ```text
10
+ 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)
11
+ ```
12
+
13
+ | Segment | Meaning |
14
+ | --- | --- |
15
+ | `14:32:07` | When the response ended (`completed`, else `streamed`, else `created`). |
16
+ | `Δ 3m12s` | Time since the previous prompt of the same session. |
17
+ | `opencode-go/deepseek-v4.1-flash max` | The identity of the turn: the configured provider the model ran through and the model. The variant is a trailing word; the provider/model and variant fields can be hidden in Settings. Yellow with `changed` when the provider differs from the previous prompt, `model changed` when only the model does. |
18
+ | `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. **Turn totals → Sum every step** in Settings sums every step. |
19
+ | `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. Turn the cost field off in Settings to hide it. |
20
+ | `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`. **List-price estimates** in Settings hides estimates everywhere; the cost field hides both. |
21
+ | `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`. |
22
+ | `⚠ 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. |
23
+
24
+ The turn segment carries no label by default — the numbers are the turn's, and
25
+ `sess` marks the session's; the turn label in Settings (e.g. `"turn"`) brings a
26
+ prefix back. The line belongs to finished work, so it stays hidden while a turn
27
+ runs. It is mounted in the `session.composer.top` slot.
28
+
29
+ `≈` marks a list-price estimate, never a charge. The `sess` segment and
30
+ historical views use the stored per-step estimate; a live turn uses the client's
31
+ current catalog and can differ after a price change. See
32
+ [costs.md](costs.md) for the price sources and the backfill.
33
+
34
+ A turn is every consecutive assistant step after a prompt. Compaction, shell,
35
+ `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
36
+ messages do. From a checkout, `bun run demo` prints one example per case,
37
+ including the streaming one and both turn-total views.
38
+
39
+ ## The panel
40
+
41
+ `/usage-insights [view] [range]` opens the panel; without arguments it reopens
42
+ the last view, or `overview` over `all` the first time. While the panel is open
43
+ it owns input: `escape` closes it, `f` toggles full screen, and the palette entry
44
+ (`ctrl+p` → **Usage insights**) toggles it closed. With the composer focused,
45
+ `/usage-insights` with no arguments also toggles it closed; any argument —
46
+ including an unknown token, which is ignored — keeps it open. There is no
47
+ default key binding, so the command never shadows a key you use. `/usage` stays
48
+ the host's native usage-limits dialog.
49
+
50
+ ![The providers view](images/panel-providers.png)
51
+
52
+ ![The latency view: wall, stream, TTFT, TPS and request TPS](images/panel-latency.png)
53
+
54
+ The view bar at the top names every view and brackets the active one. `?` opens
55
+ a help overlay that repeats the keys and defines every number, including the
56
+ rate windows ([help screenshot](images/panel-help.png)). The view, range, sort,
57
+ bucket, scope and filters are stored through the host's durable storage, so the
58
+ panel reopens where it was left.
59
+
60
+ ### Keys
61
+
62
+ | Key | Does |
63
+ | --- | --- |
64
+ | `↑` `↓` / `j` `k` | Move the cursor; the row under it is highlighted. |
65
+ | `pageup` `pagedown` / `home` `end` | Move by ten rows / to the first or last row. |
66
+ | `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). |
67
+ | `backspace` | Go back from a drill-down. |
68
+ | `1`–`9` `0` / `[` `]` | Pick a view (`9` is `db`, `0` is `go`) / cycle views. |
69
+ | `t` / `shift+t` | Next / previous range. |
70
+ | `s` / `shift+s` | Cycle the sort column / reverse it. |
71
+ | `b` | `periods` bucket: day → week → month. |
72
+ | `a` | `turns` scope: this session ↔ every session (only with a time range; the `this session` range already pins one session). |
73
+ | `m` `p` | Filter by model or by provider (a picker of the values actually observed). |
74
+ | `x` | Clear the filters. |
75
+ | `r` | Re-read the database; in `go`, refresh the live allowance. |
76
+ | `e` | `db`: backfill list-price estimates for the `$0` steps that have none (asks first; uses today's model list). |
77
+ | `v` | `db`: compact the file, giving the space of deleted rows back. |
78
+ | `?` | Help overlay. |
79
+ | `f` / `escape` | Full screen / close. |
80
+
81
+ ### Views
82
+
83
+ | View | Answers |
84
+ | --- | --- |
85
+ | `overview` | Steps, sessions, prompts, `in`/`cached`/`write`/`out`, `hit`, `tps`/`rtps`/`ttft p50`, 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, a completion or a first token). |
86
+ | `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. |
87
+ | `providers` | Which configured provider ran each model: one row per provider, with the models it served, steps, share, prompt, cached, `hit`, p50 TPS, p50 TTFT, wall time and cost. Cost is assistant steps only. `enter` lists every model it served. Steps recorded without a provider are dimmed and cannot be drilled into. |
88
+ | `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. |
89
+ | `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. |
90
+ | `latency` | Wall time, streaming window, TTFT, TPS and request TPS as p50/p90/p99 overall; the per-model table (per provider when a model is filtered) adds the TTFT p50 beside TPS. `n < 5` is dimmed. |
91
+ | `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. |
92
+ | `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. |
93
+ | `db` | File name (full path with `OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS=1`), 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. |
94
+ | `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. |
95
+
96
+ The panel sums the stored per-step buckets over the selected range, so a number
97
+ read in one place means the same in the other: `prompt` is everything the
98
+ provider saw (`cached + fresh + writes`), `in` the uncached part, `hit` is
99
+ `cached / prompt`, and `out` everything generated (visible output + reasoning).
100
+
101
+ The identity of a step is the configured provider the model ran through —
102
+ `opencode`, `opencode-go`, `deepseek`, whatever the provider is called in the
103
+ OpenCode configuration — and the model itself. That is what every view groups
104
+ by. A gateway may route a request to another operator, but that upstream is not
105
+ observable, so it is not guessed. The same model through `deepseek` and through
106
+ `opencode-go` is two rows, two caches and two latency profiles, and a switch
107
+ between them forfeits the cache the previous one held.
108
+
109
+ ### Rates
110
+
111
+ Every view reports two rates and the wait that separates them:
112
+
113
+ | Metric | Formula | Window |
114
+ | --- | --- | --- |
115
+ | `tps` | `Σ(output + reasoning) / Σ(streamed − firstToken)` | first streamed token → last chunk |
116
+ | `rtps` | `Σ(output + reasoning) / Σ(streamed − created)` | request dispatch → last chunk |
117
+ | `ttft` | `firstToken − created` | request dispatch → first streamed token |
118
+
119
+ `tps` is OpenCode's definition: it excludes the wait for the first token. `rtps`
120
+ (request TPS) includes TTFT and queueing and is the conservative reading. The
121
+ difference is exactly TTFT: `rtps = P / (P / tps + ttft)` over the steps. A step
122
+ recorded before the host exposed `firstToken` falls back to `created` for `tps`,
123
+ as OpenCode does; the data coverage block reports that share.
124
+
125
+ A turn is shown as `200 tps · 2.1s ttft`; the session block and the overview show
126
+ `200 tps · 167 rtps` and `ttft p50`; the latency view reports p50/p90/p99 for all
127
+ three. Tables use separate `tps p50` and `ttft p50` columns. With hidden
128
+ reasoning, `firstToken` is the first visible token and `tps` can overstate;
129
+ `rtps` is the conservative rate.
130
+
131
+ `wall` and `stream` are durations: request → completed step and request → last
132
+ chunk. The sidebar's turn header shows the turn's wall time — the first request
133
+ to the last completed step, so any tool wait inside the turn counts — while its
134
+ rates use the windows above. The rates are weighted: produced tokens divided by
135
+ the summed windows, not the mean of the per-step rates the `latency` view
136
+ reports as p50/p90/p99.
137
+
138
+ ## OpenCode Go
139
+
140
+ OpenCode 2.4 already has a native usage dialog. The plugin's `go` view adds the
141
+ monthly forecast, the exact renewal instant, and a chart in the Desktop panel.
142
+ `/usage` remains the host's command; the plugin command is `/usage-insights`.
143
+
144
+ The forecast uses the average pace of the current monthly cycle:
145
+
146
+ ```text
147
+ start = monthly resetsAt - 1 calendar month (inferred)
148
+ elapsed = now - start
149
+ rate = percent / elapsedDays
150
+ projected = percent + rate * remainingDays
151
+ exhaustAt = now + (100 - percent) / rate
152
+ ```
153
+
154
+ It is a percentage projection, not a dollar amount or a token estimate. The host
155
+ exposes whole-number percentages and the reset instant, but not the start of the
156
+ cycle, so the start is inferred. When nothing has been used yet it reads `no
157
+ monthly usage yet`; when the cycle is younger than 30 minutes it says it is too
158
+ early to project. The `renews` line is the exact `monthly.resetsAt` in local
159
+ time, with its countdown.
160
+
161
+ The TUI sidebar and the Desktop **Turns insights** tab show the compact form:
162
+
163
+ ```text
164
+ OpenCode Go
165
+ 5h 2% · week 9% · month 40%
166
+ forecast ~75% at reset
167
+ renews 17 Dec 12:25
168
+ ```
169
+
170
+ The values come from the host's local usage-limits endpoint. The plugin never
171
+ reads the Console API key and makes no external request; turning **Allowance
172
+ view** off in Settings hides the view, the TUI sidebar block and the Desktop
173
+ Turns block, and stops the poll. The host payload names the meters but not the
174
+ paid plan; the UI uses the provider display name or the **Allowance label**
175
+ setting, and falls back to `OpenCode Go`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-usage-insights",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "OpenCode V2 plugin that puts per-turn and per-session cost back in the TUI and OpenCode Desktop — charged cost, list-price estimates, tokens, prompt-cache reuse, latency, local history and an OpenCode Go allowance forecast in a live line, sidebar, header badge and /usage-insights panel.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -80,6 +80,7 @@
80
80
  "build": "bun run scripts/build.ts",
81
81
  "demo": "bun run scripts/demo.ts",
82
82
  "docs:images": "bun run scripts/screenshot.ts",
83
+ "docs:annotate": "python3 scripts/annotate-screenshots.py",
83
84
  "report": "bun run scripts/report.ts",
84
85
  "prepublishOnly": "bun run typecheck && bun run build && bun test && bun run check:package",
85
86
  "bench": "bun run scripts/bench.ts",
@@ -97,16 +98,16 @@
97
98
  "solid-js": ">=1.9.12"
98
99
  },
99
100
  "devDependencies": {
100
- "@happy-dom/global-registrator": "20.0.11",
101
- "@opencode/plugin": "2.4.2",
102
- "@opencode/theme": "2.4.2",
101
+ "@happy-dom/global-registrator": "21.0.4",
102
+ "@opencode/plugin": "2.4.3",
103
+ "@opencode/theme": "2.4.3",
103
104
  "@opentui/core": "0.9.9",
104
- "@opentui/solid": "0.9.9",
105
+ "@opentui/solid": "0.9.10",
105
106
  "@types/bun": "^1.4.1",
106
107
  "@types/node": "^24.0.0",
107
108
  "effect": "4.1.0",
108
- "solid-js": "1.9.12",
109
- "typescript": "^5.8.0",
109
+ "solid-js": "1.9.20",
110
+ "typescript": "^7.0.2",
110
111
  "vite": "^7",
111
112
  "vite-plugin-solid": "^2.11.17"
112
113
  }