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 (Claude Code, Codex, and
5 * Grok Build) rather than T3 Code's orchestration projections, so usage covers
6 * turns driven outside T3 Code too. 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, and a file that merely grew resumes
11 * from its cached parse position so only the appended bytes are read.
12 *
13 * @module UsageService
14 */
15import * as NodeOS from "node:os";
16
17import {
18 USAGE_CONTRACT_VERSION,
19 type ServerSettings as ServerSettingsValue,
20 type UsageProviderKind,
21 type UsageSource,
22 type UsagePricing,
23 type UsageSummary,
24 type UsageSummaryInput,
25 UsageReadError,
26} from "@t3tools/contracts";
27import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
28import * as Cause from "effect/Cause";
29import * as Clock from "effect/Clock";
30import * as Context from "effect/Context";
31import * as DateTime from "effect/DateTime";
32import * as Deferred from "effect/Deferred";
33import * as Effect from "effect/Effect";
34import * as FileSystem from "effect/FileSystem";
35import * as Layer from "effect/Layer";
36import * as Option from "effect/Option";
37import * as Path from "effect/Path";
38import * as Schema from "effect/Schema";
39import * as Semaphore from "effect/Semaphore";
40import { HttpClient, HttpClientResponse } from "effect/unstable/http";
41
42import { ServerConfig } from "../config.ts";
43import { expandHomePath } from "../pathExpansion.ts";
44import * as ServerSettings from "../serverSettings.ts";
45import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";
46import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
47import { UsageAggregator } from "./usageAggregation.ts";
48import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
49import {
50 listTranscriptFiles,
51 readDirectoryVolumeId,
52 readTranscriptRecords,
53} from "./usageTranscriptReader.ts";
54import {
55 decodeScanCache,
56 dedupeWithinFile,
57 encodeScanCache,
58 pruneScanCache,
59 type ScanCache,
60} from "./usageScanCache.ts";
61import type { UsageRecord } from "./usageTranscripts.ts";
62
63const LITELLM_RATES_URL =
64 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
65
66/** Rates move rarely; a day-old table keeps the page working offline. */
67const RATES_TTL_MS = 24 * 60 * 60 * 1000;
68
69/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
70const RATES_REFRESH_FLOOR_MS = 60 * 1000;
71
72/**
73 * Files are filtered by mtime before opening. The slack covers a session whose
74 * last write lands just before local midnight on the window's first day.
75 */
76const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
77const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
78
79/** Longest window the UI offers, plus slack. Older entries are pruned. */
80const CACHE_RETENTION_DAYS = 90;
81
82/** On-disk shape of the rate snapshot. */
83const RatesCacheFile = Schema.Struct({
84 fetchedAtMs: Schema.Number,
85 document: Schema.Unknown,
86});
87const decodeRatesCache = Schema.decodeUnknownEffect(
88 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
89);
90const encodeRatesCache = Schema.encodeEffect(
91 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
92);
93
94/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
95const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
96const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
97const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
98
99export class UsageService extends Context.Service<
100 UsageService,
101 {
102 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
103 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
104 readonly refreshRates: Effect.Effect<UsagePricing>;
105 }
106>()("t3/usage/UsageService") {}
107
108const EMPTY_PRICING: UsagePricing = {
109 status: "unavailable",
110 source: LITELLM_RATES_URL,
111 fetchedAt: null,
112 knownModels: 0,
113};
114
115/** Empty summary, for suites that only need the RPC surface to resolve. */
116const layerTest = Layer.succeed(
117 UsageService,
118 UsageService.of({
119 readSummary: (input) =>
120 Effect.succeed({
121 contractVersion: USAGE_CONTRACT_VERSION,
122 readAt: "1970-01-01T00:00:00.000Z",
123 timeZone: input.timeZone,
124 sinceDay: input.sinceDay,
125 untilDay: input.untilDay,
126 buckets: [],
127 sources: [],
128 pricing: EMPTY_PRICING,
129 scanDurationMs: 0,
130 }),
131 refreshRates: Effect.succeed(EMPTY_PRICING),
132 }),
133);
134
135export const make = Effect.gen(function* () {
136 const fileSystem = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 const config = yield* ServerConfig;
139 const settingsService = yield* ServerSettings.ServerSettingsService;
140 const httpClient = yield* HttpClient.HttpClient;
141 const hostEnvironment = yield* HostProcessEnvironment;
142
143 const fileCache: ScanCache = new Map();
144 let cacheDirty = false;
145
146 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
147 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
148 let rates: RateTable = new Map();
149 let ratesFetchedAtMs: number | null = null;
150 let ratesStatus: UsagePricing["status"] = "unavailable";
151 // One fetch at a time. A burst of refreshes from several clients waits on
152 // the first fetch and then sees a table young enough to skip its own.
153 const ratesLock = yield* Semaphore.make(1);
154
155 const pricing = (): UsagePricing => ({
156 status: ratesStatus,
157 source: LITELLM_RATES_URL,
158 fetchedAt:
159 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
160 knownModels: rates.size,
161 });
162
163 /**
164 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
165 * the on-disk snapshot. With neither, every model reports as unpriced rather
166 * than the page failing. `force` refetches inside the TTL so a model that
167 * LiteLLM added since the last fetch gets priced now.
168 */
169 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
170 const now = yield* Clock.currentTimeMillis;
171 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
172 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
173
174 if (ratesFetchedAtMs === null) {
175 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
176 Effect.flatMap((raw) => decodeRatesCache(raw)),
177 Effect.catchCause(() => Effect.succeed(null)),
178 );
179 if (fromDisk !== null) {
180 const parsed = parseRateTable(fromDisk.document);
181 if (parsed.size > 0) {
182 rates = parsed;
183 ratesFetchedAtMs = fromDisk.fetchedAtMs;
184 ratesStatus = "cached";
185 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
186 }
187 }
188 }
189
190 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
191 Effect.flatMap(HttpClientResponse.filterStatusOk),
192 Effect.flatMap((response) => response.json),
193 Effect.timeout(10_000),
194 Effect.catchCause(() => Effect.succeed(null)),
195 );
196 if (fetched === null) {
197 // The refresh failed; whatever we are serving is now past its TTL and
198 // must not keep claiming to be fresh.
199 if (rates.size > 0) ratesStatus = "cached";
200 return;
201 }
202
203 const parsed = parseRateTable(fetched);
204 if (parsed.size === 0) return;
205
206 rates = parsed;
207 ratesFetchedAtMs = now;
208 ratesStatus = "fresh";
209
210 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
211 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
212 Effect.catchCause(() => Effect.void),
213 );
214 });
215
216 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
217
218 const refreshRates = ensureRates(true).pipe(
219 Effect.map(pricing),
220 Effect.withSpan("UsageService.refreshRates"),
221 );
222
223 /**
224 * Claude's config dir is the home itself when overridden, but a default
225 * install nests transcripts under `~/.claude/projects`. Probe both.
226 */
227 const resolveClaudeTranscriptDir = (homePath: string) =>
228 Effect.gen(function* () {
229 const nested = path.join(homePath, ".claude", "projects");
230 const nestedExists = yield* fileSystem
231 .exists(nested)
232 .pipe(Effect.catchCause(() => Effect.succeed(false)));
233 return nestedExists ? nested : path.join(homePath, "projects");
234 });
235
236 // A settings failure must not silently discard custom rates or transcript homes.
237 const readSettings = settingsService.getSettings.pipe(
238 Effect.catchCause(
239 (cause) =>
240 new UsageReadError({
241 reason: "scanFailed",
242 detail: "Server settings could not be read.",
243 cause: Cause.squash(cause),
244 }),
245 ),
246 );
247
248 /** Resolves the transcript directory for each provider. */
249 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
250 settings: ServerSettingsValue,
251 ) {
252 const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
253 const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
254 const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
255 // Grok Settings only expose the binary path; home is `$GROK_HOME` or `~/.grok`.
256 // Empty/whitespace GROK_HOME must fall back: coalescing alone would scan cwd.
257 const grokHomeEnv = hostEnvironment["GROK_HOME"]?.trim() ?? "";
258 const grokHome =
259 grokHomeEnv.length > 0
260 ? path.resolve(expandHomePath(grokHomeEnv))
261 : path.join(NodeOS.homedir(), ".grok");
262
263 return [
264 { provider: "claude" as const, dir: claudeDir },
265 { provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") },
266 {
267 provider: "grok" as const,
268 dir: path.join(grokHome, "sessions"),
269 fileName: "updates.jsonl",
270 },
271 ];
272 });
273
274 /**
275 * Loads the persisted scan cache exactly once per process.
276 *
277 * `Effect.cached` makes concurrent first readers await the same load rather
278 * than each seeing a "loaded" flag set before the read finished and cold
279 * scanning against an empty cache.
280 */
281 const ensureScanCacheLoaded = yield* Effect.cached(
282 Effect.gen(function* () {
283 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
284 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
285 Effect.catchCause(() => Effect.succeed(null)),
286 );
287 if (document === null) return;
288 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
289 }),
290 );
291
292 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
293 if (!cacheDirty) return;
294 // Cleared only after the write lands, so a failed persist is retried on
295 // the next scan instead of leaving disk permanently stale.
296 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
297 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
298 Effect.map(() => {
299 cacheDirty = false;
300 }),
301 // A cache we cannot write is a slower next start, not a failed read.
302 Effect.catchCause(() => Effect.void),
303 );
304 });
305
306 /**
307 * Parses one transcript, reusing the cached result when it is unchanged.
308 *
309 * A file that only grew re-parses from the cached position, so an actively
310 * written multi-hundred-megabyte rollout costs its appended bytes per scan
311 * rather than a full re-read. The reader verifies the position's guard bytes
312 * and silently restarts from byte 0 when they no longer match.
313 */
314 const readFileRecords = (
315 filePath: string,
316 size: number,
317 mtimeMs: number,
318 provider: UsageProviderKind,
319 ): Effect.Effect<readonly UsageRecord[]> =>
320 Effect.gen(function* () {
321 const cached = fileCache.get(filePath);
322 // Provider is part of the identity: if both providers were ever pointed
323 // at one directory, a hit parsed by the other parser must not be reused.
324 if (
325 cached &&
326 cached.size === size &&
327 cached.mtimeMs === mtimeMs &&
328 cached.provider === provider
329 ) {
330 return cached.tailRecords.length === 0
331 ? cached.records
332 : [...cached.records, ...cached.tailRecords];
333 }
334
335 // Only a strictly grown file may resume. Same size with a new mtime, or
336 // a shrunken file, means rewritten content; re-parse it whole.
337 const resumeFrom =
338 cached !== undefined && cached.provider === provider && size > cached.size
339 ? cached.position
340 : undefined;
341
342 const parsed = yield* Effect.promise(() =>
343 readTranscriptRecords(filePath, provider, resumeFrom),
344 );
345 // A read failure is not an empty transcript: caching it under this
346 // (size, mtime) would silently drop the file's usage until it changes.
347 if (parsed === null) return [];
348
349 // Stored already de-duplicated within the file, which is 99% of all
350 // duplicates. The aggregator still runs the cross-file dedupe pass. One
351 // seen set spans the cached base, the new lines, and the tail so a
352 // resumed parse dedupes exactly like a full one.
353 const base = parsed.resumed && cached !== undefined ? cached.records : [];
354 const seen = new Set<string>();
355 const records = dedupeWithinFile([...base, ...parsed.records], seen);
356 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
357
358 fileCache.set(filePath, {
359 size,
360 mtimeMs,
361 provider,
362 records,
363 tailRecords,
364 position: parsed.position,
365 });
366 cacheDirty = true;
367 return tailRecords.length === 0 ? records : [...records, ...tailRecords];
368 });
369
370 /** One provider directory's walk and parse, before rates are involved. */
371 interface ScannedDir {
372 readonly provider: UsageProviderKind;
373 readonly dir: string;
374 readonly volumeId: string;
375 /** Parsed records per file, or `null` when the directory does not exist. */
376 readonly files:
377 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
378 | null;
379 }
380
381 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
382 windowStartMs: number,
383 settings: ServerSettingsValue,
384 ) {
385 // The home resolvers ask for `Path` themselves; satisfy them from the
386 // instance we already hold so the scan stays context-free.
387 const dirs = yield* resolveTranscriptDirs(settings).pipe(
388 Effect.provideService(Path.Path, path),
389 );
390 const scanned: ScannedDir[] = [];
391 for (const { provider, dir, fileName } of dirs) {
392 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
393 const exists = yield* fileSystem
394 .exists(dir)
395 .pipe(Effect.catchCause(() => Effect.succeed(false)));
396 if (!exists) {
397 scanned.push({ provider, dir, volumeId, files: null });
398 continue;
399 }
400 const files = yield* Effect.promise(() =>
401 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
402 );
403 const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = [];
404 for (const file of files) {
405 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
406 parsedFiles.push({ path: file.path, records });
407 }
408 scanned.push({ provider, dir, volumeId, files: parsedFiles });
409 }
410 return scanned;
411 });
412
413 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
414 input: UsageSummaryInput,
415 settings: ServerSettingsValue,
416 ) {
417 if (input.sinceDay > input.untilDay) {
418 return yield* new UsageReadError({
419 reason: "invalidWindow",
420 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
421 });
422 }
423
424 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
425 if (input.resolution === "hour") {
426 const sinceTime =
427 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
428 const untilTime =
429 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
430 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
431 return yield* new UsageReadError({
432 reason: "invalidWindow",
433 detail: "Hourly usage requires valid sinceTime and untilTime instants",
434 });
435 }
436 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
437 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
438 const durationMs = untilTimeMs - sinceTimeMs;
439 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
440 return yield* new UsageReadError({
441 reason: "invalidWindow",
442 detail: "Hourly usage window must be greater than zero and at most 24 hours",
443 });
444 }
445 hourlyWindow = { sinceTimeMs, untilTimeMs };
446 }
447
448 const startedAtMs = yield* Clock.currentTimeMillis;
449 yield* ensureScanCacheLoaded;
450
451 const hostId = NodeOS.hostname();
452 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
453 if (Option.isNone(windowStart)) {
454 return yield* new UsageReadError({
455 reason: "invalidWindow",
456 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
457 });
458 }
459 const windowStartMs =
460 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
461
462 // Pricing only matters once records are aggregated, so the rate table
463 // loads while transcripts stream instead of gating them: a cold rates
464 // fetch on a slow network no longer delays the scan by its own timeout.
465 const [, scannedDirs] = yield* Effect.all(
466 [ensureRates(false), collectDirs(windowStartMs, settings)],
467 { concurrency: 2 },
468 );
469
470 const aggregator = new UsageAggregator({
471 timeZone: input.timeZone,
472 sinceDay: input.sinceDay,
473 untilDay: input.untilDay,
474 resolution: input.resolution ?? "day",
475 ...hourlyWindow,
476 rates,
477 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
478 });
479
480 const sources: UsageSource[] = [];
481 const livePaths = new Set<string>();
482 const walkedRoots: string[] = [];
483
484 for (const { provider, dir, volumeId, files } of scannedDirs) {
485 if (files === null) {
486 sources.push({
487 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
488 status: "missing",
489 scannedFiles: 0,
490 skippedFiles: 0,
491 malformedRecords: 0,
492 distinctSessions: 0,
493 message: "No transcript directory on this environment.",
494 });
495 continue;
496 }
497
498 walkedRoots.push(dir);
499 let scannedFiles = 0;
500 let skippedFiles = 0;
501 // Distinct per directory. Buckets carry per-cell session counts, but a
502 // session spans days and models, so clients total this figure instead.
503 const sessionIds = new Set<string>();
504
505 for (const file of files) {
506 livePaths.add(file.path);
507 if (file.records.length === 0) {
508 skippedFiles += 1;
509 continue;
510 }
511 scannedFiles += 1;
512 for (const record of file.records) {
513 // Only sessions that contributed in-window count: the mtime slack
514 // admits boundary files whose records fall outside the range.
515 if (aggregator.add(record) && record.sessionId.length > 0) {
516 sessionIds.add(record.sessionId);
517 }
518 }
519 }
520
521 sources.push({
522 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
523 status: "ok",
524 scannedFiles,
525 skippedFiles,
526 malformedRecords: 0,
527 distinctSessions: sessionIds.size,
528 message: null,
529 });
530 }
531
532 const pruned = pruneScanCache(fileCache, {
533 livePaths,
534 walkedRoots,
535 windowStartMs,
536 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
537 });
538 if (pruned > 0) cacheDirty = true;
539 yield* persistScanCache();
540
541 const aggregated = aggregator.finish();
542 const readAt = yield* DateTime.now;
543 const finishedAtMs = yield* Clock.currentTimeMillis;
544
545 return {
546 contractVersion: USAGE_CONTRACT_VERSION,
547 readAt: DateTime.formatIso(readAt),
548 timeZone: input.timeZone,
549 sinceDay: input.sinceDay,
550 untilDay: input.untilDay,
551 buckets: aggregated.buckets,
552 sources,
553 pricing: pricing(),
554 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
555 } satisfies UsageSummary;
556 });
557
558 /**
559 * In-flight scans by window and custom prices, so concurrent identical requests (the usage
560 * page open on two clients at once) share one scan instead of racing over
561 * the same corpus twice.
562 */
563 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
564
565 const scanKey = (
566 input: UsageSummaryInput,
567 priceOverrides: ServerSettingsValue["usagePriceOverrides"],
568 ): string =>
569 JSON.stringify([
570 input.timeZone,
571 input.sinceDay,
572 input.untilDay,
573 input.resolution ?? "day",
574 input.sinceTime ?? null,
575 input.untilTime ?? null,
576 priceOverrides,
577 ]);
578
579 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
580 const settings = yield* readSettings;
581 const key = scanKey(input, settings.usagePriceOverrides);
582 const deferred = yield* Effect.uninterruptible(
583 Effect.gen(function* () {
584 const existing = inflightScans.get(key);
585 if (existing !== undefined) return existing;
586
587 // Enrollment and detached-fiber creation must be atomic. Otherwise a
588 // canceled first caller can leave a Deferred with no scan to finish it.
589 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
590 inflightScans.set(key, created);
591 // Detached so one departing client cannot tear the scan out from under
592 // the fibers awaiting it; a finished scan warms the cache either way.
593 yield* scanSummary(input, settings).pipe(
594 Effect.onExit((exit) =>
595 Effect.sync(() => inflightScans.delete(key)).pipe(
596 Effect.andThen(Deferred.done(created, exit)),
597 ),
598 ),
599 Effect.forkDetach,
600 );
601 return created;
602 }),
603 );
604 // Waiting stays interruptible. The detached scan continues for other
605 // callers and still warms the cache if this caller leaves.
606 return yield* Deferred.await(deferred);
607 });
608
609 return { readSummary, refreshRates } as const;
610});
611
612export const layer = Layer.effect(UsageService, make);