opencode-usage-insights 0.1.1 → 0.1.2

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.
package/README.md CHANGED
@@ -33,7 +33,8 @@ written by the server-side recorder and read by the TUI.
33
33
  whether it is the whole session or a window of a long one:
34
34
  `16:54 opencode-go` / `deepseek-v4.1-flash max` /
35
35
  `in 1.7k (427.3k) · out 1.06k` / `hit 99.7% · 1.2k/s · $0.0006`.
36
- - **The record** (server entry): every assistant step with tokens, cost,
36
+ - **The record** (server entry): every assistant step with tokens, charged cost,
37
+ the list-price estimate when the host reported `$0`,
37
38
  timings, finish reason, the provider and model it ran as, and its session and
38
39
  parent ids; prompts, session lifecycle and compaction events too.
39
40
  - **Portable data** (from a checkout): `bun run report --ndjson` exports the
@@ -55,10 +56,7 @@ written by the server-side recorder and read by the TUI.
55
56
 
56
57
  ## Install
57
58
 
58
- > [!IMPORTANT]
59
- > **Not on the npm registry yet.** Until the first release is published,
60
- > `opencode plugin add` and the package-name form below cannot resolve it — use
61
- > the local checkout, the last form of this section.
59
+ The plugin is published on npm as `opencode-usage-insights`.
62
60
 
63
61
  ```sh
64
62
  opencode plugin add opencode-usage-insights
@@ -126,17 +124,130 @@ turn finishes, and `/usage` (alias `/insights`) opens the panel.
126
124
  | `opencode-go/deepseek-v4.1-flash max` | The identity of the turn: the provider the model ran through, as OpenCode is configured, 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. |
127
125
  | `in 85.4k (1.62M), cached 1.53M, out 3.7k, cost $0.21` | `in` is the uncached part of the prompt (fresh input + cache writes), the parenthesised value the whole prompt — shown only when the two differ — `cached` its cached part, `out` everything generated (visible output + reasoning), and `cost` what the turn was billed. With several steps the segment reads `3 steps · …` and reports the step the turn ended with (`latest`) for the tokens, while the cost is always the turn's own — every step is paid for; `turnTotals: "sum"` adds every step's tokens instead. |
128
126
  | `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. |
129
- | `sess in 2.1M (14.5M), cached 12.4M, out 88k, cost $1.90` | The session totals reported by the host, in the same buckets, with the cost of the whole session. |
127
+ | `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. |
128
+ | `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, 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`. |
130
129
  | `⚠ 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. |
131
130
 
132
131
  The turn segment carries no label by default — the numbers are the turn's, and
133
132
  `sess` marks the session's; `labels.turn` (e.g. `"turn"`) brings a prefix back.
134
133
 
134
+ `≈` is an estimate at the host's list price, never a charge. It appears when
135
+ OpenCode reports a step at `$0` — subscription-covered Go requests, or a provider
136
+ that stopped reporting a cost — and the host's model list still has a price. A
137
+ genuinely free model has no price and therefore no estimate; it is recorded as
138
+ known free rather than as an unknown price. The estimate is stored per step, so
139
+ the line's `sess` segment, the panel, the sidebar, the NDJSON export and the CLI
140
+ report all show the same number. The `db` view lists how many `$0` steps still
141
+ lack one; `e` backfills them using today's model list.
142
+
135
143
  A turn is every consecutive assistant step after a prompt. Compaction, shell,
136
144
  `idle` and info messages do not split a turn; `user`, `synthetic` and `system`
137
145
  messages do. From a checkout, `bun run demo` prints one example per case,
138
146
  including the streaming one and both turn-total views.
139
147
 
