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