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
@@ -0,0 +1,114 @@
1
+ import { type LineFields, type LineLabels, type TurnTotalsView } from "./core";
2
+ /**
3
+ * The settings shared by the server, the TUI and the desktop app.
4
+ *
5
+ * The server keeps the canonical object in its plugin storage and exposes it
6
+ * over the settings RPC; every client edits the same value and receives the
7
+ * update live. Nothing here is read from `opencode.json(c)`: that file only
8
+ * declares the package, so the TUI and the Desktop can no longer disagree
9
+ * about what the plugin is configured to do.
10
+ */
11
+ export type UsageSettings = {
12
+ /** Price the steps the host reports as free, and show the estimates. */
13
+ pricing: boolean;
14
+ /** How a turn counts prompt usage: its last step, or the sum of every step. */
15
+ turnTotals: TurnTotalsView;
16
+ /** Telemetry line field toggles. */
17
+ fields: LineFields;
18
+ /** Telemetry line label overrides. */
19
+ labels: LineLabels;
20
+ /** Show the `/usage-insights` panel and its commands. */
21
+ panel: boolean;
22
+ /** TUI only: show the per-prompt history in the session sidebar. */
23
+ sidebar: boolean;
24
+ /** How many turns the TUI sidebar and the Desktop Turns tab show. */
25
+ sidebarTurns: number;
26
+ /** Read the host's OpenCode Go allowance and show the `go` view. */
27
+ quota: boolean;
28
+ /** Full subscription label; an empty string uses the host/provider default. */
29
+ quotaName: string;
30
+ };
31
+ /**
32
+ * A partial write. The client sends only what changed, so two windows editing
33
+ * different sections cannot overwrite each other's values.
34
+ */
35
+ export type UsageSettingsPatch = {
36
+ pricing?: boolean | undefined;
37
+ turnTotals?: TurnTotalsView | undefined;
38
+ fields?: Partial<LineFields> | undefined;
39
+ labels?: Partial<LineLabels> | undefined;
40
+ panel?: boolean | undefined;
41
+ sidebar?: boolean | undefined;
42
+ sidebarTurns?: number | undefined;
43
+ quota?: boolean | undefined;
44
+ quotaName?: string | undefined;
45
+ };
46
+ /**
47
+ * Server policy that is not a user setting. It is read from the environment
48
+ * (see `serverPolicy`) and returned read-only to the clients so the panel can
49
+ * hide destructive actions that the server would reject anyway.
50
+ */
51
+ export type ServerPolicy = {
52
+ /** Allow prune, wipe, vacuum and backfill over the RPC. */
53
+ maintenance: boolean;
54
+ /** Return the absolute database path in the `db` view. */
55
+ exposePaths: boolean;
56
+ };
57
+ /** The object every settings RPC method and event carries. */
58
+ export type UsageSettingsEnvelope = {
59
+ settings: UsageSettings;
60
+ policy: ServerPolicy;
61
+ };
62
+ /** The storage key in the plugin's server-side KV namespace. */
63
+ export declare const SETTINGS_STORAGE_KEY = "settings";
64
+ /** Longest label the line and the settings editors accept. */
65
+ export declare const MAX_LABEL_LENGTH = 80;
66
+ /** Longest subscription label the allowance blocks accept. */
67
+ export declare const MAX_QUOTA_NAME_LENGTH = 120;
68
+ /** The default history depth, shared with the previous option's default. */
69
+ export declare const DEFAULT_SIDEBAR_TURNS = 8;
70
+ export declare const DEFAULT_SERVER_POLICY: ServerPolicy;
71
+ export declare const DEFAULT_USAGE_SETTINGS: UsageSettings;
72
+ /** A fresh copy of the built-in settings, safe for an editor to mutate. */
73
+ export declare function defaultUsageSettings(): UsageSettings;
74
+ /** The default envelope, used before the first `get` answers or when it fails. */
75
+ export declare function defaultSettingsEnvelope(policy?: ServerPolicy): UsageSettingsEnvelope;
76
+ /**
77
+ * Fills missing or invalid fields with defaults. The server uses it when it
78
+ * reads storage and both clients use it on every RPC payload, so a partial or
79
+ * older value can never break the line, the panel or an editor.
80
+ */
81
+ export declare function sanitizeUsageSettings(value: unknown): UsageSettings;
82
+ export declare function sanitizeServerPolicy(value: unknown): ServerPolicy;
83
+ /** Reads the `{ settings, policy }` envelope used by the RPC methods and event. */
84
+ export declare function sanitizeSettingsEnvelope(value: unknown): UsageSettingsEnvelope;
85
+ /**
86
+ * Merges a patch into the current value. Unknown or invalid entries are
87
+ * dropped by the final sanitize; an invalid field never replaces a good one.
88
+ */
89
+ export declare function mergeUsageSettings(current: UsageSettings, patch: UsageSettingsPatch): UsageSettings;
90
+ /** Combines two patches, merging the nested line objects instead of replacing them. */
91
+ export declare function mergeUsagePatches(a: UsageSettingsPatch | undefined, b: UsageSettingsPatch | undefined): UsageSettingsPatch;
92
+ /** The values a renderer derives from the settings. */
93
+ export type ResolvedUsageSettings = {
94
+ format: {
95
+ labels: LineLabels;
96
+ fields: LineFields;
97
+ turnTotals: TurnTotalsView;
98
+ estimates: boolean;
99
+ };
100
+ sidebarTurns: number;
101
+ quotaName: string | undefined;
102
+ };
103
+ /** Normalizes the raw settings for the line, the panel and the sidebar. */
104
+ export declare function resolveUsageSettings(settings: UsageSettings): ResolvedUsageSettings;
105
+ /** A valid history depth typed in a settings editor. */
106
+ export declare function isValidSidebarTurns(raw: string): boolean;
107
+ export declare function parseSidebarTurns(raw: string): number | undefined;
108
+ /**
109
+ * Server policy from the environment. These are deliberately not editable
110
+ * over the RPC: `maintenance` is a safety switch for a server reachable from
111
+ * another machine, and `exposePaths` controls whether filesystem paths leave
112
+ * the server at all.
113
+ */
114
+ export declare function serverPolicy(env?: Record<string, string | undefined>): ServerPolicy;
package/dist/sidebar.d.ts CHANGED
@@ -9,8 +9,8 @@ import type { QuotaFetch } from "./quota";
9
9
  export type TurnsSidebarDeps = {
10
10
  /** Bumped by the TUI when a step or an execution ends. */
11
11
  refresh: () => number;
12
- /** How many turns to show. */
13
- limit: number;
12
+ /** How many turns to show, read reactively so a settings edit applies. */
13
+ limit: () => number;
14
14
  /** Column budget of the sidebar, shared with the summary. */
15
15
  budget?: number | undefined;
16
16
  };
