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

usage.ts

187 lines7.2 KB

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