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