Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import { ForwardCompatibleArray, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
4
5/**
6 * Bumped whenever the shape of {@link UsageSummary} changes incompatibly.
7 * Adding providers or other array-element variants is additive: unknown entries
8 * are skipped on decode and do not require a version bump.
9 */
10export const USAGE_CONTRACT_VERSION = 6 as const;
11
12export const USAGE_MERGE_COMPATIBLE_SINCE = 4 as const;
13
14export const UsageProviderKind = Schema.Literals([
15 "claude",
16 "codex",
17 "grok",
18 "cursor",
19 "opencode",
20 "antigravity",
21 "pi",
22 "muse",
23]);
24export type UsageProviderKind = typeof UsageProviderKind.Type;
25
26const USAGE_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
27
28export const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(
29 Schema.brand("UsageDay"),
30);
31export type UsageDay = typeof UsageDay.Type;
32
33export const UsageResolution = Schema.Literals(["day", "hour"]);
34export type UsageResolution = typeof UsageResolution.Type;
35
36export const UsageCostSource = Schema.Literals(["providerReported", "modelPriced", "unpriced"]);
37export type UsageCostSource = typeof UsageCostSource.Type;
38
39/**
40 * `cachedInputTokens` and `cacheCreationTokens` are disjoint from
41 * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`
42 * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic
43 * folds thinking into output), so it must never be added on top.
44 */
45export const UsageTokenTotals = Schema.Struct({
46 uncachedInputTokens: NonNegativeInt,
47 cachedInputTokens: NonNegativeInt,
48 cacheCreationTokens: NonNegativeInt,
49 outputTokens: NonNegativeInt,
50 reasoningTokens: NonNegativeInt,
51});
52export type UsageTokenTotals = typeof UsageTokenTotals.Type;
53
54export const UsageCategoryCost = Schema.Struct({
55 input: Schema.Number,
56 cacheRead: Schema.Number,
57 cacheWrite: Schema.Number,
58 output: Schema.Number,
59});
60export type UsageCategoryCost = typeof UsageCategoryCost.Type;
61
62export const UsageBucket = Schema.Struct({
63 day: UsageDay,
64 hourStart: Schema.optional(TrimmedNonEmptyString),
65 provider: UsageProviderKind,
66 model: TrimmedNonEmptyString,
67 sourcePath: Schema.optional(TrimmedNonEmptyString),
68 totals: UsageTokenTotals,
69 costUsd: Schema.Number,
70 cacheSavingsUsd: Schema.Number,
71 categoryCostUsd: Schema.optional(UsageCategoryCost),
72 fastCostUsd: Schema.optional(Schema.Number),
73 ultrafastCostUsd: Schema.optional(Schema.Number),
74 speedPremiumUsd: Schema.optional(Schema.Number),
75 costSource: UsageCostSource,
76 records: NonNegativeInt,
77 unpricedRecords: NonNegativeInt,
78 sessions: NonNegativeInt,
79});
80export type UsageBucket = typeof UsageBucket.Type;
81
82export const UsageSourceFingerprint = Schema.Struct({
83 hostId: TrimmedNonEmptyString,
84 provider: UsageProviderKind,
85 resolvedHomePath: TrimmedNonEmptyString,
86 /**
87 * Filesystem identity of the transcript directory, as `device:inode`.
88 * Hostname and path alone are not enough: every Mac in a fleet resolves
89 * `/Users/<user>/.claude`, so two machines that happen to share a hostname
90 * would look like one source and have their usage silently dropped.
91 */
92 volumeId: Schema.String,
93});
94export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
95
96export const UsageSourceStatus = Schema.Literals(["ok", "missing", "partial", "failed"]);
97export type UsageSourceStatus = typeof UsageSourceStatus.Type;
98
99export const UsageSource = Schema.Struct({
100 fingerprint: UsageSourceFingerprint,
101 status: UsageSourceStatus,
102 scannedFiles: NonNegativeInt,
103 skippedFiles: NonNegativeInt,
104 malformedRecords: NonNegativeInt,
105 /**
106 * Buckets also carry per-bucket session counts, but a session spans days and
107 * models, so summing those overcounts; this is the figure clients should
108 * total.
109 */
110 distinctSessions: NonNegativeInt,
111 message: Schema.NullOr(TrimmedNonEmptyString),
112 action: Schema.optionalKey(Schema.Literal("enableCursorKeychain")),
113 /**
114 * Present when this source answered from its cache while a slow refresh (an
115 * account API, for example) runs. Repeat the request with `awaitRefresh` to
116 * get the refreshed source.
117 */
118 refreshing: Schema.optionalKey(Schema.Literal(true)),
119});
120export type UsageSource = typeof UsageSource.Type;
121
122export const UsagePricingStatus = Schema.Literals(["fresh", "cached", "unavailable"]);
123export type UsagePricingStatus = typeof UsagePricingStatus.Type;
124
125export const UsagePricing = Schema.Struct({
126 status: UsagePricingStatus,
127 source: TrimmedNonEmptyString,
128 fetchedAt: Schema.NullOr(Schema.String),
129 knownModels: NonNegativeInt,
130});
131export type UsagePricing = typeof UsagePricing.Type;
132
133export const UsageSummaryInput = Schema.Struct({
134 sinceDay: UsageDay,
135 untilDay: UsageDay,
136 /**
137 * IANA zone the client wants days bucketed in. An offset would be wrong for
138 * any window that crosses a DST boundary.
139 */
140 timeZone: TrimmedNonEmptyString,
141 resolution: Schema.optional(UsageResolution),
142 sinceTime: Schema.optional(TrimmedNonEmptyString),
143 untilTime: Schema.optional(TrimmedNonEmptyString),
144 awaitRefresh: Schema.optional(Schema.Boolean),
145});
146export type UsageSummaryInput = typeof UsageSummaryInput.Type;
147
148export const UsageSummary = Schema.Struct({
149 contractVersion: Schema.Number,
150 readAt: Schema.String,
151 timeZone: TrimmedNonEmptyString,
152 sinceDay: UsageDay,
153 untilDay: UsageDay,
154 buckets: ForwardCompatibleArray(UsageBucket),
155 sources: ForwardCompatibleArray(UsageSource),
156 pricing: UsagePricing,
157 scanDurationMs: NonNegativeInt,
158});
159export type UsageSummary = typeof UsageSummary.Type;
160
161export class UsageReadError extends Schema.TaggedError<UsageReadError>()("UsageReadError", {
162 reason: Schema.Literals(["scanFailed", "invalidWindow"]),
163 detail: TrimmedNonEmptyString,
164 cause: Schema.optional(Schema.Defect()),
165}) {
166 override get message(): string {
167 return `Usage read failed (${this.reason}): ${this.detail}`;
168 }
169}