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

usage.ts

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