opencode-usage-insights 0.1.0 → 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
- import { type LineFields, type LineIdentity, type LineLabels, type LineTone, type Totals, type TranscriptMessage, type TurnStats, type TurnTotalsView } from "./core";
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,7 +79,7 @@ export declare function lineParts(stats: TurnStats | undefined, options?: {
66
79
  labels?: Partial<LineLabels>;
67
80
  fields?: Partial<LineFields>;
68
81
  turnTotals?: TurnTotalsView;
69
- identity?: LineIdentity;
82
+ estimates?: boolean;
70
83
  }): LinePart[];
71
84
  /** Plain text of the same line, useful for tests and logs. */
72
85
  export declare function lineText(parts: readonly LinePart[]): string;
@@ -1,5 +1,5 @@
1
1
  import type { Database } from "bun:sqlite";
2
- import { type CacheStats, type PairRow } from "./stats/aggregates";
2
+ import { type CacheStats, type PairRow, type SwitchRow } from "./stats/aggregates";
3
3
  import { type Filters } from "./stats/queries";
4
4
  import type { DbInfo } from "./stats/maintenance";
5
5
  import { type Granularity, type LineFormatOptions, type PanelLine, type PanelRow, type PanelView, type RangeKey } from "./panel-data";
@@ -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. */
@@ -42,3 +44,5 @@ export declare function detailLabel(row: PanelRow): string;
42
44
  export declare function buildPanel(request: PanelRequest): PanelLine[];
43
45
  /** Token reuse per model, for the models view and the cache view. */
44
46
  export declare function cacheByModel(pairs: readonly PairRow[]): Map<string, CacheStats>;
47
+ /** The switch summary per `modelKey`, as the models view reads it. */
48
+ export declare function switchesByModel(rows: readonly SwitchRow[]): Map<string, SwitchRow>;
@@ -1,7 +1,7 @@
1
- import { type LineFields, type LineIdentity, type LineLabels, type TurnStats, type TurnTotalsView } from "./core";
1
+ import { type LineFields, type LineLabels, type TurnStats, type TurnTotalsView } from "./core";
2
2
  import type { CacheDropRow, LatencyReport, ModelUsage, Overview, Range, SessionUsage, TurnUsage, TtlEvidenceRow } from "./stats/queries";
3
3
  import type { DbInfo } from "./stats/maintenance";
4
- import type { AffinityReport, CacheStats, CoverageReport, EndpointRow, EndpointSummary, GapReport, LatencyGroupRow, PeriodGranularity, PeriodRow } from "./stats/aggregates";
4
+ import type { CacheStats, CoverageReport, ProviderRow, ProviderSummary, GapReport, LatencyGroupRow, PeriodGranularity, PeriodRow, SwitchRow } from "./stats/aggregates";
5
5
  /**
6
6
  * View models and formatting for the stats panel. Everything here is pure:
7
7
  * the panel component feeds query results in and renders the lines out, which
@@ -9,7 +9,7 @@ import type { AffinityReport, CacheStats, CoverageReport, EndpointRow, EndpointS
9
9
  * identity the cursor selects and Enter drills into.
10
10
  */
11
11
  export declare const PANEL_NAME = "usage-insights";
12
- export declare const PANEL_VIEWS: readonly ["overview", "models", "endpoints", "affinity", "cache", "periods", "latency", "sessions", "turns", "db"];
12
+ export declare const PANEL_VIEWS: readonly ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
13
13
  export type PanelView = (typeof PANEL_VIEWS)[number];
14
14
  export declare const RANGE_KEYS: readonly ["session", "today", "7d", "30d", "all"];
15
15
  export type RangeKey = (typeof RANGE_KEYS)[number];
@@ -18,7 +18,7 @@ export type Granularity = (typeof GRANULARITIES)[number];
18
18
  export type PanelTone = "base" | "muted" | "warning" | "accent";
19
19
  /** What a selectable line stands for; Enter drills into it. */
20
20
  export type PanelRow = {
21
- kind: "model" | "session" | "period" | "endpoint" | "provider" | "turn" | "prune";
21
+ kind: "model" | "session" | "period" | "provider" | "turn" | "prune";
22
22
  value: string;
23
23
  variant?: string | undefined;
24
24
  };
