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