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

usage.ts

258 lines9.7 KB

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 { ForwardCompatibleArray, 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 * Adding providers or other array-element variants is additive: unknown
21 * entries are skipped on decode and do not require a version bump. So are
22 * optional bucket fields, which older clients ignore.
23 */
24export const USAGE_CONTRACT_VERSION = 6 as const;
25​
26/**
27 * Oldest {@link UsageSummary} version a current client will still merge.
28 *
29 * v5/v6 add providers and optional source attribution; v4 Claude/Codex
30 * buckets remain valid in mixed-version environments.
31 */
32export const USAGE_MERGE_COMPATIBLE_SINCE = 4 as const;
33​
34export const UsageProviderKind = Schema.Literals([
35 "claude",
36 "codex",
37 "grok",
38 "cursor",
39 "opencode",
40 "antigravity",
41]);
42export type UsageProviderKind = typeof UsageProviderKind.Type;
43​
44/**
45 * A calendar day in the reporting time zone, formatted `YYYY-MM-DD`.
46 *
47 * Days are bucketed server-side so that a turn always lands on the day the user
48 * experienced it, not the UTC day.
49 */
50const USAGE_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
51​
52export const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(
53 Schema.brand("UsageDay"),
54);
55export type UsageDay = typeof UsageDay.Type;
56​
57export const UsageResolution = Schema.Literals(["day", "hour"]);
58export type UsageResolution = typeof UsageResolution.Type;
59​
60/**
61 * Why a bucket's cost is what it is.
62 *
63 * - `providerReported` - the transcript carried an explicit cost figure.
64 * - `modelPriced` - we used a custom price override or the LiteLLM rate table.
65 * - `unpriced` - tokens are known, rates are not. Counted in totals, excluded
66 * from cost.
67 */
68export const UsageCostSource = Schema.Literals(["providerReported", "modelPriced", "unpriced"]);
69export type UsageCostSource = typeof UsageCostSource.Type;
70​
71/**
72 * Token counts for a bucket.
73 *
74 * `cachedInputTokens` and `cacheCreationTokens` are disjoint from
75 * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`
76 * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic
77 * folds thinking into output), so it must never be added on top.
78 */
79export const UsageTokenTotals = Schema.Struct({
80 uncachedInputTokens: NonNegativeInt,
81 cachedInputTokens: NonNegativeInt,
82 cacheCreationTokens: NonNegativeInt,
83 outputTokens: NonNegativeInt,
84 reasoningTokens: NonNegativeInt,
85});
86export type UsageTokenTotals = typeof UsageTokenTotals.Type;
87​
88/**
89 * A bucket's cost split by token category, in USD. A provider-reported cost is
90 * split in proportion to the model's list rates.
91 */
92export const UsageCategoryCost = Schema.Struct({
93 input: Schema.Number,
94 cacheRead: Schema.Number,
95 cacheWrite: Schema.Number,
96 output: Schema.Number,
97});
98export type UsageCategoryCost = typeof UsageCategoryCost.Type;
99​
100/**
101 * One `(day, hourStart?, provider, model)` cell. `hourStart` is the UTC start
102 * instant of a rolling bucket and is present only for hourly requests.
103 *
104 * `costUsd` is the raw API-equivalent cost of these tokens. It is not money
105 * spent: subscription plans bill separately. `unpricedRecords` counts records
106 * whose tokens are included in the token totals but which contributed nothing
107 * to `costUsd`.
108 */
109export const UsageBucket = Schema.Struct({
110 day: UsageDay,
111 hourStart: Schema.optional(TrimmedNonEmptyString),
112 provider: UsageProviderKind,
113 model: TrimmedNonEmptyString,
114 /** Source directory, so overlapping multi-home environments merge once per source. */
115 sourcePath: Schema.optional(TrimmedNonEmptyString),
116 totals: UsageTokenTotals,
117 costUsd: Schema.Number,
118 /**
119 * What the cached input would have cost at full input rates minus what it
120 * actually cost. Requires the rate table, so it is computed alongside cost
121 * rather than derived on the client.
122 */
123 cacheSavingsUsd: Schema.Number,
124 /**
125 * `costUsd` by token category. Cost with no known rates stays out of it, and
126 * it is absent when nothing could be split or the server predates it.
127 */
128 categoryCostUsd: Schema.optional(UsageCategoryCost),
129 /** Cost of fast and ultrafast requests. Absent when zero; the rest is standard. */
130 fastCostUsd: Schema.optional(Schema.Number),
131 ultrafastCostUsd: Schema.optional(Schema.Number),
132 /** What fast and ultrafast requests cost above the standard rate. Absent when zero. */
133 speedPremiumUsd: Schema.optional(Schema.Number),
134 costSource: UsageCostSource,
135 /** Distinct assistant responses, after de-duplication. */
136 records: NonNegativeInt,
137 unpricedRecords: NonNegativeInt,
138 /** Distinct transcript sessions that contributed to this cell. */
139 sessions: NonNegativeInt,
140});
141export type UsageBucket = typeof UsageBucket.Type;
142​
143/**
144 * Identifies the physical transcript directory a source read from.
145 *
146 * Two environments on the same machine (worktree servers, for example) resolve
147 * the same provider home and would otherwise double count. The client drops
148 * duplicate fingerprints before merging.
149 */
150export const UsageSourceFingerprint = Schema.Struct({
151 hostId: TrimmedNonEmptyString,
152 provider: UsageProviderKind,
153 resolvedHomePath: TrimmedNonEmptyString,
154 /**
155 * Filesystem identity of the transcript directory, as `device:inode`.
156 *
157 * Hostname and path alone are not enough: every Mac in a fleet resolves
158 * `/Users/<user>/.claude`, so two machines that happen to share a hostname
159 * would look like one source and have their usage silently dropped. The
160 * device/inode pair is stable for two servers reading the same directory and
161 * effectively never collides across machines. Empty when it cannot be read.
162 */
163 volumeId: Schema.String,
164});
165export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
166​
167export const UsageSourceStatus = Schema.Literals(["ok", "missing", "partial", "failed"]);
168export type UsageSourceStatus = typeof UsageSourceStatus.Type;
169​
170export const UsageSource = Schema.Struct({
171 fingerprint: UsageSourceFingerprint,
172 status: UsageSourceStatus,
173 scannedFiles: NonNegativeInt,
174 skippedFiles: NonNegativeInt,
175 /** Records that parsed but carried no recognisable usage payload. */
176 malformedRecords: NonNegativeInt,
177 /**
178 * Distinct transcript sessions seen under this directory. Buckets also carry
179 * per-bucket session counts, but a session spans days and models, so summing
180 * those overcounts; this is the figure clients should total.
181 */
182 distinctSessions: NonNegativeInt,
183 message: Schema.NullOr(TrimmedNonEmptyString),
184 /** An action the client can offer to make this source available. */
185 action: Schema.optionalKey(Schema.Literal("enableCursorKeychain")),
186 /**
187 * Present when this source answered from its cache while a slow refresh (an
188 * account API, for example) runs. Repeat the request with `awaitRefresh` to
189 * get the refreshed source.
190 */
191 refreshing: Schema.optionalKey(Schema.Literal(true)),
192});
193export type UsageSource = typeof UsageSource.Type;
194​
195export const UsagePricingStatus = Schema.Literals(["fresh", "cached", "unavailable"]);
196export type UsagePricingStatus = typeof UsagePricingStatus.Type;
197​
198/**
199 * Provenance for the rate table, so the UI can be honest about how good the
200 * cost figures are.
201 */
202export const UsagePricing = Schema.Struct({
203 status: UsagePricingStatus,
204 source: TrimmedNonEmptyString,
205 fetchedAt: Schema.NullOr(Schema.String),
206 knownModels: NonNegativeInt,
207});
208export type UsagePricing = typeof UsagePricing.Type;
209​
210export const UsageSummaryInput = Schema.Struct({
211 /** Inclusive first day of the window, in `timeZone`. */
212 sinceDay: UsageDay,
213 /** Inclusive last day of the window, in `timeZone`. */
214 untilDay: UsageDay,
215 /**
216 * IANA zone the client wants days bucketed in. An offset would be wrong for
217 * any window that crosses a DST boundary.
218 */
219 timeZone: TrimmedNonEmptyString,
220 /** Defaults to daily for older clients. */
221 resolution: Schema.optional(UsageResolution),
222 /** Inclusive UTC instant for an hourly rolling window. */
223 sinceTime: Schema.optional(TrimmedNonEmptyString),
224 /** Exclusive UTC instant for an hourly rolling window. */
225 untilTime: Schema.optional(TrimmedNonEmptyString),
226 /**
227 * Wait for slow sources to finish refreshing instead of answering from their
228 * cache. Clients send it as the follow-up to a summary with a `refreshing`
229 * source. Older servers ignore it and always wait.
230 */
231 awaitRefresh: Schema.optional(Schema.Boolean),
232});
233export type UsageSummaryInput = typeof UsageSummaryInput.Type;
234​
235export const UsageSummary = Schema.Struct({
236 contractVersion: Schema.Number,
237 readAt: Schema.String,
238 timeZone: TrimmedNonEmptyString,
239 sinceDay: UsageDay,
240 untilDay: UsageDay,
241 buckets: ForwardCompatibleArray(UsageBucket),
242 sources: ForwardCompatibleArray(UsageSource),
243 pricing: UsagePricing,
244 /** Wall-clock cost of the scan, surfaced in diagnostics. */
245 scanDurationMs: NonNegativeInt,
246});
247export type UsageSummary = typeof UsageSummary.Type;
248​
249export class UsageReadError extends Schema.TaggedError<UsageReadError>()("UsageReadError", {
250 reason: Schema.Literals(["scanFailed", "invalidWindow"]),
251 /** Stable, bounded description. The underlying failure travels in `cause`. */
252 detail: TrimmedNonEmptyString,
253 cause: Schema.optional(Schema.Defect()),
254}) {
255 override get message(): string {
256 return `Usage read failed (${this.reason}): ${this.detail}`;
257 }