@@ -50,8 +50,8 @@ export type PanelSettings = {
50
50
  turnsScope: TurnsScope;
51
51
  /** Empty string means "no filter". */
52
52
  modelID: string;
53
- /** The routing endpoint that served the request. */
54
- routerID: string;
53
+ /** The provider the model ran through. */
54
+ providerID: string;
55
55
  };
56
56
  export declare const DEFAULT_SETTINGS: PanelSettings;
57
57
  /** Merge persisted state with the defaults, dropping anything unrecognized. */
@@ -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
@@ -122,7 +124,7 @@ export declare function viewBar(view: PanelView, width?: number): PanelLine;
122
124
  export declare function keysFor(of: PanelView): string;
123
125
  export declare function filterSummary(filters: {
124
126
  modelID?: string | undefined;
125
- routerID?: string | undefined;
127
+ providerID?: string | undefined;
126
128
  }): string | undefined;
127
129
  export declare function granularityLabel(granularity: PeriodGranularity): string;
128
130
  /** Help overlay: the keys and the exact meaning of every number. */
@@ -135,24 +137,25 @@ 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. */
141
145
  cache?: Map<string, CacheStats> | undefined;
142
- /** Identity changes per `modelKey`, from the affinity report. */
143
- changes?: Map<string, number> | undefined;
146
+ /** Switches per `modelKey`, computed from the consecutive step pairs. */
147
+ switches?: Map<string, SwitchRow> | undefined;
144
148
  };
145
149
  /**
146
- * Usage per model with the cache it actually got, where it was served from and
147
- * how often its identity changed. One line per model; `providers` keeps the
150
+ * Usage per model with the cache it actually got, the providers it ran through
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[];
151
- /** One row per endpoint, over every model it served. */
152
- export declare function endpointSummaryLines(rows: readonly EndpointSummary[], width: number, limit?: number): PanelLine[];
153
- /** One row per model × endpoint: the endpoints that served each model. */
154
- export declare function endpointsLines(rows: readonly EndpointRow[], width: number, limit?: number): PanelLine[];
155
- export declare function affinityLines(report: AffinityReport, width: number, limit?: number): PanelLine[];
154
+ export declare function modelsLines(rows: readonly ModelUsage[], width: number, extras?: ModelExtras, limit?: number, estimates?: boolean): PanelLine[];
155
+ /** One row per provider, over every model it served. */
156
+ export declare function providerSummaryLines(rows: readonly ProviderSummary[], width: number, limit?: number, estimates?: boolean): PanelLine[];
157
+ /** One row per model × provider: the providers each model ran through. */
158
+ export declare function providerLines(rows: readonly ProviderRow[], width: number, limit?: number, estimates?: boolean): PanelLine[];
156
159
  /** One model's reuse row, shared by the models and cache views. */
