Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import {
4 ForwardCompatibleArray,
5 NonBlankString,
6 NonNegativeInt,
7 TrimmedNonEmptyString,
8} from "./baseSchemas.ts";
9import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
10
11/** Bump for incompatible UsageSummary changes; skipped unknown array variants need no bump. */
12export const USAGE_CONTRACT_VERSION = 6 as const;
13
14export const USAGE_MERGE_COMPATIBLE_SINCE = 4 as const;
15
16export const UsageProviderKind = Schema.Literals([
17 "claude",
18 "codex",
19 "grok",
20 "cursor",
21 "opencode",
22 "antigravity",
23 "pi",
24 "muse",
25]);
26export type UsageProviderKind = typeof UsageProviderKind.Type;
27
28const USAGE_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
29
30export const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(
31 Schema.brand("UsageDay"),
32);
33export type UsageDay = typeof UsageDay.Type;
34
35export const UsageResolution = Schema.Literals(["day", "hour"]);
36export type UsageResolution = typeof UsageResolution.Type;
37
38export const UsageCostSource = Schema.Literals(["providerReported", "modelPriced", "unpriced"]);
39export type UsageCostSource = typeof UsageCostSource.Type;
40
41/** Sum uncached input, cache reads, and cache writes for input totals; reasoning is already included in output. */
42export const UsageTokenTotals = Schema.Struct({
43 uncachedInputTokens: NonNegativeInt,
44 cachedInputTokens: NonNegativeInt,
45 cacheCreationTokens: NonNegativeInt,
46 outputTokens: NonNegativeInt,
47 reasoningTokens: NonNegativeInt,
48});
49export type UsageTokenTotals = typeof UsageTokenTotals.Type;
50
51export const UsageCategoryCost = Schema.Struct({
52 input: Schema.Number,
53 cacheRead: Schema.Number,
54 cacheWrite: Schema.Number,
55 output: Schema.Number,
56});
57export type UsageCategoryCost = typeof UsageCategoryCost.Type;
58
59export const UsageBucket = Schema.Struct({
60 day: UsageDay,
61 hourStart: Schema.optional(TrimmedNonEmptyString),
62 provider: UsageProviderKind,
63 model: TrimmedNonEmptyString,
64 sourcePath: Schema.optional(NonBlankString),
65 totals: UsageTokenTotals,
66 costUsd: Schema.Number,
67 cacheSavingsUsd: Schema.Number,
68 categoryCostUsd: Schema.optional(UsageCategoryCost),
69 fastCostUsd: Schema.optional(Schema.Number),
70 ultrafastCostUsd: Schema.optional(Schema.Number),
71 speedPremiumUsd: Schema.optional(Schema.Number),
72 costSource: UsageCostSource,
73 records: NonNegativeInt,
74 unpricedRecords: NonNegativeInt,
75 /** Absent from older servers; merges then estimate it from the unpriced record share. */
76 unpricedTokens: Schema.optional(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: NonBlankString,
85 /** Transcript directory device:inode distinguishes machines sharing a hostname and home path. */
86 volumeId: Schema.String,
87 /**
88 * Opaque identity of a directory that the Windows server of a desktop install
89 * reads natively and its managed WSL server reads through a drvfs mount. Path
90 * and `volumeId` differ between the two sides, so clients treat sources with
91 * an equal value as one directory in addition to the fields above.
92 */
93 physicalSourceId: Schema.optionalKey(TrimmedNonEmptyString),
94});
95export type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;
96
97export const UsageSourceStatus = Schema.Literals(["ok", "missing", "partial", "failed"]);
98export type UsageSourceStatus = typeof UsageSourceStatus.Type;
99
100export const UsageSource = Schema.Struct({
101 fingerprint: UsageSourceFingerprint,
102 status: UsageSourceStatus,
103 scannedFiles: NonNegativeInt,
104 skippedFiles: NonNegativeInt,
105 malformedRecords: NonNegativeInt,
106 /** Total this count; bucket counts double-count sessions spanning days or models. */
107 distinctSessions: NonNegativeInt,
108 message: Schema.NullOr(TrimmedNonEmptyString),
109 /** Cached response during refresh; repeat with awaitRefresh for fresh data. */
110 refreshing: Schema.optionalKey(Schema.Literal(true)),
111});
112export type UsageSource = typeof UsageSource.Type;
113
114export const UsagePricingStatus = Schema.Literals(["fresh", "cached", "unavailable"]);
115export type UsagePricingStatus = typeof UsagePricingStatus.Type;
116
117export const UsagePricing = Schema.Struct({
118 status: UsagePricingStatus,
119 source: TrimmedNonEmptyString,
120 fetchedAt: Schema.NullOr(Schema.String),
121 knownModels: NonNegativeInt,
122});
123export type UsagePricing = typeof UsagePricing.Type;
124
125/**
126 * Matches a provider's original model ID, before usage model aliases apply. Omit provider to
127 * match any; a string provider lets older clients carry selectors for providers they lack.
128 */
129export const UsageModelSelector = Schema.Struct({
130 provider: Schema.optional(TrimmedNonEmptyString),
131 model: TrimmedNonEmptyString,
132});
133export type UsageModelSelector = typeof UsageModelSelector.Type;
134
135/** Keeps records matching `include` (all when omitted) and not matching `exclude`. */
136export const UsageModelFilter = Schema.Struct({
137 include: Schema.optional(Schema.Array(UsageModelSelector)),
138 exclude: Schema.optional(Schema.Array(UsageModelSelector)),
139});
140export type UsageModelFilter = typeof UsageModelFilter.Type;
141
142export const UsageSummaryInput = Schema.Struct({
143 sinceDay: UsageDay,
144 untilDay: UsageDay,
145 /** IANA bucketing zone; offsets fail across DST boundaries. */
146 timeZone: TrimmedNonEmptyString,
147 resolution: Schema.optional(UsageResolution),
148 sinceTime: Schema.optional(TrimmedNonEmptyString),
149 untilTime: Schema.optional(TrimmedNonEmptyString),
150 awaitRefresh: Schema.optional(Schema.Boolean),
151 /** Accept an immediate answer from the last scan; its sources are marked refreshing. */
152 provisional: Schema.optional(Schema.Boolean),
153 modelFilter: Schema.optional(UsageModelFilter),
154});
155export type UsageSummaryInput = typeof UsageSummaryInput.Type;
156
157/** An enabled provider whose usage files T3 has not been allowed to read yet. Nothing was read. */
158export const UsageAccessRequest = Schema.Struct({
159 instanceId: ProviderInstanceId,
160 driver: ProviderDriverKind,
161 provider: UsageProviderKind,
162 /** Folders a grant would let T3 read; empty when finding them would itself read the provider. */
163 paths: Schema.Array(TrimmedNonEmptyString),
164});
165export type UsageAccessRequest = typeof UsageAccessRequest.Type;
166
167export const UsageSummary = Schema.Struct({
168 contractVersion: Schema.Number,
169 readAt: Schema.String,
170 timeZone: TrimmedNonEmptyString,
171 sinceDay: UsageDay,
172 untilDay: UsageDay,
173 buckets: ForwardCompatibleArray(UsageBucket),
174 sources: ForwardCompatibleArray(UsageSource),
175 pricing: UsagePricing,
176 scanDurationMs: NonNegativeInt,
177 /** The filter the server applied; absent means unfiltered, including servers that predate filters. */
178 modelFilter: Schema.optional(UsageModelFilter),
179 /** Absent from servers that read every provider without asking. */
180 accessRequests: Schema.optional(ForwardCompatibleArray(UsageAccessRequest)),
181});
182export type UsageSummary = typeof UsageSummary.Type;
183
184export class UsageReadError extends Schema.TaggedError<UsageReadError>()("UsageReadError", {
185 reason: Schema.Literals(["scanFailed", "invalidWindow"]),
186 detail: TrimmedNonEmptyString,
187 cause: Schema.optional(Schema.Defect()),
188}) {
189 override get message(): string {
190 return `Usage read failed (${this.reason}): ${this.detail}`;
191 }
192}