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

usage.ts

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