157
160
  export type CacheModelRow = {
158
161
  usage: {
@@ -167,13 +170,15 @@ export declare function cacheLines(data: {
167
170
  gap?: GapReport | undefined;
168
171
  models?: readonly CacheModelRow[] | undefined;
169
172
  }, width: number): PanelLine[];
170
- export declare function periodLines(rows: readonly PeriodRow[], width: number, granularity: PeriodGranularity, limit?: number): PanelLine[];
171
- 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[];
172
175
  export declare function sessionsLines(rows: readonly SessionUsage[], width: number, options?: {
173
176
  limit?: number | undefined;
177
+ estimates?: boolean | undefined;
174
178
  rollup?: {
175
179
  subagentSteps: number;
176
180
  subagentCost: number;
181
+ subagentListCost?: number | undefined;
177
182
  } | undefined;
178
183
  }): PanelLine[];
179
184
  /** The database view: where it lives, what it holds, and the two cleanups. */
@@ -181,12 +186,14 @@ export declare function dbLines(data: {
181
186
  info: DbInfo;
182
187
  busy?: boolean | undefined;
183
188
  now: number;
189
+ estimates?: boolean | undefined;
184
190
  }, width: number): PanelLine[];
185
191
  export type LineFormatOptions = {
186
192
  labels?: Partial<LineLabels> | undefined;
187
193
  fields?: Partial<LineFields> | undefined;
188
194
  turnTotals?: TurnTotalsView | undefined;
189
- identity?: LineIdentity | undefined;
195
+ /** `false` hides list-price estimates everywhere this line is rendered. */
196
+ estimates?: boolean | undefined;
190
197
  };
191
198
  /** The line's own view of a recorded turn, so both render identically. */
192
199
  export declare function turnStats(turn: TurnUsage): TurnStats;
@@ -202,10 +209,16 @@ export declare function turnsLines(rows: readonly TurnUsage[], width: number, op
202
209
  * The accumulated usage of one session, as compact lines for the sidebar. The
203
210
  * buckets are the live line's, so the sidebar, the line and the panel agree.
204
211
  */
205
- export declare function sessionSummaryLines(usage: Overview, budget?: number): PanelLine[];
212
+ export declare function sessionSummaryLines(usage: Overview, budget?: number, estimates?: boolean): PanelLine[];
206
213
  /**
207
- * The sidebar history: two compact lines per turn — when and through which
208
- * endpoint, then the prompt volumes — truncated to the sidebar budget.
214
+ * The sidebar history: a compact block per turn — when and through which
215
+ * provider, then the prompt volumes, then the cache hit, the rate and the cost.
216
+ *
217
+ * The model gets a line of its own at both ends of the block and on every turn
218
+ * that changed it. The ends matter because the reader cannot tell whether a
219
+ * block is the whole history or a window of a long session: the newest turn
220
+ * names the model in use now, the oldest names the one the window started with,
221
+ * and everything between them is read against the nearest line below it.
209
222
  */
210
223
  export declare function sidebarLines(rows: readonly TurnUsage[], options?: LineFormatOptions & {
211
224
  budget?: number | undefined;
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,12 +1,15 @@
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
5
6
  * unexpected shape, so unknown events are ignored and malformed payloads are
6
7
  * dropped rather than thrown.
7
8
  *
8
- * Pure with respect to its inputs (database plus events) so the whole
9
- * recording policy can be unit-tested without the plugin runtime.
9
+ * Everything written comes from the event stream: the step's provider, model
10
+ * and variant, its tokens, its timing and its outcome. Pure with respect to
11
+ * its inputs (database plus events) so the whole recording policy can be
12
+ * unit-tested without the plugin runtime.
10
13
  */
11
14
  export type SessionModelRef = {
12
15
  id: string;
@@ -48,19 +51,6 @@ export type RecorderEvent = {
48
51
  created?: number | undefined;
49
52
  data?: RecorderEventData | undefined;
50
53
  };
51
- export type HttpResponseInput = {
52
- sessionID?: string | undefined;
53
- kind?: string | undefined;
54
- model?: SessionModelRef | undefined;
55
- request?: {
56
- method?: string | undefined;
57
- url?: string | undefined;
58
- } | undefined;
59
- response?: {
60
- status?: number | undefined;
61
- headers?: Headers | Record<string, string | undefined> | undefined;
62
- } | undefined;
63
- };
64
54
  export type PendingStep = {
65
55
  messageID: string;
66
56
  sessionID: string;
@@ -71,12 +61,15 @@ export type PendingStep = {
71
61
  export type RecorderOptions = {
72
62
  /** Clock override, for tests. */
73
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;
74
69
  };
75
70
  export type Recorder = {
76
71
  /** Apply one session event. Unknown or malformed events are ignored. */
77
72
  handleEvent(event: RecorderEvent): void;
78
- /** Learn the routing endpoint from one model response. */
79
- handleHttpResponse(event: HttpResponseInput): void;
80
73
  pendingFor(sessionID: string): PendingStep | undefined;
81
74
  };
82
75
  export declare function createRecorder(db: Database, options?: RecorderOptions): Recorder;
package/dist/sidebar.d.ts CHANGED
@@ -4,9 +4,9 @@ import type { Context } from "@opencode/plugin/tui/context";
4
4
  import { type LineFormatOptions } from "./panel-data";
5
5
  /**
6
6
  * Sidebar history: the session's accumulated usage, then the last finished
7
- * turns, two compact lines each (when + endpoint, then the prompt volumes).
8
- * Reads the same database, the same buckets and the same formatter as the panel
9
- * and the live line, and refreshes whenever a turn ends.
7
+ * turns — when and through which provider, the model when it changed, and the
8
+ * prompt volumes. Reads the same database, the same buckets and the same
9
+ * formatter as the panel and the live line, and refreshes whenever a turn ends.
10
10
  */
11
11
  export type TurnsSidebarDeps = {
12
12
  db: () => Database | undefined;
@@ -33,13 +33,13 @@ export type StepRow = {
33
33
  providerID: string | undefined;
34
34
  modelID: string | undefined;
35
35
  variant: string | undefined;
36
- router: string | undefined;
37
36
  input: number;
38
37
  cached: number;
39
38
  cacheWrite: number;
40
39
  output: number;
41
40
  reasoning: number;
42
41
  cost: number;
42
+ listCost: number;
43
43
  createdAt: number | undefined;
44
44
  streamedAt: number | undefined;
45
45
  completedAt: number | undefined;
@@ -69,18 +69,18 @@ export declare function cachePairs(db: Database, options?: Options): PairRow[];
69
69
  export type CoverageReport = {
70
70
  steps: number;
71
71
  models: number;
72
- endpoints: number;
72
+ /** Providers the steps ran through. A step whose provider is unknown is counted nowhere. */
73
+ providers: number;
73
74
  missingModel: number;
74
- missingEndpoint: number;
75
75
  unsettled: number;
76
76
  missingTps: number;
77
77
  firstAt: number | undefined;
78
78
  lastAt: number | undefined;
79
79
  };
80
80
  /**
81
- * What the panel cannot answer honestly: how many steps lack a model or an
82
- * observed endpoint, and how many never settled. A zero in the affinity view
83
- * means "never changed" only when this coverage is complete.
81
+ * What the panel cannot answer honestly: how many steps lack a model, and how
82
+ * many never settled. A zero in the switch counts means "never switched" only
83
+ * when this coverage is complete.
84
84
  */
85
85
  export declare function coverageOf(db: Database, options?: Options): CoverageReport;
86
86
  /** The steps a latency report is built from. It reads no generated tokens. */
@@ -103,7 +103,7 @@ export type LatencyGroupRow = {
103
103
  stream: LatencyStats;
104
104
  tps: LatencyStats;
105
105
  };
106
- export type Dimension = "model" | "provider" | "endpoint";
106
+ export type Dimension = "model" | "provider";
107
107
  /** Wall, streaming window and throughput percentiles per group. */
108
108
  export declare function latencyGroupsOf(rows: readonly StepRow[], by: Dimension): LatencyGroupRow[];
109
109
  export type CacheStats = {
@@ -130,26 +130,23 @@ export type CacheModelRow = {
130
130
  * range. A boundary step is not part of the range, so it is left out.
131
131
  */
132
132
  export declare function cacheStatsByModel(rows: readonly PairRow[]): CacheModelRow[];
133
- export type AffinityRow = {
133
+ export type SwitchRow = {
134
134
  modelID: string;
135
135
  variant: string | undefined;
136
136
  steps: number;
137
137
  pairs: number;
138
+ /** Steps whose model, variant or provider differed from the step before. */
138
139
  changes: number;
140
+ /** Of those, the ones whose model (or variant) differed. */
139
141
  modelChanges: number;
140
- endpointChanges: number;
142
+ /** Of those, the ones whose provider differed. */
143
+ providerChanges: number;
144
+ /** Cache the changes cost: only a provider switch can forfeit a reusable cache. */
141
145
  cacheLost: number;
142
146
  cacheLostEvents: number;
143
147
  };
144
- export type AffinityTransition = {
145
- dimension: "model" | "endpoint";
146
- from: string;
147
- to: string;
148
- count: number;
149
- };
150
- export type AffinityReport = {
151
- rows: AffinityRow[];
152
- transitions: AffinityTransition[];
148
+ export type SwitchReport = {
149
+ rows: SwitchRow[];
153
150
  totals: {
154
151
  pairs: number;
155
152
  changes: number;
@@ -158,12 +155,17 @@ export type AffinityReport = {
158
155
  };
159
156
  };
160
157
  /**
161
- * Identity changes between consecutive steps of a session, by the two
162
- * dimensions that decide where the work ran: the model and the routing
163
- * endpoint. A change is not by itself a fault — a gateway may re-route
164
- * deliberately — so the report pairs the count with the cache it actually cost.
158
+ * Switches between consecutive steps of a session, by the two dimensions that
159
+ * decide which cache holds the work: the model (with its variant) and the
160
+ * provider.
161
+ *
162
+ * A switch is not by itself a fault — it is usually the user choosing another
163
+ * model — so the report only names a cost where one is measurable: a provider
164
+ * switch that leaves the model intact forfeits the cache the previous provider
165
+ * held. A model switch has no measurable cost by definition, because two models
166
+ * never share a cache to lose.
165
167
  */
166
- export declare function affinityOf(rows: readonly PairRow[]): AffinityReport;
168
+ export declare function switchesOf(rows: readonly PairRow[]): SwitchReport;
167
169
  export type GapBucket = {
168
170
  label: string;
169
171
  samples: number;
@@ -173,9 +175,9 @@ export type GapBucket = {
173
175
  lostTokens: number;
174
176
  retainedRatio: number | undefined;
175
177
  };
176
- export type EndpointReuseRow = {
177
- /** The routing endpoint, or `(unknown)` when it was never observed. */
178
- endpoint: string;
178
+ export type ProviderReuseRow = {
179
+ /** The provider, or `(unknown)` when a step ran without one. */
180
+ provider: string;
179
181
  samples: number;
180
182
  retained: number;
181
183
  drops: number;
@@ -184,14 +186,14 @@ export type EndpointReuseRow = {
184
186
  };
185
187
  export type GapReport = {
186
188
  buckets: GapBucket[];
187
- endpoints: EndpointReuseRow[];
189
+ providers: ProviderReuseRow[];
188
190
  samples: number;
189
191
  };
190
192
  /** Idle-gap buckets, coarse enough to read at a glance. */
191
193
  export declare const GAP_BUCKETS: ReadonlyArray<readonly [string, number, number | undefined]>;
192
194
  /**
193
195
  * How long an idle gap the prompt cache survives, per gap bucket and per
194
- * endpoint. Only pairs of the same model are comparable, which is exactly the
196
+ * provider. Only pairs of the same model are comparable, which is exactly the
195
197
  * set the cache rule already uses.
196
198
  */
197
199
  export declare function gapReportOf(rows: readonly PairRow[]): GapReport;
@@ -233,10 +235,10 @@ export type CacheDropRow = {
233
235
  export declare function cacheDropsOf(db: Database, rows: readonly PairRow[], options?: {
234
236
  ttlHintMs?: number;
235
237
  }): CacheDropRow[];
236
- export type EndpointSummary = {
237
- /** The routing endpoint, or undefined for requests whose destination was never observed. */
238
- endpoint: string | undefined;
239
- /** Models this endpoint served. */
238
+ export type ProviderSummary = {
239
+ /** The provider, or undefined for steps recorded without one. */
240
+ provider: string | undefined;
241
+ /** Models this provider served. */
240
242
  models: string[];
241
243
  share: number;
242
244
  usage: Usage;
@@ -246,14 +248,14 @@ export type EndpointSummary = {
246
248
  firstAt: number | undefined;
247
249
  lastAt: number | undefined;
248
250
  };
249
- export type EndpointRow = EndpointSummary & {
251
+ export type ProviderRow = ProviderSummary & {
250
252
  modelID: string;
251
253
  variant: string | undefined;
252
254
  };
253
- /** One row per endpoint, over every model it served. */
254
- export declare function endpointSummaryOf(rows: readonly StepRow[]): EndpointSummary[];
255
- /** One row per model × endpoint: where each model was served, and how much. */
256
- export declare function endpointBreakdownOf(rows: readonly StepRow[]): EndpointRow[];
255
+ /** One row per provider, over every model it served. */
256
+ export declare function providerSummaryOf(rows: readonly StepRow[]): ProviderSummary[];
257
+ /** One row per model × provider: through which provider each model ran, and how much. */
258
+ export declare function providerBreakdownOf(rows: readonly StepRow[]): ProviderRow[];
257
259
  export type PeriodGranularity = "day" | "week" | "month";
258
260
  export type PeriodRow = {
259
261
  key: string;
@@ -1,5 +1,4 @@
1
1
  import { Database } from "bun:sqlite";
2
- import type { EndpointInfo } from "../endpoint";
3
2
  /**
4
3
  * Persistent usage store. One SQLite database holds every recorded step,
5
4
  * prompt, event and session row — and nothing else: the recorder only writes
@@ -15,7 +14,7 @@ import type { EndpointInfo } from "../endpoint";
15
14
  * - `openStatsDbWrite` is a short-lived maintenance connection (prune, vacuum)
16
15
  * that gives up quickly instead of holding the recorder up.
17
16
  */
18
- export declare const SCHEMA_VERSION = 8;
17
+ export declare const SCHEMA_VERSION = 10;
19
18
  /** Tables carried by `exportNdjson` / `importNdjson`, in import-safe order. */
20
19
  export declare const TABLES: readonly ["sessions", "prompts", "events", "steps"];
21
20
  export type TableName = (typeof TABLES)[number];
@@ -23,6 +22,7 @@ export type StepRecord = {
23
22
  messageID: string;
24
23
  sessionID: string;
25
24
  parentID?: string | undefined;
25
+ /** The provider the model ran through, as OpenCode configured it (`opencode-go`). */
26
26
  providerID?: string | undefined;
27
27
  modelID?: string | undefined;
28
28
  variant?: string | undefined;
@@ -32,12 +32,16 @@ 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;
38
44
  finish?: string | undefined;
39
- /** Gateway routing endpoint that served the request (`orcarouter-dsv4.1flash`). */
40
- router?: string | undefined;
41
45
  /** Clock of the recording itself, defaults to `Date.now()`. */
42
46
  recordedAt?: number | undefined;
43
47
  };
@@ -77,25 +81,20 @@ export declare function openStatsDbReadOnly(path: string): Database;
77
81
  export declare function openStatsDbWrite(path: string): Database;
78
82
  /**
79
83
  * Insert or refresh an assistant step. Idempotent by message ID so replayed
80
- * events, restarts and NDJSON imports never duplicate usage. Non-null fields
81
- * discovered later (the routing endpoint) survive a re-record with `NULL`
82
- * through COALESCE.
84
+ * events, restarts and NDJSON imports never duplicate usage. A non-null field
85
+ * (the provider, the model, the finish reason) survives a re-record with `NULL`
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.
89
+ *
90
+ * The provider is the identity every view groups by, so it is validated as a
91
+ * token before it is stored: a value that is not a provider id is recorded as
92
+ * absent instead of becoming a grouping key.
83
93
  */
84
94
  export declare function recordStep(db: Database, record: StepRecord): void;
85
95
  export declare function recordPrompt(db: Database, record: PromptRecord): void;
86
96
  export declare function recordEvent(db: Database, record: EventRecord): void;
87
97
  export declare function upsertSession(db: Database, record: SessionRecord): void;
88
- /**
89
- * Attach the endpoint discovered after the step was recorded. A step that
90
- * already carries the same endpoint is left alone: the recorder runs on the
91
- * request path, and a no-op write there is a cost with no reader.
92
- */
93
- export declare function setStepRouter(db: Database, messageID: string, info: EndpointInfo): void;
94
- /**
95
- * Apply the endpoint learned from a compaction to every step of that session
96
- * and model that still lacks one. Returns the number of rows touched.
97
- */
98
- export declare function setStepRouterForSessionModel(db: Database, sessionID: string, modelID: string | undefined, info: EndpointInfo): number;
99
98
  /** Dump every table as NDJSON (`{"table": "...", "row": {...}}` per line). */
100
99
  export declare function exportNdjson(db: Database): string;
101
100
  /**