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

UsageService.ts

1,265 lines49.0 KB

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 * OpenCode's SQLite reader queries the live database each scan so WAL writes
12 * remain visible. Antigravity databases are memoised in memory while the
13 * database and its WAL keep the same `(size, mtime, ctime)`.
14 *
15 * Cursor's account API is slow, so its source answers from a cache and marks
16 * itself `refreshing` while a background refresh runs; `awaitRefresh` waits
17 * for that refresh instead. See `cursorAccountCache`.
18 *
19 * @module UsageService
20 */
21import * as NodeOS from "node:os";
22​
23import {
24 type ProviderInstanceConfig,
25 ProviderInstanceId,
26 USAGE_CONTRACT_VERSION,
27 type ServerSettings as ServerSettingsValue,
28 type UsageProviderKind,
29 type UsageSource,
30 type UsagePricing,
31 type UsageSummary,
32 type UsageSummaryInput,
33 UsageReadError,
34} from "@t3tools/contracts";
35import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
36import * as Cause from "effect/Cause";
37import * as Clock from "effect/Clock";
38import * as Context from "effect/Context";
39import * as Crypto from "effect/Crypto";
40import * as DateTime from "effect/DateTime";
41import * as Deferred from "effect/Deferred";
42import * as Effect from "effect/Effect";
43import * as Exit from "effect/Exit";
44import * as Fiber from "effect/Fiber";
45import * as FileSystem from "effect/FileSystem";
46import * as Layer from "effect/Layer";
47import * as Option from "effect/Option";
48import * as Path from "effect/Path";
49import * as Schema from "effect/Schema";
50import * as Semaphore from "effect/Semaphore";
51import { HttpClient, HttpClientResponse } from "effect/http";
52​
53import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
54import * as ServerConfig from "../config.ts";
55import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
56import * as ServerSettings from "../serverSettings.ts";
57import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
58import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
59import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
60import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
61import type {
62 ProviderUsageInstance,
63 TranscriptUsageFormat,
64 UsageRecord,
65} from "@t3tools/provider-core/server/usage";
66import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts";
67import {
68 CURSOR_ACCOUNT_CACHE_FILE_NAME,
69 CURSOR_ACCOUNT_TTL_MS,
70 cursorFetchRange,
71 decodeCursorAccountCaches,
72 encodeCursorAccountCaches,
73 isCursorCacheFresh,
74 mergeCursorFetch,
75 type CursorAccountCache,
76 type CursorCredentialSource,
77} from "./cursorAccountCache.ts";
78import * as CursorUsageReader from "./cursorUsageReader.ts";
79import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts";
80import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts";
81import {
82 listTranscriptFiles,
83 readDirectoryVolumeId,
84 readTranscriptRecords,
85} from "./usageTranscriptReader.ts";
86import {
87 decodeScanCache,
88 dedupeWithinFile,
89 LEGACY_SCAN_CACHE_FILE_NAME,
90 makeScanCacheWriter,
91 pruneScanCache,
92 SCAN_CACHE_FILE_NAME,
93 type CachedFile,
94 type ScanCache,
95} from "./usageScanCache.ts";
96​
97const LITELLM_RATES_URL =
98 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
99​
100/** Rates move rarely; a day-old table keeps the page working offline. */
101const RATES_TTL_MS = 24 * 60 * 60 * 1000;
102​
103/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
104const RATES_REFRESH_FLOOR_MS = 60 * 1000;
105​
106/**
107 * Files are filtered by mtime before opening. The slack covers a session whose
108 * last write lands just before local midnight on the window's first day.
109 */
110const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
111const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
112​
113/**
114 * The longest window the UI offers, 90 days, plus its `MTIME_SLACK_MS`, rounded
115 * up. Older entries are pruned.
116 */
117const CACHE_RETENTION_DAYS = 92;
118​
119const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
120​
121/** Transcripts parsed at once. More gains little once the disk stays busy. */
122const TRANSCRIPT_READ_CONCURRENCY = 4;
123​
124/** The transcript readers, in driver order. */
125const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
126 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
127);
128​
129/** The scan readers, in driver order. */
130const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
131 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
132);
133​
134/** Transcript formats by provider, for decoding the persisted scan cache. */
135const transcriptFormats = new Map(
136 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
137);
138​
139/** One transcript directory to scan. */
140interface TranscriptSource {
141 readonly provider: UsageProviderKind;
142 readonly format: TranscriptUsageFormat<unknown>;
143 readonly dir: string;
144 readonly volumeId: string;
145 readonly fileName?: string;
147​
148/** On-disk shape of the rate snapshot. */
149const RatesCacheFile = Schema.Struct({
150 fetchedAtMs: Schema.Number,
151 document: Schema.Unknown,
152});
153const decodeRatesCache = Schema.decodeUnknownEffect(
154 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
155);
156const encodeRatesCache = Schema.encodeEffect(
157 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
158);
159​
160/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
161const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
162const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
163const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
164const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
165​
166/** Whether `a` read a later state of its file than `b`. Transcripts only grow. */
167function isLaterRead(a: CachedFile, b: CachedFile): boolean {
168 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
170​
171/** Providers whose format lets one session's records appear in several files. */
172const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
173 transcriptReaders.flatMap(({ reader }) =>
174 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
175 ),
176);
177​
178/**
179 * Sessions of `sharedSessionProviders` with records in more than one file,
180 * such as a rollout that moved after it was read. Only these need cross-file
181 * dedupe keys: within one file the occurrence count already keeps every key
182 * unique, so keying the rest would only build and hash a string for each of
183 * their records.
184 */
185function sharedSessions(
186 files: readonly { readonly records: readonly UsageRecord[] }[],
187): ReadonlySet<string> {
188 const firstFile = new Map<string, number>();
189 const shared = new Set<string>();
190 for (const [index, file] of files.entries()) {
191 let previous = "";
192 for (const { provider, sessionId } of file.records) {
193 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
194 continue;
195 previous = sessionId;
196 const first = firstFile.get(sessionId);
197 if (first === undefined) firstFile.set(sessionId, index);
198 else if (first !== index) shared.add(sessionId);
199 }
200 }
201 return shared;
203const decodeCachedSources = Schema.decodeUnknownOption(
204 Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }),
205);
206​
207export class UsageService extends Context.Service<
208 UsageService,
209 {
210 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
211 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
212 readonly refreshRates: Effect.Effect<UsagePricing>;
213 }
214>()("t3/usage/UsageService") {}
215​
216const EMPTY_PRICING: UsagePricing = {
217 status: "unavailable",
218 source: LITELLM_RATES_URL,
219 fetchedAt: null,
220 knownModels: 0,
221};
222​
223/** Empty summary, for suites that only need the RPC surface to resolve. */
224const layerTest = Layer.succeed(
225 UsageService,
226 UsageService.of({
227 readSummary: (input) =>
228 Effect.succeed({
229 contractVersion: USAGE_CONTRACT_VERSION,
230 readAt: "1970-01-01T00:00:00.000Z",
231 timeZone: input.timeZone,
232 sinceDay: input.sinceDay,
233 untilDay: input.untilDay,
234 buckets: [],
235 sources: [],
236 pricing: EMPTY_PRICING,
237 scanDurationMs: 0,
238 }),
239 refreshRates: Effect.succeed(EMPTY_PRICING),
240 }),
241);
242​
243export const make = Effect.gen(function* () {
244 const crypto = yield* Crypto.Crypto;
245 const fileSystem = yield* FileSystem.FileSystem;
246 const path = yield* Path.Path;
247 const config = yield* ServerConfig.ServerConfig;
248 const settingsService = yield* ServerSettings.ServerSettingsService;
249 const httpClient = yield* HttpClient.HttpClient;
250 const hostEnvironment = yield* HostProcessEnvironment;
251 const platform = yield* HostProcessPlatform;
252 const cursorAccountReader = yield* CursorUsageReader.CursorAccountReader;
253 // The readers yield their own services; scans run them against this context.
254 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
255​
256 const fileCache: ScanCache = new Map();
257 const antigravityCache = makeAntigravityUsageCache();
258 const sourceCache = new Map<string, typeof CachedSource.Type>();
259 let cacheDirty = false;
260 /** Cursor account caches by credential source. */
261 const cursorCaches = new Map<string, CursorAccountCache>();
262 let cursorCacheDirty = false;
263 /**
264 * The last failed refresh per credential source, standing for a TTL so a
265 * client refetching a broken login does not refetch Cursor each time. A
266 * `null` error means there is no login: no source to report.
267 */
268 const cursorFailures = new Map<
269 string,
270 { readonly atMs: number; readonly error: string | null }
271 >();
272 /** The refresh in flight per credential source, which every read joins. */
273 const cursorRefreshes = new Map<string, Deferred.Deferred<void>>();
274 const isWithinDirectory = (filePath: string, dir: string) => {
275 const relative = path.relative(dir, filePath);
276 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
277 };
278​
279 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
280 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
281 const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
282 const cursorCachePath = path.join(config.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
283 const writeCacheFile = (filePath: string, contents: string) =>
284 writeFileStringAtomically({ filePath, contents }).pipe(
285 Effect.provideService(FileSystem.FileSystem, fileSystem),
286 Effect.provideService(Path.Path, path),
287 );
288 let rates: RateTable = new Map();
289 let ratesFetchedAtMs: number | null = null;
290 let ratesStatus: UsagePricing["status"] = "unavailable";
291 // One fetch at a time. A burst of refreshes from several clients waits on
292 // the first fetch and then sees a table young enough to skip its own.
293 const ratesLock = yield* Semaphore.make(1);
294​
295 const pricing = (): UsagePricing => ({
296 status: ratesStatus,
297 source: LITELLM_RATES_URL,
298 fetchedAt:
299 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
300 knownModels: rates.size,
301 });
302​
303 /**
304 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
305 * the on-disk snapshot. With neither, every model reports as unpriced rather
306 * than the page failing. `force` refetches inside the TTL so a model that
307 * LiteLLM added since the last fetch gets priced now.
308 */
309 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
310 const now = yield* Clock.currentTimeMillis;
311 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
312 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
313​
314 if (ratesFetchedAtMs === null) {
315 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
316 Effect.flatMap((raw) => decodeRatesCache(raw)),
317 Effect.catchCause(() => Effect.succeed(null)),
318 );
319 if (fromDisk !== null) {
320 const parsed = parseRateTable(fromDisk.document);
321 if (parsed.size > 0) {
322 rates = parsed;
323 ratesFetchedAtMs = fromDisk.fetchedAtMs;
324 ratesStatus = "cached";
325 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
326 }
327 }
328 }
329​
330 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
331 Effect.flatMap(HttpClientResponse.filterStatusOk),
332 Effect.flatMap((response) => response.json),
333 Effect.timeout(10_000),
334 Effect.catchCause(() => Effect.succeed(null)),
335 );
336 if (fetched === null) {
337 // The refresh failed; whatever we are serving is now past its TTL and
338 // must not keep claiming to be fresh.
339 if (rates.size > 0) ratesStatus = "cached";
340 return;
341 }
342​
343 const parsed = parseRateTable(fetched);
344 if (parsed.size === 0) return;
345​
346 rates = parsed;
347 ratesFetchedAtMs = now;
348 ratesStatus = "fresh";
349​
350 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
351 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
352 Effect.ignoreCause,
353 );
354 });
355​
356 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
357​
358 const refreshRates = ensureRates(true).pipe(
359 Effect.map(pricing),
360 Effect.withSpan("UsageService.refreshRates"),
361 );
362​
363 // A settings failure must not silently discard custom rates or transcript homes.
364 const readSettings = settingsService.getSettings.pipe(
365 Effect.catchCause(
366 (cause) =>
367 new UsageReadError({
368 reason: "scanFailed",
369 detail: "Server settings could not be read.",
370 cause: Cause.squash(cause),
371 }),
372 ),
373 );
374​
375 /**
376 * Every instance of `driver` with its decoded config, or none when it does
377 * not decode. Disabled accounts still have history. An unconfigured default
378 * slot runs with default config, just as it does in the provider registry.
379 */
380 const usageInstances = <Config>(
381 driver: ProviderDriver<Config, unknown, unknown>,
382 settings: ServerSettingsValue,
383 ): Array<ProviderUsageInstance<Config>> => {
384 const entries: Array<
385 readonly [ProviderInstanceId, Pick<ProviderInstanceConfig, "config" | "environment">, boolean]
386 > = Object.entries(settings.providerInstances)
387 .filter(([, instance]) => instance.driver === driver.driverKind)
388 .map(([id, instance]) => [ProviderInstanceId.make(id), instance, true] as const);
389 if (!Object.hasOwn(settings.providerInstances, driver.driverKind)) {
390 entries.push([ProviderInstanceId.make(driver.driverKind), {}, false]);
391 }
392 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
393 return entries.map(([instanceId, instance, configured]) => ({
394 instanceId,
395 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
396 environment: mergeProviderInstanceEnvironment(instance.environment, hostEnvironment),
397 configured,
398 }));
399 };
400​
401 /** Resolves every transcript directory the usage readers point at. */
402 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
403 settings: ServerSettingsValue,
404 retentionCutoffMs: number,
405 ) {
406 const dirs: Array<TranscriptSource> = [];
407 const seen = new Set<string>();
408 for (const { driver, reader } of transcriptReaders) {
409 const { provider, format } = reader;
410 const directories = yield* Effect.forEach(usageInstances(driver, settings), (instance) =>
411 reader.directories(instance),
412 );
413 for (const { dir: directory, fileName } of directories.flat()) {
414 const sourceKey = provider + "\0" + directory;
415 const previous = sourceCache.get(sourceKey);
416 // Keep canonical paths and source fingerprints stable after root cleanup,
417 // including aliases and clients merging pre-cleanup environment summaries.
418 const dir = yield* fileSystem
419 .realPath(directory)
420 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
421 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
422 const hasRetainedHistory = fileCache
423 .entries()
424 .some(
425 ([filePath, entry]) =>
426 entry.provider === provider &&
427 entry.mtimeMs >= retentionCutoffMs &&
428 entry.records.length + entry.tailRecords.length > 0 &&
429 isWithinDirectory(filePath, dir),
430 );
431 // A recreated directory still reports the retained history under its old identity.
432 const volumeId =
433 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
434 ? previous.volumeId || currentVolumeId
435 : currentVolumeId;
436 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
437 sourceCache.set(sourceKey, { dir, volumeId });
438 cacheDirty = true;
439 }
440 const key = `${provider}\0${dir}`;
441 if (seen.has(key)) continue;
442 seen.add(key);
443 dirs.push({
444 provider,
445 format,
446 dir,
447 volumeId,
448 ...(fileName === undefined ? {} : { fileName }),
449 });
450 }
451 }
452 return dirs;
453 });
454​
455 /**
456 * Loads the persisted scan and Cursor account caches exactly once per process.
457 *
458 * `Effect.cached` makes concurrent first readers await the same load rather
459 * than each seeing a "loaded" flag set before the read finished and cold
460 * scanning against an empty cache.
461 */
462 const ensureScanCacheLoaded = yield* Effect.cached(
463 Effect.gen(function* () {
464 const readDocument = (filePath: string) =>
465 fileSystem.readFileString(filePath).pipe(
466 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
467 Effect.catchCause(() => Effect.succeed(null)),
468 );
469 for (const [key, cache] of decodeCursorAccountCaches(yield* readDocument(cursorCachePath))) {
470 cursorCaches.set(key, cache);
471 }
472 let document = yield* readDocument(scanCachePath);
473 if (document === null) {
474 document = yield* readDocument(legacyScanCachePath);
475 // Write the migrated cache to its own file on the next scan.
476 cacheDirty = document !== null;
477 }
478 if (document === null) return;
479 for (const [path, entry] of decodeScanCache(document, transcriptFormats)) {
480 fileCache.set(path, entry);
481 }
482 const sources = decodeCachedSources(document);
483 if (Option.isSome(sources)) {
484 for (const [key, source] of Object.entries(sources.value.sources))
485 sourceCache.set(key, source);
486 }
487 }),
488 );
489​
490 const writeScanCache = makeScanCacheWriter();
491 // Scans with different windows can finish together; serializing the writes
492 // keeps an older snapshot from landing after a newer one.
493 const persistLock = yield* Semaphore.make(1);
494​
495 // Each dirty flag is cleared before encoding, so a change while the write is
496 // in flight marks it dirty again. A failed write restores the flag, so the
497 // next persist retries instead of leaving disk stale. A cache we cannot
498 // write is a slower next start, not a failed read.
499 const persistCaches = Effect.gen(function* () {
500 if (cacheDirty) {
501 cacheDirty = false;
502 yield* Effect.sync(() =>
503 writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
504 ).pipe(
505 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
506 Effect.catchCause(() =>
507 Effect.sync(() => {
508 cacheDirty = true;
509 }),
510 ),
511 );
512 }
513 if (cursorCacheDirty) {
514 cursorCacheDirty = false;
515 yield* Effect.sync(() => encodeCursorAccountCaches(cursorCaches)).pipe(
516 Effect.flatMap((contents) => writeCacheFile(cursorCachePath, contents)),
517 Effect.catchCause(() =>
518 Effect.sync(() => {
519 cursorCacheDirty = true;
520 }),
521 ),
522 );
523 }
524 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
525​
526 const pendingPersists = new Set<Fiber.Fiber<void>>();
527 /** Writes dirty caches in the background, after the summary that dirtied them answers. */
528 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
529 Effect.map((fiber) => {
530 pendingPersists.add(fiber);
531 fiber.addObserver(() => pendingPersists.delete(fiber));
532 }),
533 );
534 /** Waits for every write scheduled so far, as a restart would need. */
535 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
536 Effect.asVoid,
537 );
538 // A write still running when the service shuts down finishes first, so the
539 // next start does not lose the last scan.
540 yield* Effect.addFinalizer(() => awaitPersisted);
541​
542 /**
543 * Parses one transcript, reusing the cached result when it is unchanged.
544 *
545 * A file that only grew re-parses from the cached position, so an actively
546 * written multi-hundred-megabyte rollout costs its appended bytes per scan
547 * rather than a full re-read. The reader verifies the position's guard bytes
548 * and silently restarts from byte 0 when they no longer match.
549 *
550 * A fresh parse comes back as `update` for the caller to cache, with the
551 * entry it was built from. Reads run concurrently, and the caller stores
552 * updates in walk order rather than completion order: saved records of
553 * deleted transcripts aggregate in cache order, where the first copy of a
554 * duplicate wins.
555 */
556 const readFileRecords = (
557 filePath: string,
558 size: number,
559 mtimeMs: number,
560 provider: UsageProviderKind,
561 format: TranscriptUsageFormat<unknown>,
562 ): Effect.Effect<{
563 readonly records: readonly UsageRecord[];
564 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
565 }> =>
566 Effect.gen(function* () {
567 const cached = fileCache.get(filePath);
568 // Provider is part of the identity: if both providers were ever pointed
569 // at one directory, a hit parsed by the other parser must not be reused.
570 if (
571 cached &&
572 cached.size === size &&
573 cached.mtimeMs === mtimeMs &&
574 cached.provider === provider
575 ) {
576 return {
577 records:
578 cached.tailRecords.length === 0
579 ? cached.records
580 : [...cached.records, ...cached.tailRecords],
581 };
582 }
583​
584 // Only a strictly grown file may resume. Same size with a new mtime, or
585 // a shrunken file, means rewritten content; re-parse it whole.
586 const resumeFrom =
587 cached !== undefined && cached.provider === provider && size > cached.size
588 ? cached.position
589 : undefined;
590​
591 const parsed = yield* Effect.promise(() =>
592 readTranscriptRecords(filePath, format, resumeFrom),
593 );
594 // A read failure is not an empty transcript: caching it under this
595 // (size, mtime) would silently drop the file's usage until it changes.
596 if (parsed === null)
597 return {
598 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
599 };
600​
601 // Stored already de-duplicated within the file, which is 99% of all
602 // duplicates. The aggregator still runs the cross-file dedupe pass. One
603 // seen set spans the cached base, the new lines, and the tail so a
604 // resumed parse dedupes exactly like a full one.
605 const base = parsed.resumed && cached !== undefined ? cached.records : [];
606 const seen = new Set<string>();
607 const records = dedupeWithinFile([...base, ...parsed.records], seen);
608 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
609​
610 return {
611 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
612 update: {
613 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
614 replaces: cached,
615 },
616 };
617 });
618​
619 /** One provider directory's walk and parse, before rates are involved. */
620 interface ScannedDir {
621 readonly provider: UsageProviderKind;
622 readonly dir: string;
623 readonly volumeId: string;
624 readonly hostId?: string;
625 readonly status?: UsageSource["status"];
626 readonly message?: string;
627 readonly action?: UsageSource["action"];
628 /** Parsed records per file, or `null` when the directory does not exist. */
629 readonly files:
630 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
631 | null;
632 /** Answered from a cache while a refresh runs. */
633 readonly refreshing?: true;
634 }
635​
636 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
637 source: TranscriptSource,
638 windowStartMs: number,
639 ) {
640 const { provider, format, dir, volumeId, fileName } = source;
641 const exists = yield* fileSystem
642 .exists(dir)
643 .pipe(Effect.catchCause(() => Effect.succeed(false)));
644 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
645 const files = yield* Effect.promise(() =>
646 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
647 );
648 // A cold parse waits on disk reads, so a few files in flight read
649 // close to twice as fast. Results keep walk order.
650 const read = yield* Effect.forEach(
651 files,
652 (file) =>
653 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
654 Effect.map((result) => ({ path: file.path, ...result })),
655 ),
656 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
657 );
658 const parsedFiles = read.map(({ path, records, update }) => {
659 if (update === undefined) return { path, records };
660 // A scan of another window may have cached its own read of this file
661 // meanwhile. Then keep whichever read saw the later file, so a slower
662 // scan never replaces newer usage with older.
663 const current = fileCache.get(path);
664 if (
665 current === update.replaces ||
666 current === undefined ||
667 !isLaterRead(current, update.entry)
668 ) {
669 fileCache.set(path, update.entry);
670 cacheDirty = true;
671 }
672 return { path, records };
673 });
674 return { provider, dir, volumeId, files: parsedFiles } satisfies ScannedDir;
675 });
676​
677 /** Fetches what one account cache is missing, then persists it if anything changed. */
678 const refreshCursorAccount = Effect.fn("UsageService.refreshCursorAccount")(function* (
679 credential: CursorCredentialSource,
680 credentialKey: string,
681 retentionStartMs: number,
682 ) {
683 const nowMs = yield* Clock.currentTimeMillis;
684 const fetchMissing = (cache: CursorAccountCache | undefined) => {
685 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
686 return cursorAccountReader
687 .read(credential, range.sinceMs, range.untilMs)
688 .pipe(Effect.map((result) => ({ range, result })));
689 };
690 let base = cursorCaches.get(credentialKey);
691 let fetched = yield* fetchMissing(base);
692 // Another login's history replaces the cached account's, even if reading it fails.
693 if (
694 base !== undefined &&
695 fetched.result.accountKey !== null &&
696 fetched.result.accountKey !== base.accountKey
697 ) {
698 cursorCaches.delete(credentialKey);
699 cursorCacheDirty = true;
700 base = undefined;
701 fetched = yield* fetchMissing(base);
702 }
703 const { range, result } = fetched;
704 if (result.missing || result.error !== null || result.accountKey === null) {
705 cursorFailures.set(credentialKey, {
706 atMs: nowMs,
707 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
708 });
709 yield* schedulePersist;
710 return;
711 }
712 const merged = mergeCursorFetch(
713 base,
714 result.accountKey,
715 range,
716 result.records,
717 nowMs,
718 retentionStartMs,
719 );
720 cursorCaches.set(credentialKey, merged.cache);
721 cursorFailures.delete(credentialKey);
722 // An unchanged edge is not worth rewriting the file for: after a restart
723 // the cache just refetches a slightly wider edge.
724 if (merged.changed) {
725 cursorCacheDirty = true;
726 yield* schedulePersist;
727 }
728 });
729​
730 /** Joins the refresh in flight, or starts one. */
731 const startCursorRefresh = (
732 credential: CursorCredentialSource,
733 credentialKey: string,
734 retentionStartMs: number,
735 ) =>
736 // Enrollment and fork are atomic, so an interrupted caller cannot leave a
737 // registered refresh that nothing will finish.
738 Effect.uninterruptible(
739 Effect.gen(function* () {
740 const current = cursorRefreshes.get(credentialKey);
741 if (current !== undefined) return current;
742 const done = Deferred.makeUnsafe<void>();
743 cursorRefreshes.set(credentialKey, done);
744 // Detached: a departing client must not cancel a fetch later reads reuse.
745 yield* refreshCursorAccount(credential, credentialKey, retentionStartMs).pipe(
746 Effect.catchCause(() =>
747 Clock.currentTimeMillis.pipe(
748 Effect.map((atMs) =>
749 cursorFailures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
750 ),
751 ),
752 ),
753 Effect.ensuring(
754 Effect.suspend(() => {
755 cursorRefreshes.delete(credentialKey);
756 return Deferred.succeed(done, undefined);
757 }),
758 ),
759 Effect.forkDetach,
760 );
761 return done;
762 }),
763 );
764​
765 /**
766 * The Cursor account source. A cache inside its TTL, or a refresh that failed
767 * inside it, answers directly. Otherwise a refresh starts: `awaitRefresh`
768 * waits for it, and anything else answers from the cache marked `refreshing`.
769 */
770 const cursorAccountSource = Effect.fn("UsageService.cursorAccountSource")(function* (
771 credential: CursorCredentialSource,
772 authPath: string,
773 windowStartMs: number,
774 retentionStartMs: number,
775 awaitRefresh: boolean,
776 ) {
777 // No saved login means there is no account source to report, not a setup error.
778 if (
779 typeof credential === "string" &&
780 !(yield* fileSystem.exists(credential).pipe(Effect.orElseSucceed(() => true)))
781 ) {
782 return null;
783 }
784 const credentialKey = typeof credential === "string" ? credential : "keychain";
785 const nowMs = yield* Clock.currentTimeMillis;
786 const recentFailure = cursorFailures.get(credentialKey);
787 let refreshing = false;
788 if (
789 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
790 !isCursorCacheFresh(cursorCaches.get(credentialKey), nowMs)
791 ) {
792 const refresh = yield* startCursorRefresh(credential, credentialKey, retentionStartMs);
793 if (awaitRefresh) yield* Deferred.await(refresh);
794 else refreshing = true;
795 }
796​
797 const cache = cursorCaches.get(credentialKey);
798 const failure = refreshing ? undefined : cursorFailures.get(credentialKey);
799 const failureMessage = failure === undefined ? undefined : failure.error;
800 if (failureMessage === null) return null;
801 if (cache === undefined) {
802 return {
803 provider: "cursor",
804 dir: authPath,
805 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(authPath)),
806 // Never combine a local fallback with another server's account-wide history.
807 ...(refreshing
808 ? { files: [], refreshing: true }
809 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
810 } satisfies ScannedDir;
811 }
812 // The same account includes CLI and desktop history from every machine.
813 // A stable remote fingerprint prevents connected environments counting it twice.
814 const source = `cursor-account:${cache.accountKey}`;
815 return {
816 provider: "cursor",
817 dir: source,
818 hostId: "cursor.com",
819 volumeId: cache.accountKey,
820 files: [
821 {
822 path: source,
823 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
824 },
825 ],
826 ...(failureMessage === undefined
827 ? { status: "ok" }
828 : { status: "partial", message: failureMessage }),
829 ...(refreshing ? { refreshing: true } : {}),
830 } satisfies ScannedDir;
831 });
832​
833 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
834 windowStartMs: number,
835 settings: ServerSettingsValue,
836 retentionCutoffMs: number,
837 awaitRefresh: boolean,
838 ) {
839 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
840 Effect.provideContext(readerContext),
841 );
842​
843 const home = NodeOS.homedir();
844 const envRoots = Effect.fnUntraced(function* (key: string, defaults: readonly string[]) {
845 const roots = hostEnvironment[key]
846 ?.split(",")
847 .map((value) => value.trim())
848 .filter(Boolean);
849 const canonical = new Set<string>();
850 for (const root of roots?.length ? roots : defaults) {
851 const resolved = path.resolve(expandHomePath(root));
852 canonical.add(
853 yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),
854 );
855 }
856 return [...canonical];
857 });
858​
859 const scans = Effect.forEach(
860 scanReaders,
861 ({ driver, reader }) =>
862 reader
863 .scan({
864 instances: usageInstances(driver, settings),
865 windowStartMs,
866 retentionCutoffMs,
867 awaitRefresh,
868 })
869 .pipe(
870 Effect.flatMap((sources) =>
871 Effect.forEach(sources, ({ volumeId, ...source }) =>
872 Effect.map(
873 volumeId === undefined
874 ? Effect.promise(() => readDirectoryVolumeId(source.dir))
875 : Effect.succeed(volumeId),
876 (resolved): ScannedDir => ({
877 ...source,
878 provider: reader.provider,
879 volumeId: resolved,
880 }),
881 ),
882 ),
883 ),
884 Effect.provideContext(readerContext),
885 ),
886 { concurrency: "unbounded" },
887 ).pipe(Effect.map((sources) => sources.flat()));
888​
889 const antigravity = Effect.gen(function* () {
890 const antigravityRoots = yield* envRoots("ANTIGRAVITY_DATA_DIR", [
891 ...["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"].map((name) =>
892 path.join(home, ".gemini", name),
893 ),
894 path.join(home, ".config", "antigravity"),
895 ]);
896 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
897 if (instance.driver === "antigravity") {
898 const directories = yield* resolveAntigravityInstanceDirectories(
899 config.stateDir,
900 ProviderInstanceId.make(instanceId),
901 ).pipe(
902 Effect.provideService(Crypto.Crypto, crypto),
903 Effect.provideService(Path.Path, path),
904 Effect.mapError(
905 (cause) =>
906 new UsageReadError({
907 reason: "scanFailed",
908 detail: "Antigravity profile directory could not be resolved.",
909 cause,
910 }),
911 ),
912 );
913 antigravityRoots.push(path.join(directories.profile, "antigravity-acp"));
914 }
915 }
916 const antigravityDirs = new Set<string>();
917 for (const root of antigravityRoots) {
918 const resolvedRoot = yield* fileSystem
919 .realPath(root)
920 .pipe(Effect.orElseSucceed(() => root));
921 const nested = path.join(resolvedRoot, "conversations");
922 const dir = (yield* fileSystem
923 .exists(nested)
924 .pipe(Effect.catchCause(() => Effect.succeed(false))))
925 ? nested
926 : resolvedRoot;
927 antigravityDirs.add(yield* fileSystem.realPath(dir).pipe(Effect.orElseSucceed(() => dir)));
928 }
929 const result = yield* Effect.promise(() =>
930 readAntigravityUsage([...antigravityDirs], windowStartMs, antigravityCache),
931 );
932 const scanned: ScannedDir[] = [];
933 for (const dir of antigravityDirs) {
934 const exists = yield* fileSystem
935 .exists(dir)
936 .pipe(Effect.catchCause(() => Effect.succeed(false)));
937 const failed = result.errors.some(
938 (error) => error === dir || error.startsWith(`${dir}${path.sep}`),
939 );
940 scanned.push({
941 provider: "antigravity",
942 dir,
943 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
944 files: !exists && !failed ? null : result.files.filter((file) => file.root === dir),
945 status: failed ? "partial" : "ok",
946 ...(failed ? { message: "Some Antigravity history could not be read." } : {}),
947 });
948 }
949 return scanned;
950 });
951​
952 const cursor = Effect.gen(function* () {
953 const cursorUserHome =
954 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
955 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
956 const cursorHome =
957 platform === "darwin"
958 ? path.join(cursorUserHome, "Library", "Application Support")
959 : platform === "win32"
960 ? hostEnvironment["APPDATA"] || path.join(cursorUserHome, "AppData", "Roaming")
961 : configHome && path.isAbsolute(configHome)
962 ? configHome
963 : path.join(cursorUserHome, ".config");
964 const cursorAuthPath =
965 platform === "darwin"
966 ? path.join(cursorUserHome, ".cursor", "auth.json")
967 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
968 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
969 const loginUnavailable =
970 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
971 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
972 credentialStore === "memory";
973 const useKeychain = platform === "darwin" && credentialStore !== "file";
974 if (useKeychain && !loginUnavailable && !settings.cursorKeychainUsageEnabled) {
975 return [
976 {
977 provider: "cursor",
978 dir: cursorAuthPath,
979 volumeId: "",
980 files: null,
981 message: "Cursor account usage is off on this environment.",
982 action: "enableCursorKeychain",
983 } satisfies ScannedDir,
984 ];
985 }
986 if (loginUnavailable) {
987 return [
988 {
989 provider: "cursor",
990 dir: cursorAuthPath,
991 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(cursorAuthPath)),
992 files: null,
993 message: "Cursor account history needs a Cursor CLI login on this server.",
994 } satisfies ScannedDir,
995 ];
996 }
997 const source = yield* cursorAccountSource(
998 useKeychain ? { kind: "keychain" } : cursorAuthPath,
999 cursorAuthPath,
1000 windowStartMs,
1001 retentionCutoffMs,
1002 awaitRefresh,
1003 );
1004 return source === null ? [] : [source];
1005 });
1006​
1007 // Independent sources scan together. Transcript directories go one at a
1008 // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result
1009 // keeps this order, since aggregation keeps the first copy of a duplicate.
1010 const [transcripts, scanDirs, antigravityDirs, cursorDirs] = yield* Effect.all(
1012 Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)),
1013 scans,
1014 antigravity,
1015 cursor,
1016 ],
1017 { concurrency: "unbounded" },
1018 );
1019 const scanned: readonly ScannedDir[] = [
1020 ...transcripts,
1021 ...scanDirs,
1022 ...antigravityDirs,
1023 ...cursorDirs,
1024 ];
1025 return scanned;
1026 });
1027​
1028 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
1029 input: UsageSummaryInput,
1030 settings: ServerSettingsValue,
1031 ) {
1032 if (input.sinceDay > input.untilDay) {
1033 return yield* new UsageReadError({
1034 reason: "invalidWindow",
1035 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
1036 });
1038​
1039 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
1040 if (input.resolution === "hour") {
1041 const sinceTime =
1042 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
1043 const untilTime =
1044 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
1045 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
1046 return yield* new UsageReadError({
1047 reason: "invalidWindow",
1048 detail: "Hourly usage requires valid sinceTime and untilTime instants",
1049 });
1051 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
1052 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
1053 const durationMs = untilTimeMs - sinceTimeMs;
1054 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
1055 return yield* new UsageReadError({
1056 reason: "invalidWindow",
1057 detail: "Hourly usage window must be greater than zero and at most 24 hours",
1058 });
1060 hourlyWindow = { sinceTimeMs, untilTimeMs };
1062​
1063 const startedAtMs = yield* Clock.currentTimeMillis;
1064 yield* ensureScanCacheLoaded;
1065​
1066 const hostId = NodeOS.hostname();
1067 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
1068 if (Option.isNone(windowStart)) {
1069 return yield* new UsageReadError({
1070 reason: "invalidWindow",
1071 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
1072 });
1074 const windowStartMs =
1075 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
1076​
1077 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
1078​
1079 // Pricing only matters once records are aggregated, so the rate table
1080 // loads while transcripts stream instead of gating them: a cold rates
1081 // fetch on a slow network no longer delays the scan by its own timeout.
1082 const [, scannedDirs] = yield* Effect.all(
1084 ensureRates(false),
1085 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
1086 ],
1087 { concurrency: 2 },
1088 );
1089​
1090 const aggregator = new UsageAggregator({
1091 timeZone: input.timeZone,
1092 sinceDay: input.sinceDay,
1093 untilDay: input.untilDay,
1094 resolution: input.resolution ?? "day",
1095 ...hourlyWindow,
1096 rates,
1097 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
1098 modelAliases: resolveModelAliases(settings.usageModelAliases),
1099 });
1100​
1101 const sources: UsageSource[] = [];
1102​
1103 // Cleanup may remove transcripts, but the usage we already saved still
1104 // contributes to its source through the normal aggregation and dedupe
1105 // path. Like the walk, skip files last written before the window: they
1106 // cannot hold records inside it.
1107 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
1108 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
1109 const retainedFiles = [...(files ?? [])];
1110 const livePaths = new Set(retainedFiles.map((file) => file.path));
1111 for (const [filePath, entry] of fileCache) {
1112 if (
1113 entry.provider !== provider ||
1114 entry.mtimeMs < retainedSinceMs ||
1115 livePaths.has(filePath) ||
1116 !isWithinDirectory(filePath, dir)
1118 continue;
1119 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
1121 return retainedFiles;
1122 });
1123 const crossFileSessions = sharedSessions(filesByDir.flat());
1124​
1125 for (const [
1126 index,
1127 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
1128 ] of scannedDirs.entries()) {
1129 let scannedFiles = 0;
1130 let skippedFiles = 0;
1131 // Distinct per directory. Buckets carry per-cell session counts, but a
1132 // session spans days and models, so clients total this figure instead.
1133 const sessionIds = new Set<string>();
1134​
1135 for (const file of filesByDir[index] ?? []) {
1136 if (file.records.length === 0) {
1137 skippedFiles += 1;
1138 continue;
1140 scannedFiles += 1;
1141 const eventOccurrences = new Map<string, number>();
1142 for (const record of file.records) {
1143 let usageRecord = record;
1144 if (
1145 sharedSessionProviders.has(record.provider) &&
1146 crossFileSessions.has(record.sessionId)
1147 ) {
1148 // Match moved copies without collapsing repeated equal events
1149 // within one file (timestamps can have only second precision).
1150 // Only sessions seen in several files can have a copy to match.
1151 const key = encodeUsageRecordKey([
1152 record.provider,
1153 record.sessionId,
1154 record.timestampMs,
1155 record.model,
1156 record.totals,
1157 ]);
1158 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
1159 eventOccurrences.set(key, occurrence);
1160 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
1162 // Only sessions contributing in-window count; the mtime slack can
1163 // admit boundary files whose records fall outside the range.
1164 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
1165 sessionIds.add(record.sessionId);
1169​
1170 sources.push({
1171 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
1172 // Clients exclude missing sources, so saved records remain an available source.
1173 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
1174 scannedFiles,
1175 skippedFiles,
1176 malformedRecords: 0,
1177 distinctSessions: sessionIds.size,
1178 message:
1179 message ?? (files === null ? "No transcript directory on this environment." : null),
1180 ...(action ? { action } : {}),
1181 ...(refreshing ? { refreshing } : {}),
1182 });
1184​
1185 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
1186 if (pruned > 0) cacheDirty = true;
1187​
1188 const aggregated = aggregator.finish();
1189 const readAt = yield* DateTime.now;
1190 const finishedAtMs = yield* Clock.currentTimeMillis;
1191​
1192 return {
1193 contractVersion: USAGE_CONTRACT_VERSION,
1194 readAt: DateTime.formatIso(readAt),
1195 timeZone: input.timeZone,
1196 sinceDay: input.sinceDay,
1197 untilDay: input.untilDay,
1198 buckets: aggregated.buckets,
1199 sources,
1200 pricing: pricing(),
1201 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
1202 } satisfies UsageSummary;
1203 });
1204​
1205 /**
1206 * In-flight scans by window and usage settings, so concurrent identical requests (the usage
1207 * page open on two clients at once) share one scan instead of racing over
1208 * the same corpus twice.
1209 */
1210 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
1211​
1212 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
1213 JSON.stringify([
1214 input.timeZone,
1215 input.sinceDay,
1216 input.untilDay,
1217 input.resolution ?? "day",
1218 input.sinceTime ?? null,
1219 input.untilTime ?? null,
1220 settings.usagePriceOverrides,
1221 settings.usageModelAliases,
1222 settings.cursorKeychainUsageEnabled,
1223 // A waiting read must never share a scan that answers with `refreshing`.
1224 input.awaitRefresh === true,
1225 ]);
1226​
1227 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
1228 const settings = yield* readSettings;
1229 const key = scanKey(input, settings);
1230 const deferred = yield* Effect.uninterruptible(
1231 Effect.gen(function* () {
1232 const existing = inflightScans.get(key);
1233 if (existing !== undefined) return existing;
1234​
1235 // Enrollment and detached-fiber creation must be atomic. Otherwise a
1236 // canceled first caller can leave a Deferred with no scan to finish it.
1237 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
1238 inflightScans.set(key, created);
1239 // Detached so one departing client cannot tear the scan out from under
1240 // the fibers awaiting it; a finished scan warms the cache either way.
1241 // The cache write is registered before the waiters resume, so they
1242 // can await it, but its fiber starts after they have the summary.
1243 yield* scanSummary(input, settings).pipe(
1244 Effect.onExit((exit) =>
1245 Effect.sync(() => inflightScans.delete(key)).pipe(
1246 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
1247 Effect.andThen(Deferred.done(created, exit)),
1248 ),
1249 ),
1250 Effect.forkDetach,
1251 );
1252 return created;
1253 }),
1254 );
1255 // Waiting stays interruptible. The detached scan continues for other
1256 // callers and still warms the cache if this caller leaves.
1257 return yield* Deferred.await(deferred);
1258 });
1259​
1260 // `awaitPersisted` is outside the service interface: tests use it to restart
1261 // against what a previous instance wrote.
1262 return { readSummary, refreshRates, awaitPersisted } as const;
1263});
1264​
1265export const layer = Layer.effect(UsageService, make);