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

usage.ts

168 lines5.8 KB

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