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