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