148
+ ## How costs are calculated
149
+
150
+ **Charged money is never recalculated by the plugin.** `steps.cost` is what the
151
+ host reports for the step (possibly `0` for an OpenCode Go subscription). When
152
+ that number is `0` or missing and the model has a price in the host's model
153
+ list, the plugin computes a **list-price estimate** and stores it in
154
+ `steps.list_cost`. Prices are USD per 1,000,000 tokens.
155
+
156
+ The price source is the model list exposed by the OpenCode process that is
157
+ currently serving the session, already resolved by the host (provider config,
158
+ overrides, Zen/Go pricing):
159
+
160
+ | Surface | Where the price comes from |
161
+ | --- | --- |
162
+ | Server recorder | `ctx.model.list()` → `ModelInfo.cost` |
163
+ | Live turn / backfill | `ctx.data.location.model.list(ctx.location)` → `ModelInfo.cost` |
164
+ | Panel, sidebar, NDJSON, CLI report | stored `steps.list_cost` |
165
+ | `sess` segment | `SUM(list_cost)` from the plugin database |
166
+
167
+ The plugin does **not** read `~/.cache/opencode/models.json`, does **not** use
168
+ `opencode models` for prices (it lists model IDs only), and makes no network
169
+ call of its own. Each `ModelInfo` carries the prices as
170
+ `cost: Array<{ input, output, cache: { read, write }, tier? }>` in USD per
171
+ 1,000,000 tokens.
172
+
173
+ The estimate uses the host's own fallback formula:
174
+
175
+ ```text
176
+ input fresh (uncached) prompt tokens
177
+ cache.read prompt tokens read from the provider cache
178
+ cache.write prompt tokens written to the provider cache
179
+ output visible output tokens
180
+ reasoning reasoning tokens
181
+
182
+ prompt = input + cache.read + cache.write
183
+ cost = (input * inputPrice
184
+ + (output + reasoning) * outputPrice
185
+ + cache.read * cacheReadPrice
186
+ + cache.write * cacheWritePrice) / 1_000_000
187
+ ```
188
+
189
+ Reasoning is billed at the output price. For models with context tiers, the
190
+ tier applies only when the whole prompt is **strictly greater** than the tier
191
+ size; at exactly the threshold the untiered price applies. An unknown model or
192
+ no applicable price means no estimate; an all-zero price means the model is
193
+ known to be free.
194
+
195
+ The buckets behind the line are the same ones the estimate uses, but folded for
196
+ display:
197
+
198
+ ```text
199
+ in = input + cache.write (the uncached part of the prompt)
200
+ cached = cache.read
201
+ out = output + reasoning
202
+ prompt = in + cached
203
+ ```
204
+
205
+ `list_cost` has three meanings: `NULL` means the step was charged or its price
206
+ is unknown; `0` means the model is known to be free; a positive value is the
207
+ estimate. That is why a free model reads as `$0`, while an older model the
208
+ host's model list no longer contains stays without a price.
209
+
210
+ A worked example, using the prices of `opencode-go/deepseek-v4.1-flash`
211
+ (`input 0.15`, `output 0.6`, `cache.read 0.003`):
212
+
213
+ ```text
214
+ 2,591 × 0.15 + (564 + 3,239) × 0.6 + 514,944 × 0.003
215
+ = 4,215.282 per 1,000,000 tokens
216
+ = $0.004215282
217
+ ```
218
+
219
+ What each surface shows:
220
+
221
+ | Situation | Line | Panel |
222
+ | --- | --- | --- |
223
+ | Charged | `cost $0.12` | `$0.12` |
224
+ | Subscription-covered (host `0`, host model price known) | `cost ≈ $3.40` | `≈$3.40` |
225
+ | Mixed (some charged, some covered) | `cost $0.12 + ≈ $3.40` | overview `$0.12 + ≈ $3.40`; table cell `≈$3.52` (charged + estimate) |
226
+ | Known free model | cost omitted | `$0` |
227
+ | Price unknown | cost omitted | `$0` |
228
+
229
+ The **turn** estimate on the live line uses the model list the TUI currently
230
+ has. The **`sess`** segment uses the estimate recorded per step and summed for
231
+ the session, as do the panel, the sidebar, the NDJSON export and the CLI report.
232
+ If a price changes after a step is recorded, the live turn can therefore differ
233
+ from the stored history; `list_cost` freezes the price from the recording time.
234
+ The server loads its model list in the background, refreshes it on
235
+ `model.updated` and keeps the previous table if a refresh fails; the TUI
236
+ invalidates its table on the same event and refreshes it on a coarse TTL.
237
+
238
+ For a session, the charged total is the host's; the estimate is
239
+ `SUM(list_cost)` over the steps the plugin recorded. If the plugin started
240
+ recording in the middle of a session, the estimate covers only the recorded
241
+ steps; the charged total still follows the host. When the database is
242
+ unavailable, the line falls back to the host's charged total with no estimate.
243
+
244
+ The `db` view counts the `$0` steps that have no known price yet. `e` retries
245
+ them with today's host model list: free models become `0`, models still in that
246
+ list get an estimate, and models the list no longer contains stay unknown. Steps
247
+ without a provider/model or without tokens have nothing to price and are not
248
+ counted. `pricing: "off"` stops new estimates, hides stored ones everywhere and
249
+ disables the backfill, without deleting the data.
250
+
140
251
  ## The panel
141
252
 
