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

usage.ts

194 lines7.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`) 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, provider, model)` buckets. Raw
11 * 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 = 3 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​
42/**
43 * Why a bucket's cost is what it is.
44 *
45 * - `providerReported` - the transcript carried an explicit cost figure.
46 * - `modelPriced` - we matched the model against the LiteLLM rate table.
47 * - `unpriced` - tokens are known, rates are not. Counted in totals, excluded
48 * from cost.
49 */
50export const UsageCostSource = Schema.Literals(["providerReported", "modelPriced", "unpriced"]);
51export type UsageCostSource = typeof UsageCostSource.Type;
52​
53/**
54 * Token counts for a bucket.
55 *
56 * `cachedInputTokens` and `cacheCreationTokens` are disjoint from
57 * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`
58 * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic
59 * folds thinking into output), so it must never be added on top.
60 */
61export const UsageTokenTotals = Schema.Struct({
62 uncachedInputTokens: NonNegativeInt,
63 cachedInputTokens: NonNegativeInt,
64 cacheCreationTokens: NonNegativeInt,
65 outputTokens: NonNegativeInt,
66 reasoningTokens: NonNegativeInt,
67});
68export type UsageTokenTotals = typeof UsageTokenTotals.Type;
69​
70/**
71 * One `(day, provider, model)` cell.
72 *
73 * `costUsd` is the raw API-equivalent cost of these tokens. It is not money
74 * spent: subscription plans bill separately. `unpricedRecords` counts records
75 * whose tokens are included in the token totals but which contributed nothing
76 * to `costUsd`.
77 */
78export const UsageBucket = Schema.Struct({
79 day: UsageDay,
80 provider: UsageProviderKind,
81 model: TrimmedNonEmptyString,
82 totals: UsageTokenTotals,
83 costUsd: Schema.Number,
84 /**
85 * What the cached input would have cost at full input rates minus what it
86 * actually cost. Requires the rate table, so it is computed alongside cost
87 * rather than derived on the client.
88 */
89 cacheSavingsUsd: Schema.Number,
90 costSource: UsageCostSource,
91 /** Distinct assistant responses, after de-duplication. */
92 records: NonNegativeInt,
93 unpricedRecords: NonNegativeInt,
94 /** Distinct transcript sessions that contributed to this cell. */
95 sessions: NonNegativeInt,
96});
97export type UsageBucket = typeof UsageBucket.Type;
98​
99/**
100 * Identifies the physical transcript directory a source read from.
101 *
102 * Two environments on the same machine (worktree servers, for example) resolve
103 * the same provider home and would otherwise double count. The client drops
104 * duplicate fingerprints before merging.
105 */
106export const UsageSourceFingerprint = Schema.Struct({
107 hostId: TrimmedNonEmptyString,
108 provider: UsageProviderKind,
109 resolvedHomePath: TrimmedNonEmptyString,
110 /**
111 * Filesystem identity of the transcript directory, as `device:inode`.
112 *
113 * Hostname and path alone are not enough: every Mac in a fleet resolves
114 * `/Users/<user>/.claude`, so two machines that happen to share a hostname
115 * would look like one source and have their usage silently dropped. The
116 * device/inode pair is stable for two servers reading the same directory and
117 * effectively never collides across machines. Empty when it cannot be read.
118 */
119 volumeId: Schema.String,
120});
121export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
122​
123export const UsageSourceStatus = Schema.Literals(["ok", "missing", "partial", "failed"]);
124export type UsageSourceStatus = typeof UsageSourceStatus.Type;
125​
126export const UsageSource = Schema.Struct({
127 fingerprint: UsageSourceFingerprint,
128 status: UsageSourceStatus,
129 scannedFiles: NonNegativeInt,
130 skippedFiles: NonNegativeInt,
131 /** Records that parsed but carried no recognisable usage payload. */
132 malformedRecords: NonNegativeInt,
133 /**
134 * Distinct transcript sessions seen under this directory. Buckets also carry
135 * per-bucket session counts, but a session spans days and models, so summing
136 * those overcounts; this is the figure clients should total.
137 */
138 distinctSessions: NonNegativeInt,
139 message: Schema.NullOr(TrimmedNonEmptyString),
140});
141export type UsageSource = typeof UsageSource.Type;
142​
143export const UsagePricingStatus = Schema.Literals(["fresh", "cached", "unavailable"]);
144export type UsagePricingStatus = typeof UsagePricingStatus.Type;
145​
146/**
147 * Provenance for the rate table, so the UI can be honest about how good the
148 * cost figures are.
149 */
150export const UsagePricing = Schema.Struct({
151 status: UsagePricingStatus,
152 source: TrimmedNonEmptyString,
153 fetchedAt: Schema.NullOr(Schema.String),
154 knownModels: NonNegativeInt,
155});
156export type UsagePricing = typeof UsagePricing.Type;
157​
158export const UsageSummaryInput = Schema.Struct({
159 /** Inclusive first day of the window, in `timeZone`. */
160 sinceDay: UsageDay,
161 /** Inclusive last day of the window, in `timeZone`. */
162 untilDay: UsageDay,
163 /**
164 * IANA zone the client wants days bucketed in. An offset would be wrong for
165 * any window that crosses a DST boundary.
166 */
167 timeZone: TrimmedNonEmptyString,
168});
169export type UsageSummaryInput = typeof UsageSummaryInput.Type;
170​
171export const UsageSummary = Schema.Struct({
172 contractVersion: Schema.Number,
173 readAt: Schema.String,
174 timeZone: TrimmedNonEmptyString,
175 sinceDay: UsageDay,
176 untilDay: UsageDay,
177 buckets: Schema.Array(UsageBucket),
178 sources: Schema.Array(UsageSource),
179 pricing: UsagePricing,
180 /** Wall-clock cost of the scan, surfaced in diagnostics. */
181 scanDurationMs: NonNegativeInt,
182});
183export type UsageSummary = typeof UsageSummary.Type;
184​
185export class UsageReadError extends Schema.TaggedErrorClass<UsageReadError>()("UsageReadError", {
186 reason: Schema.Literals(["scanFailed", "invalidWindow"]),
187 /** Stable, bounded description. The underlying failure travels in `cause`. */
188 detail: TrimmedNonEmptyString,
189 cause: Schema.optional(Schema.Defect()),
190}) {
191 override get message(): string {
192 return `Usage read failed (${this.reason}): ${this.detail}`;
193 }