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

usage.ts

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