@@ -18,7 +18,7 @@ export declare function TurnsSidebar(props: {
18
18
  readonly sessionID: string;
19
19
  readonly ctx: Context;
20
20
  readonly deps: TurnsSidebarDeps;
21
- /** Live Go allowance; omitted when `quota: "off"`. */
21
+ /** Live Go allowance; omitted when the shared allowance setting is off. */
22
22
  readonly quota?: (() => QuotaFetch | undefined) | undefined;
23
23
  /** Full subscription label. */
24
24
  readonly quotaName?: string | undefined;
@@ -41,6 +41,7 @@ export type StepRow = {
41
41
  cost: number;
42
42
  listCost: number;
43
43
  createdAt: number | undefined;
44
+ firstTokenAt: number | undefined;
44
45
  streamedAt: number | undefined;
45
46
  completedAt: number | undefined;
46
47
  /** `COALESCE(created_at, recorded_at)`: the ordering time of the step. */
@@ -74,6 +75,11 @@ export type CoverageReport = {
74
75
  missingModel: number;
75
76
  unsettled: number;
76
77
  missingTps: number;
78
+ /**
79
+ * Steps with a rate but no `firstToken`: their `tps` falls back to the
80
+ * request window, and the share shows how much of `tps` is not true decode.
81
+ */
82
+ missingFirstToken: number;
77
83
  firstAt: number | undefined;
78
84
  lastAt: number | undefined;
79
85
  };
@@ -88,11 +94,13 @@ type GroupedRow = StepRow;
88
94
  export type LatencyReport = {
89
95
  wall: LatencyStats;
90
96
  stream: LatencyStats;
97
+ ttft: LatencyStats;
91
98
  tps: LatencyStats;
99
+ requestTps: LatencyStats;
92
100
  };
93
101
  /** The timings of the range: one read, shared by the overall report and the groups. */
94
102
  export declare function timingRows(db: Database, options?: Options): GroupedRow[];
95
- /** Overall wall time, streaming window and throughput percentiles. */
103
+ /** Overall wall, streaming, TTFT and throughput percentiles. */
96
104
  export declare function latencyOf(rows: readonly StepRow[]): LatencyReport;
97
105
  export type LatencyGroupRow = {
98
106
  key: string;
@@ -101,10 +109,12 @@ export type LatencyGroupRow = {
101
109
  usage: Usage;
102
110
  wall: LatencyStats;
103
111
  stream: LatencyStats;
112
+ ttft: LatencyStats;
104
113
  tps: LatencyStats;
114
+ requestTps: LatencyStats;
105
115
  };
106
116
  export type Dimension = "model" | "provider";
107
- /** Wall, streaming window and throughput percentiles per group. */
117
+ /** Wall, streaming, TTFT and throughput percentiles per group. */
108
118
  export declare function latencyGroupsOf(rows: readonly StepRow[], by: Dimension): LatencyGroupRow[];
109
119
  export type CacheStats = {
110
120
  steps: number;
@@ -232,7 +242,7 @@ export type CacheDropRow = {
232
242
  * Cache reuse losses with a best-effort reason: a compaction in between, an
233
243
  * idle gap long enough to be provider-side expiry, or unknown.
234
244
  *
235
- * Compactions come from the `events` table: one query for the sessions in
245
+ * Compactions come from the `compactions` table: one query for the sessions in
236
246
  * play, never one per loss.
237
247
  */
238
248
  export declare function cacheDropsOf(db: Database, rows: readonly PairRow[], options?: {
@@ -247,6 +257,8 @@ export type ProviderSummary = {
247
257
  usage: Usage;
248
258
  cache: CacheStats;
249
259
  tps: number | undefined;
260
+ requestTps: number | undefined;
261
+ ttft: number | undefined;
250
262
  wall: number | undefined;
251
263
  firstAt: number | undefined;
252
264
  lastAt: number | undefined;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Domain constants shared by the recorder, the migrations and the import
3
+ * layer. They live below all of them so a schema migration never has to import
4
+ * a query module just to name the one event kind it understands.
5
+ */
6
+ /** Host event kind written when a compaction completes. */
7
+ export declare const COMPACTION_KIND = "compaction";
@@ -1,130 +1,10 @@
1
- import { Database } from "bun:sqlite";
2
1
  /**
3
- * Persistent usage store. One SQLite database holds every recorded step,
4
- * prompt, event and session row — and nothing else: the recorder only writes
5
- * what a view reads.
6
- *
7
- * The database is opened in WAL mode with a busy timeout so the server
8
- * recorder process and the TUI reader process can share it safely. The two
9
- * sides open it differently on purpose:
10
- *
11
- * - `openStatsDb` writes: schema, migrations and recording (the server).
12
- * - `openStatsDbReadOnly` only reads (the TUI), so no view can change the file
13
- * and no reader pays for a schema write.
14
- * - `openStatsDbWrite` is a short-lived maintenance connection (prune, wipe, vacuum)
15
- * that gives up quickly instead of holding the recorder up.
2
+ * Public surface of the stats database. The implementation is split by
3
+ * responsibility so a migration, a recorder write and an NDJSON import can be
4
+ * read and tested without loading the whole engine. This barrel preserves the
5
+ * import path every caller and test already uses.
16
6
  */
17
- export declare const SCHEMA_VERSION = 11;
18
- /** Tables carried by `exportNdjson` / `importNdjson`, in import-safe order. */
19
- export declare const TABLES: readonly ["sessions", "prompts", "events", "steps", "usage"];
20
- export type TableName = (typeof TABLES)[number];
21
- export type StepRecord = {
22
- messageID: string;
23
- sessionID: string;
24
- parentID?: string | undefined;
25
- /** The provider the model ran through, as OpenCode configured it (`opencode-go`). */
26
- providerID?: string | undefined;
27
- modelID?: string | undefined;
28
- variant?: string | undefined;
29
- input?: number | undefined;
30
- output?: number | undefined;
31
- reasoning?: number | undefined;
32
- cacheRead?: number | undefined;
33
- cacheWrite?: number | undefined;
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;
41
- createdAt?: number | undefined;
42
- streamedAt?: number | undefined;
43
- completedAt?: number | undefined;
44
- finish?: string | undefined;
45
- /** Clock of the recording itself, defaults to `Date.now()`. */
46
- recordedAt?: number | undefined;
47
- };
48
- export type PromptRecord = {
49
- sessionID: string;
50
- messageID: string;
51
- createdAt?: number | undefined;
52
- };
53
- export type EventRecord = {
54
- sessionID: string;
55
- kind: string;
56
- messageID?: string | undefined;
57
- at?: number | undefined;
58
- data?: unknown;
59
- };
60
- /**
61
- * Usage with no assistant step behind it (a compaction or a title generation).
62
- * `id` is the host event ID: it is the primary key, so a replay is ignored
63
- * instead of counted again.
64
- */
65
- export type UsageRecord = {
66
- id: string;
67
- sessionID: string;
68
- source: string;
69
- at?: number | undefined;
70
- cost?: number | undefined;
71
- input?: number | undefined;
72
- output?: number | undefined;
73
- reasoning?: number | undefined;
74
- cacheRead?: number | undefined;
75
- cacheWrite?: number | undefined;
76
- };
77
- export type SessionRecord = {
78
- sessionID: string;
79
- parentID?: string | undefined;
80
- directory?: string | undefined;
81
- title?: string | undefined;
82
- startedAt?: number | undefined;
83
- updatedAt?: number | undefined;
84
- };
85
- /** Open (creating when needed) the stats database and apply the schema. */
86
- export declare function openStatsDb(path: string): Database;
87
- /**
88
- * Reader connection for the TUI: no schema, no migration, no write. It throws
89
- * when the database is absent or was never written by the recorder, so the
90
- * caller can say so instead of showing an empty panel.
91
- */
92
- export declare function openStatsDbReadOnly(path: string): Database;
93
- /**
94
- * Short-lived write connection for maintenance. The busy timeout is short on
95
- * purpose: a prune, wipe or vacuum that cannot take the lock must fail in front of
96
- * the user, not hold the recorder's response path for seconds.
97
- */
98
- export declare function openStatsDbWrite(path: string): Database;
99
- /**
100
- * Insert or refresh an assistant step. Idempotent by message ID so replayed
101
- * events, restarts and NDJSON imports never duplicate usage. A non-null field
102
- * (the provider, the model, the finish reason) survives a re-record with `NULL`
103
- * through COALESCE. `list_cost` follows the opposite rule: a step that becomes
104
- * charged loses its estimate, and an estimate survives a replay that carries
105
- * no price table.
106
- *
107
- * The provider is the identity every view groups by, so it is validated as a
108
- * token before it is stored: a value that is not a provider id is recorded as
109
- * absent instead of becoming a grouping key.
110
- */
111
- export declare function recordStep(db: Database, record: StepRecord): void;
112
- /**
113
- * Insert usage that has no assistant step of its own. The host event ID is the
114
- * primary key: a replayed event is ignored, so the totals never double count a
115
- * compaction or a title generation delivered more than once.
116
- */
117
- export declare function recordUsage(db: Database, record: UsageRecord): void;
118
- export declare function recordPrompt(db: Database, record: PromptRecord): void;
119
- export declare function recordEvent(db: Database, record: EventRecord): void;
120
- export declare function upsertSession(db: Database, record: SessionRecord): void;
121
- /** Dump every table as NDJSON (`{"table": "...", "row": {...}}` per line). */
122
- export declare function exportNdjson(db: Database): string;
123
- /**
124
- * Load an `exportNdjson` dump back in. Rows are inserted with `OR IGNORE`, so
125
- * importing the same dump twice is harmless. Unknown tables and rows that are
126
- * not objects are rejected; a row that cannot fill a required column is
127
- * skipped rather than aborting the rest of the import. A column the row does
128
- * not carry is left to its default, the same way a hand-written insert is.
129
- */
130
- export declare function importNdjson(db: Database, text: string): number;
7
+ export { SCHEMA_VERSION, TABLES, hasTable, type TableName } from "./schema";
8
+ export { openStatsDb, openStatsDbReadOnly, openStatsDbWrite } from "./open";
9
+ export { recordCompaction, recordPrompt, recordStep, recordUsage, upsertSession, type CompactionRecord, type PromptRecord, type SessionRecord, type StepRecord, type UsageRecord, } from "./records";
10
+ export { exportNdjson, importNdjson } from "./ndjson";
@@ -0,0 +1,25 @@
1
+ /**
2
+ * A timestamp from an imported row: a finite number or a numeric string.
3
+ * `null`, booleans, empty strings and other junk are not timestamps. The
4
+ * migration has always required a real time before recovering usage; the
5
+ * import must not turn a missing one into the epoch.
6
+ */
7
+ export declare function importTimestamp(value: unknown): number | undefined;
8
+ /** Key a non-step usage row by session and time, for import deduplication. */
9
+ export declare function usageKey(sessionID: unknown, at: unknown): string | undefined;
10
+ export type LegacyCompactionUsage = {
11
+ sessionID: string;
12
+ at: number;
13
+ cost: number;
14
+ input: number;
15
+ output: number;
16
+ reasoning: number;
17
+ cacheRead: number;
18
+ cacheWrite: number;
19
+ };
20
+ /**
21
+ * Older exports carried the compaction cost and tokens in `events.data`; the
22
+ * schema no longer has that column. Recover the same fields the old migration
23
+ * read, so a backup made by an older version still imports its totals.
24
+ */
25
+ export declare function legacyCompactionUsage(row: Record<string, unknown>): LegacyCompactionUsage | undefined;
@@ -35,7 +35,7 @@ export declare function dbInfo(db: Database, path: string, now?: number): DbInfo
35
35
  export type PruneResult = {
36
36
  steps: number;
37
37
  prompts: number;
38
- events: number;
38
+ compactions: number;
39
39
  /** Compaction/title usage records deleted with the steps they belong to. */
40
40
  usage: number;
41
41
  };
@@ -0,0 +1,7 @@
1
+ import type { Database } from "bun:sqlite";
2
+ /**
3
+ * Bring an existing file up to date. The transaction keeps a failed run from
4
+ * leaving a file that is neither the old schema nor the new one; every step is
5
+ * idempotent for the retry.
6
+ */
7
+ export declare function migrate(db: Database): void;
@@ -0,0 +1,16 @@
1
+ import type { Database } from "bun:sqlite";
2
+ /** Dump every table as NDJSON (`{"table": "...", "row": {...}}` per line). */
3
+ export declare function exportNdjson(db: Database): string;
4
+ /**
5
+ * Load an `exportNdjson` dump back in. Rows are inserted with `OR IGNORE`, so
6
+ * importing the same dump twice is harmless. Unknown tables and rows that are
7
+ * not objects are rejected; a row that cannot fill a required column is
8
+ * skipped rather than aborting the rest of the import. A column the row does
9
+ * not carry is left to its default, the same way a hand-written insert is.
10
+ *
11
+ * Dumps written before the event payload was dropped still carry the
12
+ * compaction cost and tokens there: a legacy event that imports successfully
13
+ * gets the equivalent `usage` row, unless the dump or the database already has
14
+ * one for the same session and time.
15
+ */
16
+ export declare function importNdjson(db: Database, text: string): number;
@@ -0,0 +1,15 @@
1
+ import { Database } from "bun:sqlite";
2
+ /** Open (creating when needed) the stats database and apply the schema. */
3
+ export declare function openStatsDb(path: string): Database;
4
+ /**
5
+ * Reader connection for the TUI: no schema, no migration, no write. It throws
6
+ * when the database is absent or was never written by the recorder, so the
7
+ * caller can say so instead of showing an empty panel.
8
+ */
9
+ export declare function openStatsDbReadOnly(path: string): Database;
10
+ /**
11
+ * Short-lived write connection for maintenance. The busy timeout is short on
12
+ * purpose: a prune, wipe or vacuum that cannot take the lock must fail in front
13
+ * of the user, not hold the recorder's response path for seconds.
14
+ */
15
+ export declare function openStatsDbWrite(path: string): Database;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * SQLite database used when no `db` option is configured: the per-user state
2
+ * SQLite database used when no path is configured: the per-user state
3
3
  * directory of the current OS, never a shared temp directory.
4
4
  *
5
5
  * The subdirectory is the plugin's package name, never a generic one: the
@@ -20,9 +20,10 @@ export declare function defaultDbPath(env?: Record<string, string | undefined>,
20
20
  */
21
21
  export declare function expandHome(path: string, home?: string): string;
22
22
  /**
23
- * Resolve the effective database path: explicit plugin option first, then the
24
- * `OPENCODE_USAGE_INSIGHTS_DB` escape hatch (handy for dev and tests), then
25
- * the per-OS state directory. A leading `~` is expanded in all three.
23
+ * Resolve the effective database path: an explicit override first (used by
24
+ * tests and the CLI), then the `OPENCODE_USAGE_INSIGHTS_DB` server policy, then
25
+ * the per-OS state directory. A leading `~` is expanded in all three. The
26
+ * server no longer reads a `db` option from `opencode.json(c)`.
26
27
  */
27
28
  export declare function resolveDbPath(configured?: string | undefined, env?: Record<string, string | undefined>, platform?: string): string;
28
29
  /**
@@ -5,8 +5,6 @@ import type { Database } from "bun:sqlite";
5
5
  * exports. Aggregations stay in SQL; comparisons and percentiles that would
6
6
  * need window functions or custom SQLite builds are computed in JS.
7
7
  */
8
- /** Event kind written by the recorder when a compaction completes. */
9
- export declare const COMPACTION_KIND = "compaction";
10
8
  /**
11
9
  * Idle gap above which a cache reuse loss is attributed to provider-side
12
10
  * expiry rather than to a mid-session event. Heuristic: the empirical TTL
@@ -100,16 +98,18 @@ export declare const STEP_TIME = "COALESCE(created_at, recorded_at)";
100
98
  * is a different model to the provider, so a variant never shares a row with
101
99
  * its family. The JS twin is `modelKey` below; both have to agree.
102
100
  */
103
- export declare const MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
101
+ export declare const MODEL_KEY_SEPARATOR = "#";
104
102
  /** `modelKey(modelID, variant)`: the family, with the variant as a suffix. */
105
103
  export declare function modelKey(modelID: string, variant: string | undefined): string;
106
104
  /** Human label of a model key or a model id and variant. */
107
105
  export declare function modelLabel(modelID: string, variant: string | undefined): string;
108
106
  /**
109
107
  * `WHERE` for a range plus the panel filters. Shared with the analysis layer so
110
- * a filtered view and a drill-down agree on what is in scope.
108
+ * a filtered view and a drill-down agree on what is in scope. `prefix` qualifies
109
+ * the filter columns; a query that joins another table must pass its `steps`
110
+ * alias (`"st."`), or a column the two tables share is ambiguous.
111
111
  */
112
- export declare function buildWhere(range: Range | undefined, filters?: Filters | undefined, column?: string): {
112
+ export declare function buildWhere(range: Range | undefined, filters?: Filters | undefined, column?: string, prefix?: string): {
113
113
  where: string;
114
114
  params: (string | number)[];
115
115
  };
@@ -127,11 +127,20 @@ export type Overview = Usage & {
127
127
  lastAt: number | undefined;
128
128
  cacheHitRatio: number | undefined;
129
129
  /**
130
- * Tokens generated per second of streaming, over the whole selection: the
131
- * produced tokens divided by the summed streaming windows. A weighted average,
132
- * not the mean of the per-step rates the latency view reports as p50.
130
+ * Output-plus-reasoning tokens per second over the decode window, over the
131
+ * whole selection: produced tokens divided by the summed `firstToken →
132
+ * streamed` windows. This is OpenCode's definition; a step without a first
133
+ * token falls back to its request dispatch. Weighted, not the mean of the
134
+ * per-step rates the latency view reports as p50.
133
135
  */
134
136
  tps: number | undefined;
137
+ /**
138
+ * The same tokens over the request window (`created → streamed`), including
139
+ * TTFT and queueing. The conservative rate, shown as `rtps`.
140
+ */
141
+ requestTps: number | undefined;
142
+ /** Median milliseconds from request dispatch to the first streamed token. */
143
+ ttft: number | undefined;
135
144
  };
136
145
  export declare function overview(db: Database, range?: Range, filters?: Filters): Overview;
137
146
  export type ProviderUsage = Usage & {
@@ -156,28 +165,6 @@ export type TimelineBucket = {
156
165
  } & Usage;
157
166
  /** Usage aggregated into fixed time buckets (for example one hour or day). */
158
167
  export declare function timeline(db: Database, range: Range | undefined, bucketMs: number): TimelineBucket[];
159
- export type DropReason = "compaction" | "expired" | "unknown";
160
- export type CacheDropRow = {
161
- sessionID: string;
162
- messageID: string;
163
- providerID: string | undefined;
164
- modelID: string | undefined;
165
- variant: string | undefined;
166
- at: number;
167
- tokens: number;
168
- gapMs: number | undefined;
169
- prevCached: number;
170
- reason: DropReason;
171
- };
172
- export type TtlEvidenceRow = {
173
- providerID: string;
174
- modelID: string;
175
- samples: number;
176
- /** Largest idle gap that still hit the cache. */
177
- maxHitGapMs: number | undefined;
178
- /** Smallest idle gap after which reuse was lost. */
179
- minDropGapMs: number | undefined;
180
- };
181
168
  export type LatencyStats = {
182
169
  count: number;
183
170
  p50: number | undefined;
@@ -189,8 +176,12 @@ export type LatencyReport = {
189
176
  wall: LatencyStats;
190
177
  /** Milliseconds from request to the last streamed chunk (the streaming window). */
191
178
  stream: LatencyStats;
192
- /** Output-plus-reasoning tokens per second over that window. */
179
+ /** Milliseconds from request dispatch to the first streamed token. */
180
+ ttft: LatencyStats;
181
+ /** Output-plus-reasoning tokens per second over the decode window. */
193
182
  tps: LatencyStats;
183
+ /** Output-plus-reasoning tokens per second over the request window (includes TTFT). */
184
+ requestTps: LatencyStats;
194
185
  };
195
186
  /** Nearest-rank percentile over an unsorted sample. */
196
187
  export declare function percentile(values: readonly number[], p: number): number | undefined;
@@ -218,7 +209,7 @@ export declare function sessions(db: Database, options?: {
218
209
  /** Sessions whose parent is `parentID`: the subagents of one session. */
219
210
  export declare function childSessionIDs(db: Database, parentID: string): string[];
220
211
  /** Session usage rows for a specific set of sessions (subagent rollups). */
221
- export declare function sessionUsageOf(db: Database, sessionIDs: readonly string[]): SessionUsage[];
212
+ export declare function sessionUsageOf(db: Database, sessionIDs: readonly string[], filters?: Filters): SessionUsage[];
222
213
  export type TurnDrop = {
223
214
  messageID: string;
224
215
  tokens: number;
@@ -256,11 +247,15 @@ export type TurnUsage = {
256
247
  /** Finish reason of the turn's last step. */
257
248
  finish: string | undefined;
258
249
  /**
259
- * Tokens generated per second of streaming over the turn's steps: produced
260
- * tokens divided by their summed streaming windows. For a one-step turn it is
261
- * that step's rate.
250
+ * Output-plus-reasoning tokens per second over the turn's decode windows:
251
+ * produced tokens divided by the summed `firstToken → streamed` windows. For
252
+ * a one-step turn it is that step's rate, matching OpenCode.
262
253
  */
263
254
  tps: number | undefined;
255
+ /** The same tokens over the request windows, including TTFT; the conservative rate. */
256
+ requestTps: number | undefined;
257
+ /** Milliseconds from the first step's dispatch to its first streamed token. */
258
+ ttft: number | undefined;
264
259
  };
265
260
  /**
266
261
  * Finished turns, newest first. Steps belong to the newest prompt recorded at or