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