142
253
  `/usage [view] [range]` opens the panel (`/usage` alone opens the last view, or
@@ -169,6 +280,7 @@ a help overlay that repeats the keys and defines every number.
169
280
  | `m` `p` | Filter by model or by **provider** (a picker of the values actually observed). |
170
281
  | `x` | Clear the filters. |
171
282
  | `r` | Re-read the database. |
283
+ | `e` | `db`: backfill list-price estimates for the `$0` steps that have none (asks first; uses today's model list). |
172
284
  | `v` | `db`: compact the file, giving the space of deleted rows back. |
173
285
  | `?` | Help overlay. |
174
286
  | `f` / `escape` | Full screen / close. |
@@ -188,12 +300,15 @@ durable storage, so the panel reopens where it was left.
188
300
  | `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. |
189
301
  | `sessions` | Each session with steps, prompts, tokens, `hit`, cost, its directory and how many models it used; subagent sessions are indented under their parent and rolled up. |
190
302
  | `turns` | The per-prompt history: one line per finished turn, rendered exactly like the live line. `a` widens it to every session, titled. |
191
- | `db` | Where the file lives, what it holds and how much of it is old. The retention table lists, per preset (`30`/`90`/`365` days), how many steps a prune would remove and the cutoff date it prunes from — pick one with `↑`/`↓` and `enter` prunes it (a confirmation first); `v` gives the space back. |
303
+ | `db` | Where the file lives, what it holds and how much of it is old. The retention table lists, per preset (`30`/`90`/`365` days), how many steps a prune would remove and the cutoff date it prunes from — pick one with `↑`/`↓` and `enter` prunes it (a confirmation first); `v` gives the space back. It also counts the `$0` steps with no list estimate; `e` backfills them at today's list price. |
192
304
 
193
305
  The panel sums the stored per-step buckets over the selected range, so a number
194
306
  read in one place means the same in the other: `prompt` is everything the
195
307
  provider saw (`cached + fresh + writes`), `in` the uncached part, `hit` is
196
308
  `cached / prompt`, and `out` everything generated (visible output + reasoning).
309
+ A `cost` cell marked `≈` includes list-price estimates for steps the host
310
+ reported as `$0`; the overview and the sidebar keep a mixed total in two parts
311
+ (`$0.12 + ≈ $3.40`) so charged money is never mistaken for the estimate.
197
312
 
198
313
  The identity of a step is the **provider the model ran through** — `opencode`,
199
314
  `opencode-go`, `deepseek`, whatever the provider is called in the OpenCode
@@ -226,6 +341,7 @@ Options apply to both entries (each side reads the ones it needs):
226
341
  | `enabled` | `true` | `false` disables that side completely — no line, no panel, no recording. |
227
342
  | `db` | per-OS state path | SQLite path override. Must match between the server and TUI entries. |
228
343
  | `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. |
344
+ | `pricing` | `"auto"` | `"off"` disables list-price estimates everywhere: no new `list_cost` records, no `≈` on the line, in the panel or in the sidebar, and no historical backfill. Charged money is unaffected. |
229
345
  | `sidebar` | `true` | Show the session summary and the per-prompt history — cache hit and cost per turn — in the session sidebar (the slot is invisible while the sidebar is hidden). |
230
346
  | `sidebarTurns` | `5` | How many turns the sidebar history shows. |
231
347
  | `panel` | `true` | Show the `/usage` statistics panel and its command. `false` keeps the line and the sidebar. |
@@ -239,7 +355,7 @@ Options apply to both entries (each side reads the ones it needs):
239
355
  "options": {
240
356
  "fields": { "clock": true, "delta": true, "model": true, "variant": true, "turn": true, "session": true, "reasoning": false, "cost": true, "cacheExpiry": true },
241
357
  "turnTotals": "latest",
242
- "labels": { "delta": "Δ", "turn": "", "session": "sess", "step": "step", "steps": "steps", "input": "in", "cached": "cached", "output": "out", "reasoning": "reason", "cost": "cost", "cacheExpired": "cache expired", "providerChanged": "changed", "modelChanged": "model changed" }
358
+ "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" }
243
359
  }
244
360
  }
