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