Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

207 lines7.8 KB

1/**
2 * Usage reporting contract.
3 *
4 * Each environment scans the provider CLIs' own on-disk session transcripts
5 * (`~/.claude/projects/**\/*.jsonl`, `~/.codex/sessions/**\/*.jsonl`, OpenCode's
6 * SQLite store at `~/.local/share/opencode/opencode.db`) rather than relying on
7 * T3 Code's own orchestration projections, so usage stays complete even for
8 * turns that were never driven through T3 Code. This mirrors the approach
9 * `ccusage` takes.
10 *
11 * Environments return pre-aggregated `(day, hourStart?, provider, model)`
12 * buckets. Raw transcript records never cross the wire.
13 *
14 * @module usage
15 */
16import * as Schema from "effect/Schema";
17​
18import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
19​
20/**
21 * Bumped whenever the shape of {@link UsageSummary} changes incompatibly. The
22 * client renders partial coverage when an environment reports an older version
23 * rather than failing the whole page.
24 */
25export const USAGE_CONTRACT_VERSION = 4 as const;
26​
27export const UsageProviderKind = Schema.Literals(["claude", "codex", "opencode"]);
28export type UsageProviderKind = typeof UsageProviderKind.Type;
29​
30/**
31 * A calendar day in the reporting time zone, formatted `YYYY-MM-DD`.
32 *
33 * Days are bucketed server-side so that a turn always lands on the day the user
34 * experienced it, not the UTC day.
35 */
36const USAGE_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
37​
38export const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(
39 Schema.brand("UsageDay"),
40);
41export type UsageDay = typeof UsageDay.Type;
42​
43export const UsageResolution = Schema.Literals(["day", "hour"]);
44export type UsageResolution = typeof UsageResolution.Type;
45​
46/**
47 * Why a bucket's cost is what it is.
48 *
49 * - `providerReported` - the transcript carried an explicit cost figure.
50 * - `modelPriced` - we matched the model against a rate table (LiteLLM, or
51 * models.dev for OpenCode's go/zen models).
52 * - `unpriced` - tokens are known, rates are not. Counted in totals, excluded
53 * from cost.
54 */
55export const UsageCostSource = Schema.Literals(["providerReported", "modelPriced", "unpriced"]);
56export type UsageCostSource = typeof UsageCostSource.Type;
57​
58/**
59 * Token counts for a bucket.
60 *
61 * `cachedInputTokens` and `cacheCreationTokens` are disjoint from
62 * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`
63 * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic
64 * folds thinking into output), so it must never be added on top.
65 */
66export const UsageTokenTotals = Schema.Struct({
67 uncachedInputTokens: NonNegativeInt,
68 cachedInputTokens: NonNegativeInt,
69 cacheCreationTokens: NonNegativeInt,
70 outputTokens: NonNegativeInt,
71 reasoningTokens: NonNegativeInt,
72});
73export type UsageTokenTotals = typeof UsageTokenTotals.Type;
74​
75/**
76 * One `(day, hourStart?, provider, model)` cell. `hourStart` is the UTC start
77 * instant of a rolling bucket and is present only for hourly requests.
78 *
79 * `costUsd` is the raw API-equivalent cost of these tokens. It is not money
80 * spent: subscription plans bill separately. `unpricedRecords` counts records
81 * whose tokens are included in the token totals but which contributed nothing
82 * to `costUsd`.
83 */
84export const UsageBucket = Schema.Struct({
85 day: UsageDay,
86 hourStart: Schema.optional(TrimmedNonEmptyString),
87 provider: UsageProviderKind,
88 model: TrimmedNonEmptyString,
89 totals: UsageTokenTotals,
90 costUsd: Schema.Number,
91 /**
92 * What the cached input would have cost at full input rates minus what it
93 * actually cost. Requires the rate table, so it is computed alongside cost
94 * rather than derived on the client.
95 */
96 cacheSavingsUsd: Schema.Number,
97 costSource: UsageCostSource,
98 /** Distinct assistant responses, after de-duplication. */
99 records: NonNegativeInt,
100 unpricedRecords: NonNegativeInt,
101 /** Distinct transcript sessions that contributed to this cell. */
102 sessions: NonNegativeInt,
103});
104export type UsageBucket = typeof UsageBucket.Type;
105​
106/**
107 * Identifies the physical transcript directory a source read from.
108 *
109 * Two environments on the same machine (worktree servers, for example) resolve
110 * the same provider home and would otherwise double count. The client drops
111 * duplicate fingerprints before merging.
112 */
113export const UsageSourceFingerprint = Schema.Struct({
114 hostId: TrimmedNonEmptyString,
115 provider: UsageProviderKind,
116 resolvedHomePath: TrimmedNonEmptyString,
117 /**
118 * Filesystem identity of the transcript directory, as `device:inode`.
119 *
120 * Hostname and path alone are not enough: every Mac in a fleet resolves
121 * `/Users/<user>/.claude`, so two machines that happen to share a hostname
122 * would look like one source and have their usage silently dropped. The
123 * device/inode pair is stable for two servers reading the same directory and
124 * effectively never collides across machines. Empty when it cannot be read.
125 */
126 volumeId: Schema.String,
127});
128export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
129​
130export const UsageSourceStatus = Schema.Literals(["ok", "missing", "partial", "failed"]);
131export type UsageSourceStatus = typeof UsageSourceStatus.Type;
132​
133export const UsageSource = Schema.Struct({
134 fingerprint: UsageSourceFingerprint,
135 status: UsageSourceStatus,
136 scannedFiles: NonNegativeInt,
137 skippedFiles: NonNegativeInt,
138 /** Records that parsed but carried no recognisable usage payload. */
139 malformedRecords: NonNegativeInt,
140 /**
141 * Distinct transcript sessions seen under this directory. Buckets also carry
142 * per-bucket session counts, but a session spans days and models, so summing
143 * those overcounts; this is the figure clients should total.
144 */
145 distinctSessions: NonNegativeInt,
146 message: Schema.NullOr(TrimmedNonEmptyString),
147});
148export type UsageSource = typeof UsageSource.Type;
149​
150export const UsagePricingStatus = Schema.Literals(["fresh", "cached", "unavailable"]);
151export type UsagePricingStatus = typeof UsagePricingStatus.Type;
152​
153/**
154 * Provenance for the rate table, so the UI can be honest about how good the
155 * cost figures are.
156 */
157export const UsagePricing = Schema.Struct({
158 status: UsagePricingStatus,
159 source: TrimmedNonEmptyString,
160 fetchedAt: Schema.NullOr(Schema.String),
161 knownModels: NonNegativeInt,
162});
163export type UsagePricing = typeof UsagePricing.Type;
164​
165export const UsageSummaryInput = Schema.Struct({
166 /** Inclusive first day of the window, in `timeZone`. */
167 sinceDay: UsageDay,
168 /** Inclusive last day of the window, in `timeZone`. */
169 untilDay: UsageDay,
170 /**
171 * IANA zone the client wants days bucketed in. An offset would be wrong for
172 * any window that crosses a DST boundary.
173 */
174 timeZone: TrimmedNonEmptyString,
175 /** Defaults to daily for older clients. */
176 resolution: Schema.optional(UsageResolution),
177 /** Inclusive UTC instant for an hourly rolling window. */
178 sinceTime: Schema.optional(TrimmedNonEmptyString),
179 /** Exclusive UTC instant for an hourly rolling window. */
180 untilTime: Schema.optional(TrimmedNonEmptyString),
181});
182export type UsageSummaryInput = typeof UsageSummaryInput.Type;
183​
184export const UsageSummary = Schema.Struct({
185 contractVersion: Schema.Number,
186 readAt: Schema.String,
187 timeZone: TrimmedNonEmptyString,
188 sinceDay: UsageDay,
189 untilDay: UsageDay,
190 buckets: Schema.Array(UsageBucket),
191 sources: Schema.Array(UsageSource),
192 pricing: UsagePricing,
193 /** Wall-clock cost of the scan, surfaced in diagnostics. */
194 scanDurationMs: NonNegativeInt,
195});
196export type UsageSummary = typeof UsageSummary.Type;
197​
198export class UsageReadError extends Schema.TaggedErrorClass<UsageReadError>()("UsageReadError", {
199 reason: Schema.Literals(["scanFailed", "invalidWindow"]),
200 /** Stable, bounded description. The underlying failure travels in `cause`. */
201 detail: TrimmedNonEmptyString,
202 cause: Schema.optional(Schema.Defect()),
203}) {
204 override get message(): string {
205 return `Usage read failed (${this.reason}): ${this.detail}`;
206 }