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 { listProviderHomeCandidates, scanHomePath } from "./usageHomes.ts";
43import { UsageAggregator } from "./usageAggregation.ts";
44import { parseRateTable, type RateTable } from "./usagePricing.ts";
45import {
46 listTranscriptFiles,
47 readDirectoryVolumeId,
48 readTranscriptRecords,
49} from "./usageTranscriptReader.ts";
50import {
51 decodeScanCache,
52 dedupeWithinFile,
53 encodeScanCache,
54 pruneScanCache,
55 type ScanCache,
56} from "./usageScanCache.ts";
57import type { UsageRecord } from "./usageTranscripts.ts";
58
59const LITELLM_RATES_URL =
60 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
61
62/** Rates move rarely; a day-old table keeps the page working offline. */
63const RATES_TTL_MS = 24 * 60 * 60 * 1000;
64
65/**
66 * Files are filtered by mtime before opening. The slack covers a session whose
67 * last write lands just before local midnight on the window's first day.
68 */
69const MTIME_SLACK_MS = 36 * 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
91const decodeClaudeSettings = Schema.decodeUnknownEffect(ClaudeSettings);
92const decodeCodexSettings = Schema.decodeUnknownEffect(CodexSettings);
93
94export class UsageService extends Context.Service<
95 UsageService,
96 {
97 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
98 }
99>()("t3/usage/UsageService") {}
100
101/** Empty summary, for suites that only need the RPC surface to resolve. */
102export const layerTest = Layer.succeed(
103 UsageService,
104 UsageService.of({
105 readSummary: (input) =>
106 Effect.succeed({
107 contractVersion: USAGE_CONTRACT_VERSION,
108 readAt: "1970-01-01T00:00:00.000Z",
109 timeZone: input.timeZone,
110 sinceDay: input.sinceDay,
111 untilDay: input.untilDay,
112 buckets: [],
113 sources: [],
114 pricing: {
115 status: "unavailable",
116 source: LITELLM_RATES_URL,
117 fetchedAt: null,
118 knownModels: 0,
119 },
120 scanDurationMs: 0,
121 }),
122 }),
123);
124
125export const make = Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const config = yield* ServerConfig;
129 const settingsService = yield* ServerSettings.ServerSettingsService;
130 const httpClient = yield* HttpClient.HttpClient;
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 /**
206 * Resolves the transcript directories for each provider, one per configured
207 * provider instance. Instances that share a home (shadow homes symlink
208 * `sessions` back into the shared home) collapse to a single directory.
209 */
210 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {
211 // A settings failure must surface as an error: swallowing it here would
212 // present "zero usage from every provider" as a valid answer.
213 const settings = yield* settingsService.getSettings.pipe(
214 Effect.catchCause(
215 (cause) =>
216 new UsageReadError({
217 reason: "scanFailed",
218 // Bounded description; the squashed failure travels as the cause.
219 // Squashed, not the Cause tree: a full tree in a Defect field is
220 // the unbounded wire payload the bounded detail exists to avoid.
221 detail: "Server settings could not be read.",
222 cause: Cause.squash(cause),
223 }),
224 ),
225 );
226
227 const dirs: { provider: UsageProviderKind; dir: string }[] = [];
228 const seen = new Set<string>();
229 // Two instances can point at one physical directory through symlinks
230 // (or macOS's /tmp → /private/tmp). Canonicalising before de-duplication
231 // stops the same transcripts being counted once per alias. A directory
232 // that does not resolve (typically: does not exist) keeps its configured
233 // path and is reported as missing further down.
234 const push = (provider: UsageProviderKind, dir: string) =>
235 Effect.gen(function* () {
236 const canonical = yield* fileSystem
237 .realPath(dir)
238 .pipe(Effect.catchCause(() => Effect.succeed(dir)));
239 const key = `${provider}\0${canonical}`;
240 if (seen.has(key)) return;
241 seen.add(key);
242 dirs.push({ provider, dir: canonical });
243 });
244
245 for (const candidate of listProviderHomeCandidates(settings, "claude")) {
246 // A blob that fails to decode belongs to an instance the registry
247 // already reports as unavailable; the scan skips it.
248 const config = yield* decodeClaudeSettings(candidate.config).pipe(
249 Effect.catchCause(() => Effect.succeed(null)),
250 );
251 if (config === null) continue;
252 const claudeHome = yield* resolveClaudeHomePath({
253 homePath: scanHomePath(config.homePath, candidate.homeEnvValue, false),
254 });
255 yield* push("claude", yield* resolveClaudeTranscriptDir(claudeHome));
256 }
257
258 for (const candidate of listProviderHomeCandidates(settings, "codex")) {
259 const config = yield* decodeCodexSettings(candidate.config).pipe(
260 Effect.catchCause(() => Effect.succeed(null)),
261 );
262 if (config === null) continue;
263 const layout = yield* resolveCodexHomeLayout({
264 ...config,
265 homePath: scanHomePath(
266 config.homePath,
267 candidate.homeEnvValue,
268 config.shadowHomePath.trim().length > 0,
269 ),
270 });
271 yield* push("codex", path.join(layout.sharedHomePath, "sessions"));
272 }
273
274 return dirs;
275 });
276
277 /**
278 * Loads the persisted scan cache exactly once per process.
279 *
280 * `Effect.cached` makes concurrent first readers await the same load rather
281 * than each seeing a "loaded" flag set before the read finished and cold
282 * scanning against an empty cache.
283 */
284 const ensureScanCacheLoaded = yield* Effect.cached(
285 Effect.gen(function* () {
286 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
287 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
288 Effect.catchCause(() => Effect.succeed(null)),
289 );
290 if (document === null) return;
291 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
292 }),
293 );
294
295 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
296 if (!cacheDirty) return;
297 // Cleared only after the write lands, so a failed persist is retried on
298 // the next scan instead of leaving disk permanently stale.
299 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
300 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
301 Effect.map(() => {
302 cacheDirty = false;
303 }),
304 // A cache we cannot write is a slower next start, not a failed read.
305 Effect.catchCause(() => Effect.void),
306 );
307 });
308
309 /** Parses one transcript, reusing the cached result when it is unchanged. */
310 const readFileRecords = (
311 filePath: string,
312 size: number,
313 mtimeMs: number,
314 provider: UsageProviderKind,
315 ): Effect.Effect<readonly UsageRecord[]> =>
316 Effect.gen(function* () {
317 const cached = fileCache.get(filePath);
318 // Provider is part of the identity: if both providers were ever pointed
319 // at one directory, a hit parsed by the other parser must not be reused.
320 if (
321 cached &&
322 cached.size === size &&
323 cached.mtimeMs === mtimeMs &&
324 cached.provider === provider
325 ) {
326 return cached.records;
327 }
328
329 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
330 // A read failure is not an empty transcript: caching it under this
331 // (size, mtime) would silently drop the file's usage until it changes.
332 if (parsed === null) return [];
333 // Stored already de-duplicated within the file, which is 99% of all
334 // duplicates. The aggregator still runs the cross-file dedupe pass.
335 const records = dedupeWithinFile(parsed);
336
337 fileCache.set(filePath, { size, mtimeMs, provider, records });
338 cacheDirty = true;
339 return records;
340 });
341
342 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
343 if (input.sinceDay > input.untilDay) {
344 return yield* new UsageReadError({
345 reason: "invalidWindow",
346 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
347 });
348 }
349
350 const startedAtMs = yield* Clock.currentTimeMillis;
351 yield* ensureRates();
352 yield* ensureScanCacheLoaded;
353
354 const hostId = NodeOS.hostname();
355 // The home resolvers ask for `Path` themselves; satisfy them from the
356 // instance we already hold so `readSummary` stays context-free.
357 const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));
358 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
359 if (Option.isNone(windowStart)) {
360 return yield* new UsageReadError({
361 reason: "invalidWindow",
362 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
363 });
364 }
365 const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;
366
367 const aggregator = new UsageAggregator({
368 timeZone: input.timeZone,
369 sinceDay: input.sinceDay,
370 untilDay: input.untilDay,
371 rates,
372 });
373
374 const sources: UsageSource[] = [];
375 const livePaths = new Set<string>();
376 const walkedRoots: string[] = [];
377
378 for (const { provider, dir } of dirs) {
379 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
380 const exists = yield* fileSystem
381 .exists(dir)
382 .pipe(Effect.catchCause(() => Effect.succeed(false)));
383
384 if (!exists) {
385 sources.push({
386 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
387 status: "missing",
388 scannedFiles: 0,
389 skippedFiles: 0,
390 malformedRecords: 0,
391 distinctSessions: 0,
392 message: "No transcript directory on this environment.",
393 });
394 continue;
395 }
396
397 walkedRoots.push(dir);
398 const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));
399 let scannedFiles = 0;
400 let skippedFiles = 0;
401 // Distinct per directory. Buckets carry per-cell session counts, but a
402 // session spans days and models, so clients total this figure instead.
403 const sessionIds = new Set<string>();
404
405 for (const file of files) {
406 livePaths.add(file.path);
407 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
408 if (records.length === 0) {
409 skippedFiles += 1;
410 continue;
411 }
412 scannedFiles += 1;
413 for (const record of records) {
414 // Only sessions that contributed in-window count: the mtime slack
415 // admits boundary files whose records fall outside the range.
416 if (aggregator.add(record) && record.sessionId.length > 0) {
417 sessionIds.add(record.sessionId);
418 }
419 }
420 }
421
422 sources.push({
423 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
424 status: "ok",
425 scannedFiles,
426 skippedFiles,
427 malformedRecords: 0,
428 distinctSessions: sessionIds.size,
429 message: null,
430 });
431 }
432
433 const pruned = pruneScanCache(fileCache, {
434 livePaths,
435 walkedRoots,
436 windowStartMs,
437 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
438 });
439 if (pruned > 0) cacheDirty = true;
440 yield* persistScanCache();
441
442 const aggregated = aggregator.finish();
443 const readAt = yield* DateTime.now;
444 const finishedAtMs = yield* Clock.currentTimeMillis;
445
446 return {
447 contractVersion: USAGE_CONTRACT_VERSION,
448 readAt: DateTime.formatIso(readAt),
449 timeZone: input.timeZone,
450 sinceDay: input.sinceDay,
451 untilDay: input.untilDay,
452 buckets: aggregated.buckets,
453 sources,
454 pricing: {
455 status: ratesStatus,
456 source: LITELLM_RATES_URL,
457 fetchedAt:
458 ratesFetchedAtMs === null
459 ? null
460 : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
461 knownModels: rates.size,
462 },
463 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
464 } satisfies UsageSummary;
465 });
466
467 return { readSummary } as const;
468});
469
470export const layer = Layer.effect(UsageService, make);