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/dist/line.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type LineFields, type LineLabels, type LineTone, type Totals, type TranscriptMessage, type TurnStats, type TurnTotalsView } from "./core";
2
+ import type { PriceFn } from "./pricing";
2
3
  /**
3
4
  * Adapter between the host's session messages and the pure turn accounting in
4
5
  * `core`, plus the plain-text parts the TUI line is made of.
@@ -31,6 +32,8 @@ export type RuntimeMessage = {
31
32
  model?: RuntimeModelRef | undefined;
32
33
  tokens?: RuntimeTokenUsage | undefined;
33
34
  cost?: number | undefined;
35
+ /** Only present in tests/fixtures; the host message carries `cost` alone. */
36
+ listCost?: number | undefined;
34
37
  finish?: string | null | undefined;
35
38
  rawFinish?: string | null | undefined;
36
39
  };
@@ -45,8 +48,15 @@ export type LinePart = {
45
48
  text: string;
46
49
  tone: LineTone;
47
50
  };
48
- /** Convert host messages into the structural transcript `core` understands. */
49
- export declare function toTranscript(messages: readonly RuntimeMessage[]): TranscriptMessage[];
51
+ /**
52
+ * Convert host messages into the structural transcript `core` understands.
53
+ *
54
+ * When `price` is provided, a step the host reported as costing nothing gets a
55
+ * list-price estimate here. The line is computed from the host transcript, so
56
+ * this is the only place the live line can learn the estimate without reading
57
+ * the plugin database.
58
+ */
59
+ export declare function toTranscript(messages: readonly RuntimeMessage[], price?: PriceFn | undefined): TranscriptMessage[];
50
60
  /**
51
61
  * Convert only the messages of the last `segments` turns.
52
62
  *
@@ -55,9 +65,12 @@ export declare function toTranscript(messages: readonly RuntimeMessage[]): Trans
55
65
  * it cost milliseconds at every turn end, on the thread that also paints the
56
66
  * agent's output. Walking backwards costs what the last turns hold.
57
67
  */
58
- export declare function toTranscriptTail(messages: readonly RuntimeMessage[], segments?: number): TranscriptMessage[];
59
- /** Session-wide accumulated usage, as reported by the host on the session. */
60
- export declare function sessionTotals(info: RuntimeSessionInfo | undefined): Totals | undefined;
68
+ export declare function toTranscriptTail(messages: readonly RuntimeMessage[], segments?: number, price?: PriceFn | undefined): TranscriptMessage[];
69
+ /**
70
+ * Session-wide accumulated usage: the host's tokens and charged cost, plus the
71
+ * list-price estimate the plugin recorded for the session's steps.
72
+ */
73
+ export declare function sessionTotals(info: RuntimeSessionInfo | undefined, listCost?: number): Totals | undefined;
61
74
  /**
62
75
  * The telemetry line as renderable parts: each segment plus the muted
63
76
  * separators between them, so the TUI can color every part independently.
@@ -66,6 +79,7 @@ export declare function lineParts(stats: TurnStats | undefined, options?: {
66
79
  labels?: Partial<LineLabels>;
67
80
  fields?: Partial<LineFields>;
68
81
  turnTotals?: TurnTotalsView;
82
+ estimates?: boolean;
69
83
  }): LinePart[];
70
84
  /** Plain text of the same line, useful for tests and logs. */
71
85
  export declare function lineText(parts: readonly LinePart[]): string;
@@ -30,6 +30,8 @@ export type PanelRequest = {
30
30
  database?: DbInfo | undefined;
31
31
  /** Set when the last vacuum could not take the write lock. */
32
32
  busy?: boolean | undefined;
33
+ /** `false` hides list-price estimates in every view. */
34
+ estimates?: boolean | undefined;
33
35
  width: number;
34
36
  };
35
37
  /** Sorting options per view; the first is the default. */
@@ -102,6 +102,7 @@ export type UsageBuckets = {
102
102
  output: number;
103
103
  reasoning: number;
104
104
  cost: number;
105
+ listCost: number;
105
106
  hit: number | undefined;
106
107
  };
