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