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