Open History to see the last commit
1/**
2 * UsageService - scans provider transcripts and returns priced usage buckets.
3 *
4 * The scan reads native session files and databases, including work driven
5 * outside T3 Code. Cursor's local records provide only partial coverage.
6 *
7 * JSONL transcripts are append-only, so parsed records are memoised per file by
8 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
9 * scans only reparse files that changed, and a file that merely grew resumes
10 * from its cached parse position so only the appended bytes are read.
11 * SQLite readers query live databases each scan so WAL writes remain visible.
12 *
13 * @module UsageService
14 */
15import * as NodeOS from "node:os";
16
17import {
18 ClaudeSettings,
19 CodexSettings,
20 type ProviderInstanceConfig,
21 ProviderInstanceId,
22 USAGE_CONTRACT_VERSION,
23 type ServerSettings as ServerSettingsValue,
24 type UsageProviderKind,
25 type UsageSource,
26 type UsagePricing,
27 type UsageSummary,
28 type UsageSummaryInput,
29 UsageReadError,
30} from "@t3tools/contracts";
31import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
32import * as Cause from "effect/Cause";
33import * as Clock from "effect/Clock";
34import * as Context from "effect/Context";
35import * as Crypto from "effect/Crypto";
36import * as DateTime from "effect/DateTime";
37import * as Deferred from "effect/Deferred";
38import * as Effect from "effect/Effect";
39import * as FileSystem from "effect/FileSystem";
40import * as Layer from "effect/Layer";
41import * as Option from "effect/Option";
42import * as Path from "effect/Path";
43import * as Schema from "effect/Schema";
44import * as Semaphore from "effect/Semaphore";
45import { HttpClient, HttpClientResponse } from "effect/http";
46
47import { writeFileStringAtomically } from "../atomicWrite.ts";
48import * as ServerConfig from "../config.ts";
49import { expandHomePath } from "../pathExpansion.ts";
50import * as ServerSettings from "../serverSettings.ts";
51import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
52import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
53import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
54import { readOpenCodeUsage } from "./opencodeUsageReader.ts";
55import { readAntigravityUsage } from "./antigravityUsageReader.ts";
56import { readCursorAccountUsage } from "./cursorUsageReader.ts";
57import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
58import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
59import {
60 listTranscriptFiles,
61 readDirectoryVolumeId,
62 readTranscriptRecords,
63} from "./usageTranscriptReader.ts";
64import {
65 decodeScanCache,
66 dedupeWithinFile,
67 LEGACY_SCAN_CACHE_FILE_NAME,
68 makeScanCacheWriter,
69 pruneScanCache,
70 SCAN_CACHE_FILE_NAME,
71 type CachedFile,
72 type ScanCache,
73} from "./usageScanCache.ts";
74import type { UsageRecord } from "./usageTranscripts.ts";
75
76const LITELLM_RATES_URL =
77 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
78
79/** Rates move rarely; a day-old table keeps the page working offline. */
80const RATES_TTL_MS = 24 * 60 * 60 * 1000;
81
82/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
83const RATES_REFRESH_FLOOR_MS = 60 * 1000;
84
85/**
86 * Files are filtered by mtime before opening. The slack covers a session whose
87 * last write lands just before local midnight on the window's first day.
88 */
89const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
90const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
91
92/** Longest window the UI offers, plus slack. Older entries are pruned. */
93const CACHE_RETENTION_DAYS = 90;
94
95/** Transcripts parsed at once. More gains little once the disk stays busy. */
96const TRANSCRIPT_READ_CONCURRENCY = 4;
97
98const decodeCodexSettings = Schema.decodeOption(CodexSettings);
99const decodeClaudeSettings = Schema.decodeOption(ClaudeSettings);
100
101/** On-disk shape of the rate snapshot. */
102const RatesCacheFile = Schema.Struct({
103 fetchedAtMs: Schema.Number,
104 document: Schema.Unknown,
105});
106const decodeRatesCache = Schema.decodeUnknownEffect(
107 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
108);
109const encodeRatesCache = Schema.encodeEffect(
110 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
111);
112
113/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
114const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
115const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
116const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
117const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
118
119/** Whether `a` read a later state of its file than `b`. Transcripts only grow. */
120function isLaterRead(a: CachedFile, b: CachedFile): boolean {
121 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
122}
123
124/**
125 * Codex sessions with records in more than one file, such as a rollout that
126 * moved after it was read. Only these need cross-file dedupe keys: within one
127 * file the occurrence count already keeps every key unique, so keying the rest
128 * would only build and hash a string for each of their records.
129 */
130function sharedCodexSessions(
131 files: readonly { readonly records: readonly UsageRecord[] }[],
132): ReadonlySet<string> {
133 const firstFile = new Map<string, number>();
134 const shared = new Set<string>();
135 for (const [index, file] of files.entries()) {
136 let previous = "";
137 for (const { provider, sessionId } of file.records) {
138 if (provider !== "codex" || sessionId === previous || sessionId.length === 0) continue;
139 previous = sessionId;
140 const first = firstFile.get(sessionId);
141 if (first === undefined) firstFile.set(sessionId, index);
142 else if (first !== index) shared.add(sessionId);
143 }
144 }
145 return shared;
146}
147const decodeCachedSources = Schema.decodeUnknownOption(
148 Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }),
149);
150
151export class UsageService extends Context.Service<
152 UsageService,
153 {
154 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
155 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
156 readonly refreshRates: Effect.Effect<UsagePricing>;
157 }
158>()("t3/usage/UsageService") {}
159
160const EMPTY_PRICING: UsagePricing = {
161 status: "unavailable",
162 source: LITELLM_RATES_URL,
163 fetchedAt: null,
164 knownModels: 0,
165};
166
167/** Empty summary, for suites that only need the RPC surface to resolve. */
168const layerTest = Layer.succeed(
169 UsageService,
170 UsageService.of({
171 readSummary: (input) =>
172 Effect.succeed({
173 contractVersion: USAGE_CONTRACT_VERSION,
174 readAt: "1970-01-01T00:00:00.000Z",
175 timeZone: input.timeZone,
176 sinceDay: input.sinceDay,
177 untilDay: input.untilDay,
178 buckets: [],
179 sources: [],
180 pricing: EMPTY_PRICING,
181 scanDurationMs: 0,
182 }),
183 refreshRates: Effect.succeed(EMPTY_PRICING),
184 }),
185);
186
187export const make = Effect.gen(function* () {
188 const crypto = yield* Crypto.Crypto;
189 const fileSystem = yield* FileSystem.FileSystem;
190 const path = yield* Path.Path;
191 const config = yield* ServerConfig.ServerConfig;
192 const settingsService = yield* ServerSettings.ServerSettingsService;
193 const httpClient = yield* HttpClient.HttpClient;
194 const hostEnvironment = yield* HostProcessEnvironment;
195 const platform = yield* HostProcessPlatform;
196
197 const fileCache: ScanCache = new Map();
198 const sourceCache = new Map<string, typeof CachedSource.Type>();
199 let cacheDirty = false;
200 const isWithinDirectory = (filePath: string, dir: string) => {
201 const relative = path.relative(dir, filePath);
202 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
203 };
204
205 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
206 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
207 const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
208 const writeCacheFile = (filePath: string, contents: string) =>
209 writeFileStringAtomically({ filePath, contents }).pipe(
210 Effect.provideService(FileSystem.FileSystem, fileSystem),
211 Effect.provideService(Path.Path, path),
212 );
213 let rates: RateTable = new Map();
214 let ratesFetchedAtMs: number | null = null;
215 let ratesStatus: UsagePricing["status"] = "unavailable";
216 // One fetch at a time. A burst of refreshes from several clients waits on
217 // the first fetch and then sees a table young enough to skip its own.
218 const ratesLock = yield* Semaphore.make(1);
219
220 const pricing = (): UsagePricing => ({
221 status: ratesStatus,
222 source: LITELLM_RATES_URL,
223 fetchedAt:
224 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
225 knownModels: rates.size,
226 });
227
228 /**
229 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
230 * the on-disk snapshot. With neither, every model reports as unpriced rather
231 * than the page failing. `force` refetches inside the TTL so a model that
232 * LiteLLM added since the last fetch gets priced now.
233 */
234 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
235 const now = yield* Clock.currentTimeMillis;
236 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
237 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
238
239 if (ratesFetchedAtMs === null) {
240 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
241 Effect.flatMap((raw) => decodeRatesCache(raw)),
242 Effect.catchCause(() => Effect.succeed(null)),
243 );
244 if (fromDisk !== null) {
245 const parsed = parseRateTable(fromDisk.document);
246 if (parsed.size > 0) {
247 rates = parsed;
248 ratesFetchedAtMs = fromDisk.fetchedAtMs;
249 ratesStatus = "cached";
250 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
251 }
252 }
253 }
254
255 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
256 Effect.flatMap(HttpClientResponse.filterStatusOk),
257 Effect.flatMap((response) => response.json),
258 Effect.timeout(10_000),
259 Effect.catchCause(() => Effect.succeed(null)),
260 );
261 if (fetched === null) {
262 // The refresh failed; whatever we are serving is now past its TTL and
263 // must not keep claiming to be fresh.
264 if (rates.size > 0) ratesStatus = "cached";
265 return;
266 }
267
268 const parsed = parseRateTable(fetched);
269 if (parsed.size === 0) return;
270
271 rates = parsed;
272 ratesFetchedAtMs = now;
273 ratesStatus = "fresh";
274
275 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
276 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
277 Effect.ignoreCause,
278 );
279 });
280
281 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
282
283 const refreshRates = ensureRates(true).pipe(
284 Effect.map(pricing),
285 Effect.withSpan("UsageService.refreshRates"),
286 );
287
288 // A settings failure must not silently discard custom rates or transcript homes.
289 const readSettings = settingsService.getSettings.pipe(
290 Effect.catchCause(
291 (cause) =>
292 new UsageReadError({
293 reason: "scanFailed",
294 detail: "Server settings could not be read.",
295 cause: Cause.squash(cause),
296 }),
297 ),
298 );
299
300 /** Resolves the transcript directory for each provider. */
301 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
302 settings: ServerSettingsValue,
303 retentionCutoffMs: number,
304 ) {
305 const dirs: Array<{
306 provider: UsageProviderKind;
307 dir: string;
308 volumeId: string;
309 fileName?: string;
310 }> = [];
311 const seen = new Set<string>();
312 for (const driver of ["claudeAgent", "codex", "grok"] as const) {
313 // Disabled accounts still have history. Explicit default slots replace
314 // the legacy settings, just as they do in the provider registry.
315 const instances: Array<
316 Pick<ProviderInstanceConfig, "config" | "environment"> & { instanceId: ProviderInstanceId }
317 > = Object.entries(settings.providerInstances)
318 .filter(([, instance]) => instance.driver === driver)
319 .map(([id, instance]) => ({ ...instance, instanceId: ProviderInstanceId.make(id) }));
320 if (!Object.hasOwn(settings.providerInstances, driver)) {
321 instances.push({
322 config: settings.providers[driver],
323 instanceId: ProviderInstanceId.make(driver),
324 });
325 }
326 for (const instance of instances) {
327 const environment = mergeProviderInstanceEnvironment(instance.environment, hostEnvironment);
328 const provider = driver === "claudeAgent" ? "claude" : driver;
329 let home: string;
330 if (driver === "codex") {
331 const decoded = decodeCodexSettings(instance.config ?? {});
332 if (Option.isNone(decoded)) continue;
333 const codexConfig = decoded.value;
334 const environmentHome = environment.CODEX_HOME?.trim();
335 const layout = yield* resolveCodexHomeLayout(
336 codexConfig.setupMode !== "managed" &&
337 !codexConfig.homePath.trim() &&
338 !codexConfig.shadowHomePath.trim() &&
339 environmentHome
340 ? { ...codexConfig, homePath: environmentHome }
341 : codexConfig,
342 );
343 home = layout.sharedHomePath;
344 } else if (driver === "claudeAgent") {
345 const decoded = decodeClaudeSettings(instance.config ?? {});
346 if (Option.isNone(decoded)) continue;
347 const configured = decoded.value.homePath.trim();
348 home = configured
349 ? expandHomePath(configured)
350 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
351 } else {
352 home = expandHomePath(
353 environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
354 );
355 }
356 const directory = path.resolve(home, provider === "claude" ? "projects" : "sessions");
357 const sourceKey = provider + "\0" + directory;
358 const previous = sourceCache.get(sourceKey);
359 // Keep canonical paths and source fingerprints stable after root cleanup,
360 // including aliases and clients merging pre-cleanup environment summaries.
361 const dir = yield* fileSystem
362 .realPath(directory)
363 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
364 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
365 const hasRetainedHistory = fileCache
366 .entries()
367 .some(
368 ([filePath, entry]) =>
369 entry.provider === provider &&
370 entry.mtimeMs >= retentionCutoffMs &&
371 entry.records.length + entry.tailRecords.length > 0 &&
372 isWithinDirectory(filePath, dir),
373 );
374 // A recreated directory still reports the retained history under its old identity.
375 const volumeId =
376 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
377 ? previous.volumeId || currentVolumeId
378 : currentVolumeId;
379 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
380 sourceCache.set(sourceKey, { dir, volumeId });
381 cacheDirty = true;
382 }
383 const key = `${provider}\0${dir}`;
384 if (seen.has(key)) continue;
385 seen.add(key);
386 dirs.push({
387 provider,
388 dir,
389 volumeId,
390 ...(provider === "grok" ? { fileName: "updates.jsonl" } : {}),
391 });
392 }
393 }
394 return dirs;
395 });
396
397 /**
398 * Loads the persisted scan cache exactly once per process.
399 *
400 * `Effect.cached` makes concurrent first readers await the same load rather
401 * than each seeing a "loaded" flag set before the read finished and cold
402 * scanning against an empty cache.
403 */
404 const ensureScanCacheLoaded = yield* Effect.cached(
405 Effect.gen(function* () {
406 const readDocument = (filePath: string) =>
407 fileSystem.readFileString(filePath).pipe(
408 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
409 Effect.catchCause(() => Effect.succeed(null)),
410 );
411 let document = yield* readDocument(scanCachePath);
412 if (document === null) {
413 document = yield* readDocument(legacyScanCachePath);
414 // Write the migrated cache to its own file on the next scan.
415 cacheDirty = document !== null;
416 }
417 if (document === null) return;
418 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
419 const sources = decodeCachedSources(document);
420 if (Option.isSome(sources)) {
421 for (const [key, source] of Object.entries(sources.value.sources))
422 sourceCache.set(key, source);
423 }
424 }),
425 );
426
427 const writeScanCache = makeScanCacheWriter();
428 // Scans with different windows can finish together; serializing the writes
429 // keeps an older snapshot from landing after a newer one.
430 const persistLock = yield* Semaphore.make(1);
431
432 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
433 if (!cacheDirty) return;
434 // Cleared before encoding, so a scan that changes the cache while this
435 // write is in flight marks it dirty again. A failed write restores the
436 // flag, so the next scan retries instead of leaving disk stale.
437 cacheDirty = false;
438 yield* Effect.sync(() =>
439 writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
440 ).pipe(
441 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
442 // A cache we cannot write is a slower next start, not a failed read.
443 Effect.catchCause(() =>
444 Effect.sync(() => {
445 cacheDirty = true;
446 }),
447 ),
448 persistLock.withPermit,
449 );
450 });
451
452 /**
453 * Parses one transcript, reusing the cached result when it is unchanged.
454 *
455 * A file that only grew re-parses from the cached position, so an actively
456 * written multi-hundred-megabyte rollout costs its appended bytes per scan
457 * rather than a full re-read. The reader verifies the position's guard bytes
458 * and silently restarts from byte 0 when they no longer match.
459 *
460 * A fresh parse comes back as `update` for the caller to cache, with the
461 * entry it was built from. Reads run concurrently, and the caller stores
462 * updates in walk order rather than completion order: saved records of
463 * deleted transcripts aggregate in cache order, where the first copy of a
464 * duplicate wins.
465 */
466 const readFileRecords = (
467 filePath: string,
468 size: number,
469 mtimeMs: number,
470 provider: UsageProviderKind,
471 ): Effect.Effect<{
472 readonly records: readonly UsageRecord[];
473 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
474 }> =>
475 Effect.gen(function* () {
476 const cached = fileCache.get(filePath);
477 // Provider is part of the identity: if both providers were ever pointed
478 // at one directory, a hit parsed by the other parser must not be reused.
479 if (
480 cached &&
481 cached.size === size &&
482 cached.mtimeMs === mtimeMs &&
483 cached.provider === provider
484 ) {
485 return {
486 records:
487 cached.tailRecords.length === 0
488 ? cached.records
489 : [...cached.records, ...cached.tailRecords],
490 };
491 }
492
493 // Only a strictly grown file may resume. Same size with a new mtime, or
494 // a shrunken file, means rewritten content; re-parse it whole.
495 const resumeFrom =
496 cached !== undefined && cached.provider === provider && size > cached.size
497 ? cached.position
498 : undefined;
499
500 const parsed = yield* Effect.promise(() =>
501 readTranscriptRecords(filePath, provider, resumeFrom),
502 );
503 // A read failure is not an empty transcript: caching it under this
504 // (size, mtime) would silently drop the file's usage until it changes.
505 if (parsed === null)
506 return {
507 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
508 };
509
510 // Stored already de-duplicated within the file, which is 99% of all
511 // duplicates. The aggregator still runs the cross-file dedupe pass. One
512 // seen set spans the cached base, the new lines, and the tail so a
513 // resumed parse dedupes exactly like a full one.
514 const base = parsed.resumed && cached !== undefined ? cached.records : [];
515 const seen = new Set<string>();
516 const records = dedupeWithinFile([...base, ...parsed.records], seen);
517 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
518
519 return {
520 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
521 update: {
522 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
523 replaces: cached,
524 },
525 };
526 });
527
528 /** One provider directory's walk and parse, before rates are involved. */
529 interface ScannedDir {
530 readonly provider: UsageProviderKind;
531 readonly dir: string;
532 readonly volumeId: string;
533 readonly hostId?: string;
534 readonly status?: UsageSource["status"];
535 readonly message?: string;
536 readonly action?: UsageSource["action"];
537 /** Parsed records per file, or `null` when the directory does not exist. */
538 readonly files:
539 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
540 | null;
541 }
542
543 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
544 windowStartMs: number,
545 settings: ServerSettingsValue,
546 retentionCutoffMs: number,
547 ) {
548 // The home resolvers ask for `Path` themselves; satisfy them from the
549 // instance we already hold so the scan stays context-free.
550 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
551 Effect.provideService(Path.Path, path),
552 );
553 const scanned: ScannedDir[] = [];
554 for (const { provider, dir, volumeId, fileName } of dirs) {
555 const exists = yield* fileSystem
556 .exists(dir)
557 .pipe(Effect.catchCause(() => Effect.succeed(false)));
558 if (!exists) {
559 scanned.push({ provider, dir, volumeId, files: null });
560 continue;
561 }
562 const files = yield* Effect.promise(() =>
563 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
564 );
565 // A cold parse waits on disk reads, so a few files in flight read
566 // close to twice as fast. Results keep walk order.
567 const read = yield* Effect.forEach(
568 files,
569 (file) =>
570 readFileRecords(file.path, file.size, file.mtimeMs, provider).pipe(
571 Effect.map((result) => ({ path: file.path, ...result })),
572 ),
573 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
574 );
575 const parsedFiles = read.map(({ path, records, update }) => {
576 if (update === undefined) return { path, records };
577 // A scan of another window may have cached its own read of this file
578 // meanwhile. Then keep whichever read saw the later file, so a slower
579 // scan never replaces newer usage with older.
580 const current = fileCache.get(path);
581 if (
582 current === update.replaces ||
583 current === undefined ||
584 !isLaterRead(current, update.entry)
585 ) {
586 fileCache.set(path, update.entry);
587 cacheDirty = true;
588 }
589 return { path, records };
590 });
591 scanned.push({ provider, dir, volumeId, files: parsedFiles });
592 }
593
594 const home = NodeOS.homedir();
595 const envRoots = Effect.fnUntraced(function* (key: string, defaults: readonly string[]) {
596 const roots = hostEnvironment[key]
597 ?.split(",")
598 .map((value) => value.trim())
599 .filter(Boolean);
600 const canonical = new Set<string>();
601 for (const root of roots?.length ? roots : defaults) {
602 const resolved = path.resolve(expandHomePath(root));
603 canonical.add(
604 yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),
605 );
606 }
607 return [...canonical];
608 });
609 const dataHome = hostEnvironment["XDG_DATA_HOME"]?.trim();
610 for (const dir of yield* envRoots("OPENCODE_DATA_DIR", [
611 path.join(
612 dataHome && path.isAbsolute(dataHome) ? dataHome : path.join(home, ".local", "share"),
613 "opencode",
614 ),
615 ])) {
616 const result = yield* Effect.promise(() => readOpenCodeUsage(dir, windowStartMs));
617 scanned.push({
618 provider: "opencode",
619 dir,
620 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
621 files: result.missing && !result.error ? null : result.files,
622 status: result.error ? "partial" : "ok",
623 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
624 });
625 }
626 const antigravityRoots = yield* envRoots("ANTIGRAVITY_DATA_DIR", [
627 ...["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"].map((name) =>
628 path.join(home, ".gemini", name),
629 ),
630 path.join(home, ".config", "antigravity"),
631 ]);
632 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
633 if (instance.driver === "antigravity") {
634 const directories = yield* resolveAntigravityInstanceDirectories(
635 config.stateDir,
636 ProviderInstanceId.make(instanceId),
637 ).pipe(
638 Effect.provideService(Crypto.Crypto, crypto),
639 Effect.provideService(Path.Path, path),
640 Effect.mapError(
641 (cause) =>
642 new UsageReadError({
643 reason: "scanFailed",
644 detail: "Antigravity profile directory could not be resolved.",
645 cause,
646 }),
647 ),
648 );
649 antigravityRoots.push(path.join(directories.profile, "antigravity-acp"));
650 }
651 }
652 const antigravityDirs = new Set<string>();
653 for (const root of antigravityRoots) {
654 const resolvedRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
655 const nested = path.join(resolvedRoot, "conversations");
656 const dir = (yield* fileSystem
657 .exists(nested)
658 .pipe(Effect.catchCause(() => Effect.succeed(false))))
659 ? nested
660 : resolvedRoot;
661 antigravityDirs.add(yield* fileSystem.realPath(dir).pipe(Effect.orElseSucceed(() => dir)));
662 }
663 const antigravity = yield* Effect.promise(() =>
664 readAntigravityUsage([...antigravityDirs], windowStartMs),
665 );
666 for (const dir of antigravityDirs) {
667 const exists = yield* fileSystem
668 .exists(dir)
669 .pipe(Effect.catchCause(() => Effect.succeed(false)));
670 const failed = antigravity.errors.some(
671 (error) => error === dir || error.startsWith(`${dir}${path.sep}`),
672 );
673 scanned.push({
674 provider: "antigravity",
675 dir,
676 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
677 files: !exists && !failed ? null : antigravity.files.filter((file) => file.root === dir),
678 status: failed ? "partial" : "ok",
679 ...(failed ? { message: "Some Antigravity history could not be read." } : {}),
680 });
681 }
682 const cursorUserHome =
683 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
684 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
685 const cursorHome =
686 platform === "darwin"
687 ? path.join(cursorUserHome, "Library", "Application Support")
688 : platform === "win32"
689 ? hostEnvironment["APPDATA"] || path.join(cursorUserHome, "AppData", "Roaming")
690 : configHome && path.isAbsolute(configHome)
691 ? configHome
692 : path.join(cursorUserHome, ".config");
693 const cursorAuthPath =
694 platform === "darwin"
695 ? path.join(cursorUserHome, ".cursor", "auth.json")
696 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
697 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
698 const loginUnavailable =
699 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
700 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
701 credentialStore === "memory";
702 if (
703 platform === "darwin" &&
704 credentialStore !== "file" &&
705 !loginUnavailable &&
706 !settings.cursorKeychainUsageEnabled
707 ) {
708 scanned.push({
709 provider: "cursor",
710 dir: cursorAuthPath,
711 volumeId: "",
712 files: null,
713 message: "Cursor account usage is off on this environment.",
714 action: "enableCursorKeychain",
715 });
716 return scanned;
717 }
718 const cursorUntilMs = yield* Clock.currentTimeMillis;
719 const account = loginUnavailable
720 ? {
721 accountKey: null,
722 records: [],
723 missing: true,
724 error: "Cursor account history needs a Cursor CLI login on this server.",
725 }
726 : yield* Effect.promise(() =>
727 readCursorAccountUsage(
728 platform === "darwin" && credentialStore !== "file"
729 ? { kind: "keychain" }
730 : cursorAuthPath,
731 windowStartMs,
732 cursorUntilMs,
733 ),
734 );
735 // No saved login means there is no account source to report, not a setup error.
736 if (account.missing && account.error === null) return scanned;
737 if (account.accountKey !== null && account.error === null && !account.missing) {
738 // The same account includes CLI and desktop history from every machine.
739 // A stable remote fingerprint prevents connected environments counting it twice.
740 const source = `cursor-account:${account.accountKey}`;
741 scanned.push({
742 provider: "cursor",
743 dir: source,
744 hostId: "cursor.com",
745 volumeId: account.accountKey,
746 files: [{ path: source, records: account.records }],
747 status: "ok",
748 });
749 return scanned;
750 }
751 scanned.push({
752 provider: "cursor",
753 dir: cursorAuthPath,
754 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(cursorAuthPath)),
755 // Never combine a local fallback with another server's account-wide history.
756 files: null,
757 message:
758 account.error ?? "Cursor account history needs a Cursor CLI login saved on this server.",
759 });
760 return scanned;
761 });
762
763 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
764 input: UsageSummaryInput,
765 settings: ServerSettingsValue,
766 ) {
767 if (input.sinceDay > input.untilDay) {
768 return yield* new UsageReadError({
769 reason: "invalidWindow",
770 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
771 });
772 }
773
774 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
775 if (input.resolution === "hour") {
776 const sinceTime =
777 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
778 const untilTime =
779 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
780 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
781 return yield* new UsageReadError({
782 reason: "invalidWindow",
783 detail: "Hourly usage requires valid sinceTime and untilTime instants",
784 });
785 }
786 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
787 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
788 const durationMs = untilTimeMs - sinceTimeMs;
789 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
790 return yield* new UsageReadError({
791 reason: "invalidWindow",
792 detail: "Hourly usage window must be greater than zero and at most 24 hours",
793 });
794 }
795 hourlyWindow = { sinceTimeMs, untilTimeMs };
796 }
797
798 const startedAtMs = yield* Clock.currentTimeMillis;
799 yield* ensureScanCacheLoaded;
800
801 const hostId = NodeOS.hostname();
802 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
803 if (Option.isNone(windowStart)) {
804 return yield* new UsageReadError({
805 reason: "invalidWindow",
806 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
807 });
808 }
809 const windowStartMs =
810 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
811
812 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
813
814 // Pricing only matters once records are aggregated, so the rate table
815 // loads while transcripts stream instead of gating them: a cold rates
816 // fetch on a slow network no longer delays the scan by its own timeout.
817 const [, scannedDirs] = yield* Effect.all(
818 [ensureRates(false), collectDirs(windowStartMs, settings, retentionCutoffMs)],
819 { concurrency: 2 },
820 );
821
822 const aggregator = new UsageAggregator({
823 timeZone: input.timeZone,
824 sinceDay: input.sinceDay,
825 untilDay: input.untilDay,
826 resolution: input.resolution ?? "day",
827 ...hourlyWindow,
828 rates,
829 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
830 modelAliases: resolveModelAliases(settings.usageModelAliases),
831 });
832
833 const sources: UsageSource[] = [];
834
835 // Cleanup may remove transcripts, but the usage we already saved still
836 // contributes to its source through the normal aggregation and dedupe
837 // path. Like the walk, skip files last written before the window: they
838 // cannot hold records inside it.
839 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
840 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
841 const retainedFiles = [...(files ?? [])];
842 const livePaths = new Set(retainedFiles.map((file) => file.path));
843 for (const [filePath, entry] of fileCache) {
844 if (
845 entry.provider !== provider ||
846 entry.mtimeMs < retainedSinceMs ||
847 livePaths.has(filePath) ||
848 !isWithinDirectory(filePath, dir)
849 )
850 continue;
851 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
852 }
853 return retainedFiles;
854 });
855 const sharedSessions = sharedCodexSessions(filesByDir.flat());
856
857 for (const [
858 index,
859 { provider, dir, volumeId, files, status, message, action, hostId: sourceHostId },
860 ] of scannedDirs.entries()) {
861 let scannedFiles = 0;
862 let skippedFiles = 0;
863 // Distinct per directory. Buckets carry per-cell session counts, but a
864 // session spans days and models, so clients total this figure instead.
865 const sessionIds = new Set<string>();
866
867 for (const file of filesByDir[index] ?? []) {
868 if (file.records.length === 0) {
869 skippedFiles += 1;
870 continue;
871 }
872 scannedFiles += 1;
873 const codexEventOccurrences = new Map<string, number>();
874 for (const record of file.records) {
875 let usageRecord = record;
876 if (record.provider === "codex" && sharedSessions.has(record.sessionId)) {
877 // Match moved rollout copies without collapsing repeated equal events
878 // within one rollout (timestamps can have only second precision).
879 // Only sessions seen in several files can have a copy to match.
880 const key = encodeUsageRecordKey([
881 record.provider,
882 record.sessionId,
883 record.timestampMs,
884 record.model,
885 record.totals,
886 ]);
887 const occurrence = (codexEventOccurrences.get(key) ?? 0) + 1;
888 codexEventOccurrences.set(key, occurrence);
889 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
890 }
891 // Only sessions contributing in-window count; the mtime slack can
892 // admit boundary files whose records fall outside the range.
893 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
894 sessionIds.add(record.sessionId);
895 }
896 }
897 }
898
899 sources.push({
900 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
901 // Clients exclude missing sources, so saved records remain an available source.
902 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
903 scannedFiles,
904 skippedFiles,
905 malformedRecords: 0,
906 distinctSessions: sessionIds.size,
907 message:
908 message ?? (files === null ? "No transcript directory on this environment." : null),
909 ...(action ? { action } : {}),
910 });
911 }
912
913 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
914 if (pruned > 0) cacheDirty = true;
915 yield* persistScanCache();
916
917 const aggregated = aggregator.finish();
918 const readAt = yield* DateTime.now;
919 const finishedAtMs = yield* Clock.currentTimeMillis;
920
921 return {
922 contractVersion: USAGE_CONTRACT_VERSION,
923 readAt: DateTime.formatIso(readAt),
924 timeZone: input.timeZone,
925 sinceDay: input.sinceDay,
926 untilDay: input.untilDay,
927 buckets: aggregated.buckets,
928 sources,
929 pricing: pricing(),
930 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
931 } satisfies UsageSummary;
932 });
933
934 /**
935 * In-flight scans by window and usage settings, so concurrent identical requests (the usage
936 * page open on two clients at once) share one scan instead of racing over
937 * the same corpus twice.
938 */
939 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
940
941 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
942 JSON.stringify([
943 input.timeZone,
944 input.sinceDay,
945 input.untilDay,
946 input.resolution ?? "day",
947 input.sinceTime ?? null,
948 input.untilTime ?? null,
949 settings.usagePriceOverrides,
950 settings.usageModelAliases,
951 settings.cursorKeychainUsageEnabled,
952 ]);
953
954 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
955 const settings = yield* readSettings;
956 const key = scanKey(input, settings);
957 const deferred = yield* Effect.uninterruptible(
958 Effect.gen(function* () {
959 const existing = inflightScans.get(key);
960 if (existing !== undefined) return existing;
961
962 // Enrollment and detached-fiber creation must be atomic. Otherwise a
963 // canceled first caller can leave a Deferred with no scan to finish it.
964 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
965 inflightScans.set(key, created);
966 // Detached so one departing client cannot tear the scan out from under
967 // the fibers awaiting it; a finished scan warms the cache either way.
968 yield* scanSummary(input, settings).pipe(
969 Effect.onExit((exit) =>
970 Effect.sync(() => inflightScans.delete(key)).pipe(
971 Effect.andThen(Deferred.done(created, exit)),
972 ),
973 ),
974 Effect.forkDetach,
975 );
976 return created;
977 }),
978 );
979 // Waiting stays interruptible. The detached scan continues for other
980 // callers and still warms the cache if this caller leaves.
981 return yield* Deferred.await(deferred);
982 });
983
984 return { readSummary, refreshRates } as const;
985});
986
987export const layer = Layer.effect(UsageService, make);