245
361
  ```
@@ -259,15 +375,17 @@ The recorder writes to the per-user state directory:
259
375
 
260
376
  `OPENCODE_USAGE_INSIGHTS_DB=/path/to/usage.db` overrides the path, and the `db`
261
377
  option overrides both. The file is private to the user: its directory is created
262
- `0700` and the file `0600` (POSIX), re-applied on every open. The TUI reads
263
- through a read-only connection, so it can never write, migrate or take the
264
- recorder's lock.
265
-
266
- Per step the database holds tokens, cost, timings, finish reason, the provider
267
- and the model it ran as, and the session title and working directory. **Prompts
268
- and responses are not stored**, and nothing leaves the machine. The schema, the
269
- indexes, the identity rules and the security notes live in
270
- [docs/internals.md](docs/internals.md).
378
+ `0700` and the file `0600` (POSIX), re-applied on every open. The TUI's views
379
+ read through a read-only connection, so they never write, migrate or take the
380
+ recorder's lock; prune, backfill and compact use a separate short-lived writer.
381
+ The server entry applies schema migrations on open; after an upgrade, start it
382
+ once before opening the panel if the file predates the new schema.
383
+
384
+ Per step the database holds tokens, charged cost, the list-price estimate when
385
+ the host reported `$0`, timings, finish reason, the provider and the model it ran
386
+ as, and the session title and working directory. **Prompts and responses are not
387
+ stored**, and nothing leaves the machine. The schema, the indexes, the identity
388
+ rules and the security notes live in [docs/internals.md](docs/internals.md).
271
389
 
272
390
  ## CLI report
273
391
 
@@ -280,6 +398,7 @@ bun run report all # every view
280
398
  bun run report providers --model deepseek-v4.1-flash
281
399
  bun run report periods --granularity month
282
400
  bun run report models --provider opencode-go
401
+ bun run report --no-estimates # charged money only, like pricing: "off"
283
402
  bun run report --json # raw rows and every analysis, for scripting
284
403
  bun run report --ndjson > backup.jsonl # export the whole database
285
404
  bun run report --import backup.jsonl # merge an export (idempotent)
package/dist/core.d.ts CHANGED
@@ -30,6 +30,8 @@ export type AssistantMessage = {
30
30
  } | undefined;
31
31
  } | undefined;
32
32
  cost?: number | undefined;
33
+ /** List-price estimate for a step the host reported as costing nothing. */
34
+ listCost?: number | undefined;
33
35
  finish?: string | null | undefined;
34
36
  rawFinish?: string | null | undefined;
35
37
  };
@@ -55,6 +57,8 @@ export type Totals = {
55
57
  reasoning: number;
56
58
  cacheWrite: number;
57
59
  cost: number;
60
+ /** Sum of list-price estimates for steps the host reported as $0. */
61
+ listCost: number;
58
62
  steps: number;
59
63
  };
60
64
  export type CacheDrop = {
@@ -201,6 +205,8 @@ export type LineLabels = {
201
205
  output: string;
202
206
  reasoning: string;
203
207
  cost: string;
208
+ /** Prefix for a list-price estimate, e.g. `cost ≈ $0.03`. */
209
+ estimate: string;
204
210
  cacheExpired: string;
205
211
  providerChanged: string;
206
212
  modelChanged: string;
@@ -229,6 +235,17 @@ export declare function formatClock(ms: number): string;
229
235
  export declare function formatDuration(ms: number): string;
230
236
  export declare function formatTokens(value: number): string;
231
237
  export declare function formatCost(value: number): string;
238
+ /**
239
+ * Charged and estimated money as one string. A mixed total keeps both parts
240
+ * visible so list price is never mistaken for money that was charged:
241
+ * `$0.12 + ≈ $3.40`. Returns undefined when there is no money to show.
242
+ */
243
+ export declare function formatMoney(charged: number, estimated: number, marker?: string): string | undefined;
244
+ /**
245
+ * The list-equivalent total for a compact table cell: charged money plus the
246
+ * estimates, marked with `≈` when any part is estimated.
247
+ */
248
+ export declare function formatSpend(charged: number, estimated: number, marker?: string): string;
232
249
  /**
233
250
  * The buckets the line displays, derived from a totals group. `input` is the
234
251
  * *uncached* part of the prompt (fresh input plus cache writes, i.e. what the
@@ -251,9 +268,11 @@ export declare function formatLineSegments(stats: TurnStats, options?: {
251
268
  labels?: Partial<LineLabels>;
252
269
  fields?: Partial<LineFields>;
253
270
  turnTotals?: TurnTotalsView;
271
+ estimates?: boolean;
254
272
  }): LineSegment[];
255
273
  export declare function formatLine(stats: TurnStats, options?: {
256
274
  labels?: Partial<LineLabels>;
257
275
  fields?: Partial<LineFields>;
258
276
  turnTotals?: TurnTotalsView;
277
+ estimates?: boolean;
259
278
  }): string;
package/dist/index.d.ts CHANGED
@@ -15,6 +15,11 @@ export type Options = {
15
15
  enabled?: boolean | undefined;
16
16
  /** SQLite database path override (defaults to the per-OS state directory). */
17
17
  db?: string | undefined;
18
+ /**
19
+ * List-price estimates for steps the host reports as costing nothing.
20
+ * `off` records charged money only; the TUI hides any stored estimates.
21
+ */
22
+ pricing?: "auto" | "off" | undefined;
18
23
  };
19
24
  declare const _default: Plugin.Plugin;
20
25
  export default _default;