Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageService.ts

420 lines14.9 KB

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