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

UsageService.ts

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