107
108
  export declare function usageBuckets(usage: {
@@ -112,6 +113,7 @@ export declare function usageBuckets(usage: {
112
113
  output: number;
113
114
  reasoning: number;
114
115
  cost: number;
116
+ listCost?: number | undefined;
115
117
  }): UsageBuckets;
116
118
  /**
117
119
  * The view tabs. The active one is bracketed so a single tone still reads
@@ -135,6 +137,8 @@ export declare function overviewLines(data: {
135
137
  range: RangeKey;
136
138
  activity?: readonly number[] | undefined;
137
139
  coverage?: CoverageReport | undefined;
140
+ /** `false` hides list-price estimates. */
141
+ estimates?: boolean | undefined;
138
142
  }, width: number): PanelLine[];
139
143
  export type ModelExtras = {
140
144
  /** Reuse stats per `modelKey`, computed from the step facts. */
@@ -147,11 +151,11 @@ export type ModelExtras = {
147
151
  * and how often its identity changed. One line per model; `providers` keeps the
148
152
  * per-provider detail.
149
153
  */
150
- export declare function modelsLines(rows: readonly ModelUsage[], width: number, extras?: ModelExtras, limit?: number): PanelLine[];
154
+ export declare function modelsLines(rows: readonly ModelUsage[], width: number, extras?: ModelExtras, limit?: number, estimates?: boolean): PanelLine[];
151
155
  /** One row per provider, over every model it served. */
152
- export declare function providerSummaryLines(rows: readonly ProviderSummary[], width: number, limit?: number): PanelLine[];
156
+ export declare function providerSummaryLines(rows: readonly ProviderSummary[], width: number, limit?: number, estimates?: boolean): PanelLine[];
153
157
  /** One row per model × provider: the providers each model ran through. */
154
- export declare function providerLines(rows: readonly ProviderRow[], width: number, limit?: number): PanelLine[];
158
+ export declare function providerLines(rows: readonly ProviderRow[], width: number, limit?: number, estimates?: boolean): PanelLine[];
155
159
  /** One model's reuse row, shared by the models and cache views. */
156
160
  export type CacheModelRow = {
157
161
  usage: {
@@ -166,13 +170,15 @@ export declare function cacheLines(data: {
166
170
  gap?: GapReport | undefined;
167
171
  models?: readonly CacheModelRow[] | undefined;
168
172
  }, width: number): PanelLine[];
169
- export declare function periodLines(rows: readonly PeriodRow[], width: number, granularity: PeriodGranularity, limit?: number): PanelLine[];
170
- export declare function latencyLines(report: LatencyReport, width: number, groups?: readonly LatencyGroupRow[] | undefined, limit?: number): PanelLine[];
173
+ export declare function periodLines(rows: readonly PeriodRow[], width: number, granularity: PeriodGranularity, limit?: number, estimates?: boolean): PanelLine[];
174
+ export declare function latencyLines(report: LatencyReport, width: number, groups?: readonly LatencyGroupRow[] | undefined, limit?: number, estimates?: boolean): PanelLine[];
171
175
  export declare function sessionsLines(rows: readonly SessionUsage[], width: number, options?: {
172
176
  limit?: number | undefined;
177
+ estimates?: boolean | undefined;
173
178
  rollup?: {
174
179
  subagentSteps: number;
175
180
  subagentCost: number;
181
+ subagentListCost?: number | undefined;
176
182
  } | undefined;
177
183
  }): PanelLine[];
178
184
  /** The database view: where it lives, what it holds, and the two cleanups. */
@@ -180,11 +186,14 @@ export declare function dbLines(data: {
180
186
  info: DbInfo;
181
187
  busy?: boolean | undefined;
182
188
  now: number;
189
+ estimates?: boolean | undefined;
183
190
  }, width: number): PanelLine[];
184
191
  export type LineFormatOptions = {
185
192
  labels?: Partial<LineLabels> | undefined;
186
193
  fields?: Partial<LineFields> | undefined;
187
194
  turnTotals?: TurnTotalsView | undefined;
195
+ /** `false` hides list-price estimates everywhere this line is rendered. */
196
+ estimates?: boolean | undefined;
188
197
  };
189
198
  /** The line's own view of a recorded turn, so both render identically. */
190
199
  export declare function turnStats(turn: TurnUsage): TurnStats;
@@ -200,7 +209,7 @@ export declare function turnsLines(rows: readonly TurnUsage[], width: number, op
200
209
  * The accumulated usage of one session, as compact lines for the sidebar. The
201
210
  * buckets are the live line's, so the sidebar, the line and the panel agree.
202
211
  */
203
- export declare function sessionSummaryLines(usage: Overview, budget?: number): PanelLine[];
212
+ export declare function sessionSummaryLines(usage: Overview, budget?: number, estimates?: boolean): PanelLine[];
204
213
  /**
205
214
  * The sidebar history: a compact block per turn — when and through which
206
215
  * provider, then the prompt volumes, then the cache hit, the rate and the cost.
package/dist/panel.d.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  import type { Database } from "bun:sqlite";
3
3
  import type { Context, PanelInput } from "@opencode/plugin/tui/context";
4
4
  import { type LineFormatOptions, type PanelSettings } from "./panel-data";
5
+ import { type BackfillResult } from "./stats/maintenance";
5
6
  /**
6
7
  * The `/usage` panel. One read-only view over the stats database at a time,
7
8
  * driven entirely from the keyboard: a cursor over the selectable lines,
@@ -22,12 +23,19 @@ export type PanelDeps = {
22
23
  * ever taking the recorder's lock. Undefined when the write cannot be made.
23
24
  */
24
25
  withWrite?: (<Value>(run: (db: Database) => Value) => Value | undefined) | undefined;
26
+ /** Price the historical $0 steps that have no estimate yet. */
27
+ backfill?: (() => BackfillResult | undefined) | undefined;
25
28
  /** Injectable clock, for tests. */
26
29
  now: () => number;
27
30
  /** Creation time of a session, used by the `session` range. */
28
31
  sessionStart: (sessionID: string) => number | undefined;
29
32
  /** Bumped by the TUI when a step or an execution ends, so views re-read. */
30
33
  refresh?: (() => number) | undefined;
34
+ /**
35
+ * Ask the TUI to rebuild every read view after a maintenance write. The
36
+ * panel has its own tick; the sidebar observes the TUI's shared signal.
37
+ */
38
+ bump?: (() => void) | undefined;
31
39
  };
32
40
  export declare function Panel(props: {
33
41
  readonly input: PanelInput;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * List-price arithmetic for models the host reported as costing nothing.
3
+ *
4
+ * Prices come from the running OpenCode catalog (`ModelInfo.cost`) and are
5
+ * expressed in USD per 1,000,000 tokens. This module mirrors the host's own
6
+ * fallback exactly, so an estimate for a step reproduces what OpenCode would
7
+ * have recorded before a provider started reporting `cost: 0`.
8
+ *
9
+ * Everything here takes plain objects: no host imports, so the rule can be
10
+ * tested and reused by the recorder, the TUI line and the maintenance action.
11
+ */
12
+ export type CostLike = {
13
+ tier?: {
14
+ type?: string | undefined;
15
+ size?: number | undefined;
16
+ } | undefined;
17
+ input?: number | undefined;
18
+ output?: number | undefined;
19
+ cache?: {
20
+ read?: number | undefined;
21
+ write?: number | undefined;
22
+ } | undefined;
23
+ };
24
+ /** The part of `ModelInfo` pricing needs, structurally. */
25
+ export type ModelInfoLike = {
26
+ providerID?: string | undefined;
27
+ modelID?: string | undefined;
28
+ id?: string | undefined;
29
+ cost?: readonly CostLike[] | undefined;
30
+ };
31
+ export type PriceTier = {
32
+ /** Present only on a context-tiered price; an untiered price has no tier. */
33
+ tier?: {
34
+ type?: string | undefined;
35
+ size: number;
36
+ } | undefined;
37
+ input: number;
38
+ output: number;
39
+ cacheRead: number;
40
+ cacheWrite: number;
41
+ };
42
+ export type ModelPrice = {
43
+ tiers: PriceTier[];
44
+ };
45
+ /** `providerID/modelID` to its prices. */
46
+ export type PriceTable = Map<string, ModelPrice>;
47
+ export type PriceRef = {
48
+ providerID?: string | undefined;
49
+ modelID?: string | undefined;
50
+ };
51
+ export type PriceTokens = {
52
+ input?: number | undefined;
53
+ output?: number | undefined;
54
+ reasoning?: number | undefined;
55
+ cacheRead?: number | undefined;
56
+ cacheWrite?: number | undefined;
57
+ };
58
+ /** The estimate callback the recorder and the live line share. */
59
+ export type PriceFn = (ref: PriceRef, tokens: PriceTokens) => number | undefined;
60
+ /** Build the price table from the catalog the host exposes. */
61
+ export declare function priceTable(models: readonly ModelInfoLike[] | undefined): PriceTable;
62
+ export declare function priceOf(table: PriceTable, ref: PriceRef): ModelPrice | undefined;
63
+ /**
64
+ * The list price of one step, or undefined when there is nothing to show.
65
+ *
66
+ * The rule is the host's `cost` fallback: the prompt is fresh input plus cache
67
+ * reads and writes; the tier that applies is the largest context tier the
68
+ * prompt is strictly above; otherwise the untiered price. A known model whose
69
+ * applicable prices are all zero returns `0` (free, not an estimate); an
70
+ * unknown model or no applicable tier returns `undefined`.
71
+ */
72
+ export declare function costOf(table: PriceTable, ref: PriceRef, usage: PriceTokens): number | undefined;
@@ -1,4 +1,5 @@
1
1
  import type { Database } from "bun:sqlite";
2
+ import type { PriceFn } from "./pricing";
2
3
  /**
3
4
  * Event-driven recorder. Every handler is idempotent and defensive: the
4
5
  * plugin must never break a session because an event arrived in an
@@ -60,6 +61,11 @@ export type PendingStep = {
60
61
  export type RecorderOptions = {
61
62
  /** Clock override, for tests. */
62
63
  now?: (() => number) | undefined;
64
+ /**
65
+ * List-price estimate for a step the host reported as costing nothing.
66
+ * Undefined keeps the recorder on charged money alone.
67
+ */
68
+ price?: PriceFn | undefined;
63
69
  };
64
70
  export type Recorder = {
65
71
  /** Apply one session event. Unknown or malformed events are ignored. */
@@ -39,6 +39,7 @@ export type StepRow = {
39
39
  output: number;
40
40
  reasoning: number;
41
41
  cost: number;
42
+ listCost: number;
42
43
  createdAt: number | undefined;
43
44
  streamedAt: number | undefined;
44
45
  completedAt: number | undefined;
@@ -14,7 +14,7 @@ import { Database } from "bun:sqlite";
14
14
  * - `openStatsDbWrite` is a short-lived maintenance connection (prune, vacuum)
15
15
  * that gives up quickly instead of holding the recorder up.
16
16
  */
17
- export declare const SCHEMA_VERSION = 9;
17
+ export declare const SCHEMA_VERSION = 10;
18
18
  /** Tables carried by `exportNdjson` / `importNdjson`, in import-safe order. */
19
19
  export declare const TABLES: readonly ["sessions", "prompts", "events", "steps"];
20
20
  export type TableName = (typeof TABLES)[number];
@@ -32,6 +32,12 @@ export type StepRecord = {
32
32
  cacheRead?: number | undefined;
33
33
  cacheWrite?: number | undefined;
34
34
  cost?: number | undefined;
35
+ /**
36
+ * List-price estimate for a step the host reported as costing nothing.
37
+ * `0` means a known free model; `NULL` means charged money or an unknown
38
+ * price.
39
+ */
40
+ listCost?: number | undefined;
35
41
  createdAt?: number | undefined;
36
42
  streamedAt?: number | undefined;
37
43
  completedAt?: number | undefined;
@@ -77,7 +83,9 @@ export declare function openStatsDbWrite(path: string): Database;
77
83
  * Insert or refresh an assistant step. Idempotent by message ID so replayed
78
84
  * events, restarts and NDJSON imports never duplicate usage. A non-null field
79
85
  * (the provider, the model, the finish reason) survives a re-record with `NULL`
80
- * through COALESCE.
86
+ * through COALESCE. `list_cost` follows the opposite rule: a step that becomes
87
+ * charged loses its estimate, and an estimate survives a replay that carries
88
+ * no price table.
81
89
  *
82
90
  * The provider is the identity every view groups by, so it is validated as a
83
91
  * token before it is stored: a value that is not a provider id is recorded as
@@ -1,4 +1,5 @@
1
1
  import type { Database } from "bun:sqlite";
2
+ import type { PriceRef, PriceTokens } from "../pricing";
2
3
  import { type TableName } from "./db";
3
4
  /**
4
5
  * Database maintenance: what the file holds, how much of it is worth keeping,
@@ -27,6 +28,8 @@ export type DbInfo = {
27
28
  days: number;
28
29
  steps: number;
29
30
  }>;
31
+ /** Steps at $0 with a model identity and no list-price estimate yet. */
32
+ unpriced: number;
30
33
  };
31
34
  export declare function dbInfo(db: Database, path: string, now?: number): DbInfo;
32
35
  export type PruneResult = {
@@ -46,4 +49,18 @@ export declare function vacuum(db: Database, path: string): {
46
49
  after: number;
47
50
  freed: number;
48
51
  };
52
+ /** True when the database carries the list-price column. */
53
+ export declare function hasListCost(db: Database): boolean;
54
+ export type BackfillResult = {
55
+ /** Steps that matched the `cost = 0 AND list_cost IS NULL` condition. */
56
+ candidates: number;
57
+ /** Steps a price was known for and written. */
58
+ updated: number;
59
+ };
60
+ /**
61
+ * Price historical steps the host recorded at $0. The price is today's catalog,
62
+ * not the one in force when the step ran, so this is explicitly user-triggered.
63
+ * A step whose model has no price is left NULL for a later run.
64
+ */
65
+ export declare function backfillListCost(db: Database, price: (ref: PriceRef, tokens: PriceTokens) => number | undefined): BackfillResult;
49
66
  export type { TableName };
@@ -53,7 +53,22 @@ export type Usage = {
53
53
  output: number;
54
54
  reasoning: number;
55
55
  cost: number;
56
+ /** List-price estimate for steps the host reported as costing nothing. */
57
+ listCost: number;
56
58
  };
59
+ /**
60
+ * What the selection costs: charged money plus the list-price estimate of the
61
+ * steps the host reported as free. Display code marks the estimated part.
62
+ */
63
+ export declare function spend(usage: Pick<Usage, "cost" | "listCost">): number;
64
+ /** True when at least one step in the aggregate is an estimate. */
65
+ export declare function hasEstimate(usage: Pick<Usage, "listCost">): boolean;
66
+ /**
67
+ * The list-price estimate of one session, from the steps the plugin recorded.
68
+ * The live line uses it for the `sess` segment; a session with no recorded
69
+ * estimate (or a database without the column) answers 0.
70
+ */
71
+ export declare function sessionListCost(db: Database, sessionID: string): number;
57
72
  export declare const STEP_TIME = "COALESCE(created_at, recorded_at)";
58
73
  /**
59
74
  * The identity of a model *and* its variant, in SQL: `modelKey` says a variant
package/dist/tui.d.ts CHANGED
@@ -21,6 +21,12 @@ export type Options = {
21
21
  enabled?: boolean | undefined;
22
22
  /** SQLite database path override; must match the server entry. */
23
23
  db?: string | undefined;
24
+ /**
25
+ * List-price estimates for steps the host reports as costing nothing.
26
+ * `off` hides them on the line, in the panel and in the sidebar, and
27
+ * disables the historical backfill. Defaults to `auto`.
28
+ */
29
+ pricing?: "auto" | "off" | undefined;
24
30
  /**
25
31
  * How the turn segment counts prompt usage: `latest` (default) shows the
26
32
  * prompt size the turn ended with, `sum` adds every step of the turn.