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