Open History to see the last commit
1/**
2 * UsageService - scans provider transcripts and returns priced usage buckets.
3 *
4 * The scan reads the provider CLIs' own session files rather than T3 Code's
5 * orchestration projections, so usage covers turns driven outside T3 Code too.
6 * This is the approach `ccusage` takes.
7 *
8 * Transcripts are append-only, so parsed records are memoised per file by
9 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
10 * scans only reparse files that changed.
11 *
12 * @module UsageService
13 */
14import * as NodeOS from "node:os";
15
16import {
17 USAGE_CONTRACT_VERSION,
18 type UsageProviderKind,
19 type UsageSource,
20 type UsageSummary,
21 type UsageSummaryInput,
22 UsageReadError,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Clock from "effect/Clock";
26import * as Context from "effect/Context";
27import * as DateTime from "effect/DateTime";
28import * as Effect from "effect/Effect";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as Schema from "effect/Schema";
34import { HttpClient, HttpClientResponse } from "effect/unstable/http";
35
36import { ServerConfig } from "../config.ts";
37import * as ServerSettings from "../serverSettings.ts";
38import { UsageAggregator } from "./usageAggregation.ts";
39import { parseRateTable, type RateTable } from "./usagePricing.ts";
40import {
41 listTranscriptFiles,
42 readDirectoryVolumeId,
43 readTranscriptRecords,
44} from "./usageTranscriptReader.ts";
45import {
46 decodeScanCache,
47 dedupeWithinFile,
48 encodeScanCache,
49 pruneScanCache,
50 type ScanCache,
51} from "./usageScanCache.ts";
52import type { UsageRecord } from "./usageTranscripts.ts";
53import { resolveUsageTranscriptSources } from "./usageTranscriptSources.ts";
54
55const LITELLM_RATES_URL =
56 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
57
58/** Rates move rarely; a day-old table keeps the page working offline. */
59const RATES_TTL_MS = 24 * 60 * 60 * 1000;
60
61/**
62 * Files are filtered by mtime before opening. The slack covers a session whose
63 * last write lands just before local midnight on the window's first day.
64 */
65const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
66const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
67
68/** Longest window the UI offers, plus slack. Older entries are pruned. */
69const CACHE_RETENTION_DAYS = 90;
70
71/** On-disk shape of the rate snapshot. */
72const RatesCacheFile = Schema.Struct({
73 fetchedAtMs: Schema.Number,
74 document: Schema.Unknown,
75});
76const decodeRatesCache = Schema.decodeUnknownEffect(
77 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
78);
79const encodeRatesCache = Schema.encodeEffect(
80 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
81);
82
83/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
84const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
85const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
86const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
87
88export class UsageService extends Context.Service<
89 UsageService,
90 {
91 readonly readSummary: (
92 input: UsageSummaryInput,
93 workspaceCwds?: readonly string[],
94 ) => Effect.Effect<UsageSummary, UsageReadError>;
95 }
96>()("t3/usage/UsageService") {}
97
98/** Empty summary, for suites that only need the RPC surface to resolve. */
99export const layerTest = Layer.succeed(
100 UsageService,
101 UsageService.of({
102 readSummary: (input) =>
103 Effect.succeed({
104 contractVersion: USAGE_CONTRACT_VERSION,
105 readAt: "1970-01-01T00:00:00.000Z",
106 timeZone: input.timeZone,
107 sinceDay: input.sinceDay,
108 untilDay: input.untilDay,
109 buckets: [],
110 sources: [],
111 pricing: {
112 status: "unavailable",
113 source: LITELLM_RATES_URL,
114 fetchedAt: null,
115 knownModels: 0,
116 },
117 scanDurationMs: 0,
118 }),
119 }),
120);
121
122export const make = Effect.gen(function* () {
123 const fileSystem = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125 const config = yield* ServerConfig;
126 const settingsService = yield* ServerSettings.ServerSettingsService;
127 const httpClient = yield* HttpClient.HttpClient;
128
129 const fileCache: ScanCache = new Map();
130 let cacheDirty = false;
131
132 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
133 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
134 let rates: RateTable = new Map();
135 let ratesFetchedAtMs: number | null = null;
136 let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";
137
138 /**
139 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
140 * the on-disk snapshot. With neither, every model reports as unpriced rather
141 * than the page failing.
142 */
143 const ensureRates = Effect.fn("UsageService.ensureRates")(function* () {
144 const now = yield* Clock.currentTimeMillis;
145 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;
146
147 if (ratesFetchedAtMs === null) {
148 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
149 Effect.flatMap((raw) => decodeRatesCache(raw)),
150 Effect.catchCause(() => Effect.succeed(null)),
151 );
152 if (fromDisk !== null) {
153 const parsed = parseRateTable(fromDisk.document);
154 if (parsed.size > 0) {
155 rates = parsed;
156 ratesFetchedAtMs = fromDisk.fetchedAtMs;
157 ratesStatus = "cached";
158 if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
159 }
160 }
161 }
162
163 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
164 Effect.flatMap(HttpClientResponse.filterStatusOk),
165 Effect.flatMap((response) => response.json),
166 Effect.timeout(10_000),
167 Effect.catchCause(() => Effect.succeed(null)),
168 );
169 if (fetched === null) {
170 // The refresh failed; whatever we are serving is now past its TTL and
171 // must not keep claiming to be fresh.
172 if (rates.size > 0) ratesStatus = "cached";
173 return;
174 }
175
176 const parsed = parseRateTable(fetched);
177 if (parsed.size === 0) return;
178
179 rates = parsed;
180 ratesFetchedAtMs = now;
181 ratesStatus = "fresh";
182
183 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
184 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
185 Effect.catchCause(() => Effect.void),
186 );
187 });
188
189 /** Resolves the transcript directory for each provider. */
190 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
191 workspaceCwds: readonly string[],
192 ) {
193 // A settings failure must surface as an error: swallowing it here would
194 // present "zero usage from every provider" as a valid answer.
195 const settings = yield* settingsService.getSettings.pipe(
196 Effect.catchCause(
197 (cause) =>
198 new UsageReadError({
199 reason: "scanFailed",
200 // Bounded description; the squashed failure travels as the cause.
201 // Squashed, not the Cause tree: a full tree in a Defect field is
202 // the unbounded wire payload the bounded detail exists to avoid.
203 detail: "Server settings could not be read.",
204 cause: Cause.squash(cause),
205 }),
206 ),
207 );
208
209 return yield* resolveUsageTranscriptSources(settings, process.env, workspaceCwds);
210 });
211
212 /**
213 * Loads the persisted scan cache exactly once per process.
214 *
215 * `Effect.cached` makes concurrent first readers await the same load rather
216 * than each seeing a "loaded" flag set before the read finished and cold
217 * scanning against an empty cache.
218 */
219 const ensureScanCacheLoaded = yield* Effect.cached(
220 Effect.gen(function* () {
221 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
222 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
223 Effect.catchCause(() => Effect.succeed(null)),
224 );
225 if (document === null) return;
226 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
227 }),
228 );
229
230 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
231 if (!cacheDirty) return;
232 // Cleared only after the write lands, so a failed persist is retried on
233 // the next scan instead of leaving disk permanently stale.
234 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
235 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
236 Effect.map(() => {
237 cacheDirty = false;
238 }),
239 // A cache we cannot write is a slower next start, not a failed read.
240 Effect.catchCause(() => Effect.void),
241 );
242 });
243
244 /** Parses one transcript, reusing the cached result when it is unchanged. */
245 const readFileRecords = (
246 filePath: string,
247 size: number,
248 mtimeMs: number,
249 provider: UsageProviderKind,
250 ): Effect.Effect<readonly UsageRecord[]> =>
251 Effect.gen(function* () {
252 const cached = fileCache.get(filePath);
253 // Provider is part of the identity: if both providers were ever pointed
254 // at one directory, a hit parsed by the other parser must not be reused.
255 if (
256 cached &&
257 cached.size === size &&
258 cached.mtimeMs === mtimeMs &&
259 cached.provider === provider
260 ) {
261 return cached.records;
262 }
263
264 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
265 // A read failure is not an empty transcript: caching it under this
266 // (size, mtime) would silently drop the file's usage until it changes.
267 if (parsed === null) return [];
268 // Stored already de-duplicated within the file, which is 99% of all
269 // duplicates. The aggregator still runs the cross-file dedupe pass.
270 const records = dedupeWithinFile(parsed);
271
272 fileCache.set(filePath, { size, mtimeMs, provider, records });
273 cacheDirty = true;
274 return records;
275 });
276
277 const readSummary = Effect.fn("UsageService.readSummary")(function* (
278 input: UsageSummaryInput,
279 workspaceCwds: readonly string[] = [config.cwd],
280 ) {
281 if (input.sinceDay > input.untilDay) {
282 return yield* new UsageReadError({
283 reason: "invalidWindow",
284 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
285 });
286 }
287
288 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
289 if (input.resolution === "hour") {
290 const sinceTime =
291 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
292 const untilTime =
293 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
294 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
295 return yield* new UsageReadError({
296 reason: "invalidWindow",
297 detail: "Hourly usage requires valid sinceTime and untilTime instants",
298 });
299 }
300 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
301 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
302 const durationMs = untilTimeMs - sinceTimeMs;
303 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
304 return yield* new UsageReadError({
305 reason: "invalidWindow",
306 detail: "Hourly usage window must be greater than zero and at most 24 hours",
307 });
308 }
309 hourlyWindow = { sinceTimeMs, untilTimeMs };
310 }
311
312 const startedAtMs = yield* Clock.currentTimeMillis;
313 yield* ensureRates();
314 yield* ensureScanCacheLoaded;
315
316 const hostId = NodeOS.hostname();
317 // The source resolvers ask for Path themselves; satisfy them from the
318 // instance we already hold so readSummary stays context-free.
319 const dirs = yield* resolveTranscriptDirs(workspaceCwds).pipe(
320 Effect.provideService(Path.Path, path),
321 );
322 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
323 if (Option.isNone(windowStart)) {
324 return yield* new UsageReadError({
325 reason: "invalidWindow",
326 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
327 });
328 }
329 const windowStartMs =
330 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
331
332 const sources: UsageSource[] = [];
333 const buckets: UsageSummary["buckets"][number][] = [];
334 const livePaths = new Set<string>();
335 const walkedRoots: string[] = [];
336 const seenDedupeKeys = new Set<string>();
337
338 for (const { provider, dir } of dirs) {
339 const sourceIndex = sources.length;
340 const aggregator = new UsageAggregator(
341 {
342 sourceIndex,
343 timeZone: input.timeZone,
344 sinceDay: input.sinceDay,
345 untilDay: input.untilDay,
346 resolution: input.resolution ?? "day",
347 ...hourlyWindow,
348 rates,
349 },
350 seenDedupeKeys,
351 );
352 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
353 const exists = yield* fileSystem
354 .exists(dir)
355 .pipe(Effect.catchCause(() => Effect.succeed(false)));
356
357 if (!exists) {
358 sources.push({
359 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
360 status: "missing",
361 scannedFiles: 0,
362 skippedFiles: 0,
363 malformedRecords: 0,
364 distinctSessions: 0,
365 message: "No transcript directory on this environment.",
366 });
367 continue;
368 }
369
370 walkedRoots.push(dir);
371 const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));
372 let scannedFiles = 0;
373 let skippedFiles = 0;
374 // Distinct per directory. Buckets carry per-cell session counts, but a
375 // session spans days and models, so clients total this figure instead.
376 const sessionIds = new Set<string>();
377
378 for (const file of files) {
379 livePaths.add(file.path);
380 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
381 if (records.length === 0) {
382 skippedFiles += 1;
383 continue;
384 }
385 scannedFiles += 1;
386 for (const record of records) {
387 // Only sessions that contributed in-window count: the mtime slack
388 // admits boundary files whose records fall outside the range.
389 if (aggregator.add(record) && record.sessionId.length > 0) {
390 sessionIds.add(record.sessionId);
391 }
392 }
393 }
394
395 sources.push({
396 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
397 status: "ok",
398 scannedFiles,
399 skippedFiles,
400 malformedRecords: 0,
401 distinctSessions: sessionIds.size,
402 message: null,
403 });
404 buckets.push(...aggregator.finish().buckets);
405 }
406
407 const pruned = pruneScanCache(fileCache, {
408 livePaths,
409 walkedRoots,
410 windowStartMs,
411 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
412 });
413 if (pruned > 0) cacheDirty = true;
414 yield* persistScanCache();
415
416 const readAt = yield* DateTime.now;
417 const finishedAtMs = yield* Clock.currentTimeMillis;
418
419 return {
420 contractVersion: USAGE_CONTRACT_VERSION,
421 readAt: DateTime.formatIso(readAt),
422 timeZone: input.timeZone,
423 sinceDay: input.sinceDay,
424 untilDay: input.untilDay,
425 buckets: buckets.sort(
426 (a, b) =>
427 a.day.localeCompare(b.day) ||
428 (a.hourStart ?? "").localeCompare(b.hourStart ?? "") ||
429 a.provider.localeCompare(b.provider) ||
430 a.model.localeCompare(b.model) ||
431 a.sourceIndex - b.sourceIndex,
432 ),
433 sources,
434 pricing: {
435 status: ratesStatus,
436 source: LITELLM_RATES_URL,
437 fetchedAt:
438 ratesFetchedAtMs === null
439 ? null
440 : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
441 knownModels: rates.size,
442 },
443 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
444 } satisfies UsageSummary;
445 });
446
447 return { readSummary } as const;
448});
449
450export const layer = Layer.effect(UsageService, make);