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

UsageService.ts

1,242 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 "@t3tools/shared/atomicWrite";
56import * as ServerConfig from "../config.ts";
57import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
58import * as ServerSettings from "../serverSettings.ts";
59import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
60import { resolveAntigravityInstanceDirectories } from "../provider/antigravityAuthSupport.ts";
61import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
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. An unconfigured default slot
355 // runs with default config, just as it does 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({ instanceId: ProviderInstanceId.make(driver) });
363 }
364 for (const instance of instances) {
365 const environment = mergeProviderInstanceEnvironment(instance.environment, hostEnvironment);
366 const provider = driver === "claudeAgent" ? "claude" : driver;
367 let home: string;
368 if (driver === "codex") {
369 const decoded = decodeCodexSettings(instance.config ?? {});
370 if (Option.isNone(decoded)) continue;
371 const codexConfig = decoded.value;
372 const environmentHome = environment.CODEX_HOME?.trim();
373 const layout = yield* resolveCodexHomeLayout(
374 codexConfig.setupMode !== "managed" &&
375 !codexConfig.homePath.trim() &&
376 !codexConfig.shadowHomePath.trim() &&
377 environmentHome
378 ? { ...codexConfig, homePath: environmentHome }
379 : codexConfig,
380 );
381 home = layout.sharedHomePath;
382 } else if (driver === "claudeAgent") {
383 const decoded = decodeClaudeSettings(instance.config ?? {});
384 if (Option.isNone(decoded)) continue;
385 const configured = decoded.value.homePath.trim();
386 home = configured
387 ? expandHomePath(configured)
388 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
389 } else {
390 home = expandHomePath(
391 environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
392 );
393 }
394 const directory = path.resolve(home, provider === "claude" ? "projects" : "sessions");
395 const sourceKey = provider + "\0" + directory;
396 const previous = sourceCache.get(sourceKey);
397 // Keep canonical paths and source fingerprints stable after root cleanup,
398 // including aliases and clients merging pre-cleanup environment summaries.
399 const dir = yield* fileSystem
400 .realPath(directory)
401 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
402 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
403 const hasRetainedHistory = fileCache
404 .entries()
405 .some(
406 ([filePath, entry]) =>
407 entry.provider === provider &&
408 entry.mtimeMs >= retentionCutoffMs &&
409 entry.records.length + entry.tailRecords.length > 0 &&
410 isWithinDirectory(filePath, dir),
411 );
412 // A recreated directory still reports the retained history under its old identity.
413 const volumeId =
414 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
415 ? previous.volumeId || currentVolumeId
416 : currentVolumeId;
417 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
418 sourceCache.set(sourceKey, { dir, volumeId });
419 cacheDirty = true;
420 }
421 const key = `${provider}\0${dir}`;
422 if (seen.has(key)) continue;
423 seen.add(key);
424 dirs.push({
425 provider,
426 dir,
427 volumeId,
428 ...(provider === "grok" ? { fileName: "updates.jsonl" } : {}),
429 });
430 }
431 }
432 return dirs;
433 });
434​
435 /**
436 * Loads the persisted scan and Cursor account caches exactly once per process.
437 *
438 * `Effect.cached` makes concurrent first readers await the same load rather
439 * than each seeing a "loaded" flag set before the read finished and cold
440 * scanning against an empty cache.
441 */
442 const ensureScanCacheLoaded = yield* Effect.cached(
443 Effect.gen(function* () {
444 const readDocument = (filePath: string) =>
445 fileSystem.readFileString(filePath).pipe(
446 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
447 Effect.catchCause(() => Effect.succeed(null)),
448 );
449 for (const [key, cache] of decodeCursorAccountCaches(yield* readDocument(cursorCachePath))) {
450 cursorCaches.set(key, cache);
451 }
452 let document = yield* readDocument(scanCachePath);
453 if (document === null) {
454 document = yield* readDocument(legacyScanCachePath);
455 // Write the migrated cache to its own file on the next scan.
456 cacheDirty = document !== null;
457 }
458 if (document === null) return;
459 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
460 const sources = decodeCachedSources(document);
461 if (Option.isSome(sources)) {
462 for (const [key, source] of Object.entries(sources.value.sources))
463 sourceCache.set(key, source);
464 }
465 }),
466 );
467​
468 const writeScanCache = makeScanCacheWriter();
469 // Scans with different windows can finish together; serializing the writes
470 // keeps an older snapshot from landing after a newer one.
471 const persistLock = yield* Semaphore.make(1);
472​
473 // Each dirty flag is cleared before encoding, so a change while the write is
474 // in flight marks it dirty again. A failed write restores the flag, so the
475 // next persist retries instead of leaving disk stale. A cache we cannot
476 // write is a slower next start, not a failed read.
477 const persistCaches = Effect.gen(function* () {
478 if (cacheDirty) {
479 cacheDirty = false;
480 yield* Effect.sync(() =>
481 writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
482 ).pipe(
483 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
484 Effect.catchCause(() =>
485 Effect.sync(() => {
486 cacheDirty = true;
487 }),
488 ),
489 );
490 }
491 if (cursorCacheDirty) {
492 cursorCacheDirty = false;
493 yield* Effect.sync(() => encodeCursorAccountCaches(cursorCaches)).pipe(
494 Effect.flatMap((contents) => writeCacheFile(cursorCachePath, contents)),
495 Effect.catchCause(() =>
496 Effect.sync(() => {
497 cursorCacheDirty = true;
498 }),
499 ),
500 );
501 }
502 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
503​
504 const pendingPersists = new Set<Fiber.Fiber<void>>();
505 /** Writes dirty caches in the background, after the summary that dirtied them answers. */
506 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
507 Effect.map((fiber) => {
508 pendingPersists.add(fiber);
509 fiber.addObserver(() => pendingPersists.delete(fiber));
510 }),
511 );
512 /** Waits for every write scheduled so far, as a restart would need. */
513 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
514 Effect.asVoid,
515 );
516 // A write still running when the service shuts down finishes first, so the
517 // next start does not lose the last scan.
518 yield* Effect.addFinalizer(() => awaitPersisted);
519​
520 /**
521 * Parses one transcript, reusing the cached result when it is unchanged.
522 *
523 * A file that only grew re-parses from the cached position, so an actively
524 * written multi-hundred-megabyte rollout costs its appended bytes per scan
525 * rather than a full re-read. The reader verifies the position's guard bytes
526 * and silently restarts from byte 0 when they no longer match.
527 *
528 * A fresh parse comes back as `update` for the caller to cache, with the
529 * entry it was built from. Reads run concurrently, and the caller stores
530 * updates in walk order rather than completion order: saved records of
531 * deleted transcripts aggregate in cache order, where the first copy of a
532 * duplicate wins.
533 */
534 const readFileRecords = (
535 filePath: string,
536 size: number,
537 mtimeMs: number,
538 provider: UsageProviderKind,
539 ): Effect.Effect<{
540 readonly records: readonly UsageRecord[];
541 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
542 }> =>
543 Effect.gen(function* () {
544 const cached = fileCache.get(filePath);
545 // Provider is part of the identity: if both providers were ever pointed
546 // at one directory, a hit parsed by the other parser must not be reused.
547 if (
548 cached &&
549 cached.size === size &&
550 cached.mtimeMs === mtimeMs &&
551 cached.provider === provider
552 ) {
553 return {
554 records:
555 cached.tailRecords.length === 0
556 ? cached.records
557 : [...cached.records, ...cached.tailRecords],
558 };
559 }
560​
561 // Only a strictly grown file may resume. Same size with a new mtime, or
562 // a shrunken file, means rewritten content; re-parse it whole.
563 const resumeFrom =
564 cached !== undefined && cached.provider === provider && size > cached.size
565 ? cached.position
566 : undefined;
567​
568 const parsed = yield* Effect.promise(() =>
569 readTranscriptRecords(filePath, provider, resumeFrom),
570 );
571 // A read failure is not an empty transcript: caching it under this
572 // (size, mtime) would silently drop the file's usage until it changes.
573 if (parsed === null)
574 return {
575 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
576 };
577​
578 // Stored already de-duplicated within the file, which is 99% of all
579 // duplicates. The aggregator still runs the cross-file dedupe pass. One
580 // seen set spans the cached base, the new lines, and the tail so a
581 // resumed parse dedupes exactly like a full one.
582 const base = parsed.resumed && cached !== undefined ? cached.records : [];
583 const seen = new Set<string>();
584 const records = dedupeWithinFile([...base, ...parsed.records], seen);
585 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
586​
587 return {
588 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
589 update: {
590 entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position },
591 replaces: cached,
592 },
593 };
594 });
595​
596 /** One provider directory's walk and parse, before rates are involved. */
597 interface ScannedDir {
598 readonly provider: UsageProviderKind;
599 readonly dir: string;
600 readonly volumeId: string;
601 readonly hostId?: string;
602 readonly status?: UsageSource["status"];
603 readonly message?: string;
604 readonly action?: UsageSource["action"];
605 /** Parsed records per file, or `null` when the directory does not exist. */
606 readonly files:
607 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
608 | null;
609 /** Answered from a cache while a refresh runs. */
610 readonly refreshing?: true;
611 }
612​
613 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
614 source: {
615 readonly provider: UsageProviderKind;
616 readonly dir: string;
617 readonly volumeId: string;
618 readonly fileName?: string;
619 },
620 windowStartMs: number,
621 ) {
622 const { provider, dir, volumeId, fileName } = source;
623 const exists = yield* fileSystem
624 .exists(dir)
625 .pipe(Effect.catchCause(() => Effect.succeed(false)));
626 if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir;
627 const files = yield* Effect.promise(() =>
628 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
629 );
630 // A cold parse waits on disk reads, so a few files in flight read
631 // close to twice as fast. Results keep walk order.
632 const read = yield* Effect.forEach(
633 files,
634 (file) =>
635 readFileRecords(file.path, file.size, file.mtimeMs, provider).pipe(
636 Effect.map((result) => ({ path: file.path, ...result })),
637 ),
638 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
639 );
640 const parsedFiles = read.map(({ path, records, update }) => {
641 if (update === undefined) return { path, records };
642 // A scan of another window may have cached its own read of this file
643 // meanwhile. Then keep whichever read saw the later file, so a slower
644 // scan never replaces newer usage with older.
645 const current = fileCache.get(path);
646 if (
647 current === update.replaces ||
648 current === undefined ||
649 !isLaterRead(current, update.entry)
650 ) {
651 fileCache.set(path, update.entry);
652 cacheDirty = true;
653 }
654 return { path, records };
655 });
656 return { provider, dir, volumeId, files: parsedFiles } satisfies ScannedDir;
657 });
658​
659 /** Fetches what one account cache is missing, then persists it if anything changed. */
660 const refreshCursorAccount = Effect.fn("UsageService.refreshCursorAccount")(function* (
661 credential: CursorCredentialSource,
662 credentialKey: string,
663 retentionStartMs: number,
664 ) {
665 const nowMs = yield* Clock.currentTimeMillis;
666 const fetchMissing = (cache: CursorAccountCache | undefined) => {
667 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
668 return cursorAccountReader
669 .read(credential, range.sinceMs, range.untilMs)
670 .pipe(Effect.map((result) => ({ range, result })));
671 };
672 let base = cursorCaches.get(credentialKey);
673 let fetched = yield* fetchMissing(base);
674 // Another login's history replaces the cached account's, even if reading it fails.
675 if (
676 base !== undefined &&
677 fetched.result.accountKey !== null &&
678 fetched.result.accountKey !== base.accountKey
679 ) {
680 cursorCaches.delete(credentialKey);
681 cursorCacheDirty = true;
682 base = undefined;
683 fetched = yield* fetchMissing(base);
684 }
685 const { range, result } = fetched;
686 if (result.missing || result.error !== null || result.accountKey === null) {
687 cursorFailures.set(credentialKey, {
688 atMs: nowMs,
689 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
690 });
691 yield* schedulePersist;
692 return;
693 }
694 const merged = mergeCursorFetch(
695 base,
696 result.accountKey,
697 range,
698 result.records,
699 nowMs,
700 retentionStartMs,
701 );
702 cursorCaches.set(credentialKey, merged.cache);
703 cursorFailures.delete(credentialKey);
704 // An unchanged edge is not worth rewriting the file for: after a restart
705 // the cache just refetches a slightly wider edge.
706 if (merged.changed) {
707 cursorCacheDirty = true;
708 yield* schedulePersist;
709 }
710 });
711​
712 /** Joins the refresh in flight, or starts one. */
713 const startCursorRefresh = (
714 credential: CursorCredentialSource,
715 credentialKey: string,
716 retentionStartMs: number,
717 ) =>
718 // Enrollment and fork are atomic, so an interrupted caller cannot leave a
719 // registered refresh that nothing will finish.
720 Effect.uninterruptible(
721 Effect.gen(function* () {
722 const current = cursorRefreshes.get(credentialKey);
723 if (current !== undefined) return current;
724 const done = Deferred.makeUnsafe<void>();
725 cursorRefreshes.set(credentialKey, done);
726 // Detached: a departing client must not cancel a fetch later reads reuse.
727 yield* refreshCursorAccount(credential, credentialKey, retentionStartMs).pipe(
728 Effect.catchCause(() =>
729 Clock.currentTimeMillis.pipe(
730 Effect.map((atMs) =>
731 cursorFailures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
732 ),
733 ),
734 ),
735 Effect.ensuring(
736 Effect.suspend(() => {
737 cursorRefreshes.delete(credentialKey);
738 return Deferred.succeed(done, undefined);
739 }),
740 ),
741 Effect.forkDetach,
742 );
743 return done;
744 }),
745 );
746​
747 /**
748 * The Cursor account source. A cache inside its TTL, or a refresh that failed
749 * inside it, answers directly. Otherwise a refresh starts: `awaitRefresh`
750 * waits for it, and anything else answers from the cache marked `refreshing`.
751 */
752 const cursorAccountSource = Effect.fn("UsageService.cursorAccountSource")(function* (
753 credential: CursorCredentialSource,
754 authPath: string,
755 windowStartMs: number,
756 retentionStartMs: number,
757 awaitRefresh: boolean,
758 ) {
759 // No saved login means there is no account source to report, not a setup error.
760 if (
761 typeof credential === "string" &&
762 !(yield* fileSystem.exists(credential).pipe(Effect.orElseSucceed(() => true)))
763 ) {
764 return null;
765 }
766 const credentialKey = typeof credential === "string" ? credential : "keychain";
767 const nowMs = yield* Clock.currentTimeMillis;
768 const recentFailure = cursorFailures.get(credentialKey);
769 let refreshing = false;
770 if (
771 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
772 !isCursorCacheFresh(cursorCaches.get(credentialKey), nowMs)
773 ) {
774 const refresh = yield* startCursorRefresh(credential, credentialKey, retentionStartMs);
775 if (awaitRefresh) yield* Deferred.await(refresh);
776 else refreshing = true;
777 }
778​
779 const cache = cursorCaches.get(credentialKey);
780 const failure = refreshing ? undefined : cursorFailures.get(credentialKey);
781 const failureMessage = failure === undefined ? undefined : failure.error;
782 if (failureMessage === null) return null;
783 if (cache === undefined) {
784 return {
785 provider: "cursor",
786 dir: authPath,
787 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(authPath)),
788 // Never combine a local fallback with another server's account-wide history.
789 ...(refreshing
790 ? { files: [], refreshing: true }
791 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
792 } satisfies ScannedDir;
793 }
794 // The same account includes CLI and desktop history from every machine.
795 // A stable remote fingerprint prevents connected environments counting it twice.
796 const source = `cursor-account:${cache.accountKey}`;
797 return {
798 provider: "cursor",
799 dir: source,
800 hostId: "cursor.com",
801 volumeId: cache.accountKey,
802 files: [
803 {
804 path: source,
805 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
806 },
807 ],
808 ...(failureMessage === undefined
809 ? { status: "ok" }
810 : { status: "partial", message: failureMessage }),
811 ...(refreshing ? { refreshing: true } : {}),
812 } satisfies ScannedDir;
813 });
814​
815 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
816 windowStartMs: number,
817 settings: ServerSettingsValue,
818 retentionCutoffMs: number,
819 awaitRefresh: boolean,
820 ) {
821 // The home resolvers ask for `Path` themselves; satisfy them from the
822 // instance we already hold so the scan stays context-free.
823 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
824 Effect.provideService(Path.Path, path),
825 );
826​
827 const home = NodeOS.homedir();
828 const envRoots = Effect.fnUntraced(function* (key: string, defaults: readonly string[]) {
829 const roots = hostEnvironment[key]
830 ?.split(",")
831 .map((value) => value.trim())
832 .filter(Boolean);
833 const canonical = new Set<string>();
834 for (const root of roots?.length ? roots : defaults) {
835 const resolved = path.resolve(expandHomePath(root));
836 canonical.add(
837 yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),
838 );
839 }
840 return [...canonical];
841 });
842 const dataHome = hostEnvironment["XDG_DATA_HOME"]?.trim();
843​
844 const openCode = Effect.gen(function* () {
845 const roots = yield* envRoots("OPENCODE_DATA_DIR", [
846 path.join(
847 dataHome && path.isAbsolute(dataHome) ? dataHome : path.join(home, ".local", "share"),
848 "opencode",
849 ),
850 ]);
851 return yield* Effect.forEach(
852 roots,
853 (dir) =>
854 Effect.gen(function* () {
855 const result = yield* Effect.promise(() => readOpenCodeUsage(dir, windowStartMs));
856 return {
857 provider: "opencode",
858 dir,
859 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
860 files: result.missing && !result.error ? null : result.files,
861 status: result.error ? "partial" : "ok",
862 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
863 } satisfies ScannedDir;
864 }),
865 { concurrency: "unbounded" },
866 );
867 });
868​
869 const antigravity = Effect.gen(function* () {
870 const antigravityRoots = yield* envRoots("ANTIGRAVITY_DATA_DIR", [
871 ...["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"].map((name) =>
872 path.join(home, ".gemini", name),
873 ),
874 path.join(home, ".config", "antigravity"),
875 ]);
876 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
877 if (instance.driver === "antigravity") {
878 const directories = yield* resolveAntigravityInstanceDirectories(
879 config.stateDir,
880 ProviderInstanceId.make(instanceId),
881 ).pipe(
882 Effect.provideService(Crypto.Crypto, crypto),
883 Effect.provideService(Path.Path, path),
884 Effect.mapError(
885 (cause) =>
886 new UsageReadError({
887 reason: "scanFailed",
888 detail: "Antigravity profile directory could not be resolved.",
889 cause,
890 }),
891 ),
892 );
893 antigravityRoots.push(path.join(directories.profile, "antigravity-acp"));
894 }
895 }
896 const antigravityDirs = new Set<string>();
897 for (const root of antigravityRoots) {
898 const resolvedRoot = yield* fileSystem
899 .realPath(root)
900 .pipe(Effect.orElseSucceed(() => root));
901 const nested = path.join(resolvedRoot, "conversations");
902 const dir = (yield* fileSystem
903 .exists(nested)
904 .pipe(Effect.catchCause(() => Effect.succeed(false))))
905 ? nested
906 : resolvedRoot;
907 antigravityDirs.add(yield* fileSystem.realPath(dir).pipe(Effect.orElseSucceed(() => dir)));
908 }
909 const result = yield* Effect.promise(() =>
910 readAntigravityUsage([...antigravityDirs], windowStartMs, antigravityCache),
911 );
912 const scanned: ScannedDir[] = [];
913 for (const dir of antigravityDirs) {
914 const exists = yield* fileSystem
915 .exists(dir)
916 .pipe(Effect.catchCause(() => Effect.succeed(false)));
917 const failed = result.errors.some(
918 (error) => error === dir || error.startsWith(`${dir}${path.sep}`),
919 );
920 scanned.push({
921 provider: "antigravity",
922 dir,
923 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
924 files: !exists && !failed ? null : result.files.filter((file) => file.root === dir),
925 status: failed ? "partial" : "ok",
926 ...(failed ? { message: "Some Antigravity history could not be read." } : {}),
927 });
928 }
929 return scanned;
930 });
931​
932 const cursor = Effect.gen(function* () {
933 const cursorUserHome =
934 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
935 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
936 const cursorHome =
937 platform === "darwin"
938 ? path.join(cursorUserHome, "Library", "Application Support")
939 : platform === "win32"
940 ? hostEnvironment["APPDATA"] || path.join(cursorUserHome, "AppData", "Roaming")
941 : configHome && path.isAbsolute(configHome)
942 ? configHome
943 : path.join(cursorUserHome, ".config");
944 const cursorAuthPath =
945 platform === "darwin"
946 ? path.join(cursorUserHome, ".cursor", "auth.json")
947 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
948 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
949 const loginUnavailable =
950 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
951 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
952 credentialStore === "memory";
953 const useKeychain = platform === "darwin" && credentialStore !== "file";
954 if (useKeychain && !loginUnavailable && !settings.cursorKeychainUsageEnabled) {
955 return [
956 {
957 provider: "cursor",
958 dir: cursorAuthPath,
959 volumeId: "",
960 files: null,
961 message: "Cursor account usage is off on this environment.",
962 action: "enableCursorKeychain",
963 } satisfies ScannedDir,
964 ];
965 }
966 if (loginUnavailable) {
967 return [
968 {
969 provider: "cursor",
970 dir: cursorAuthPath,
971 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(cursorAuthPath)),
972 files: null,
973 message: "Cursor account history needs a Cursor CLI login on this server.",
974 } satisfies ScannedDir,
975 ];
976 }
977 const source = yield* cursorAccountSource(
978 useKeychain ? { kind: "keychain" } : cursorAuthPath,
979 cursorAuthPath,
980 windowStartMs,
981 retentionCutoffMs,
982 awaitRefresh,
983 );
984 return source === null ? [] : [source];
985 });
986​
987 // Independent sources scan together. Transcript directories go one at a
988 // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result
989 // keeps this order, since aggregation keeps the first copy of a duplicate.
990 const [transcripts, openCodeDirs, antigravityDirs, cursorDirs] = yield* Effect.all(
991 [
992 Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)),
993 openCode,
994 antigravity,
995 cursor,
996 ],
997 { concurrency: "unbounded" },
998 );
999 const scanned: readonly ScannedDir[] = [
1000 ...transcripts,
1001 ...openCodeDirs,
1002 ...antigravityDirs,
1003 ...cursorDirs,
1004 ];
1005 return scanned;
1006 });
1007​
1008 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
1009 input: UsageSummaryInput,
1010 settings: ServerSettingsValue,
1011 ) {
1012 if (input.sinceDay > input.untilDay) {
1013 return yield* new UsageReadError({
1014 reason: "invalidWindow",
1015 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
1016 });
1018​
1019 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
1020 if (input.resolution === "hour") {
1021 const sinceTime =
1022 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
1023 const untilTime =
1024 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
1025 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
1026 return yield* new UsageReadError({
1027 reason: "invalidWindow",
1028 detail: "Hourly usage requires valid sinceTime and untilTime instants",
1029 });
1031 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
1032 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
1033 const durationMs = untilTimeMs - sinceTimeMs;
1034 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
1035 return yield* new UsageReadError({
1036 reason: "invalidWindow",
1037 detail: "Hourly usage window must be greater than zero and at most 24 hours",
1038 });
1040 hourlyWindow = { sinceTimeMs, untilTimeMs };
1042​
1043 const startedAtMs = yield* Clock.currentTimeMillis;
1044 yield* ensureScanCacheLoaded;
1045​
1046 const hostId = NodeOS.hostname();
1047 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
1048 if (Option.isNone(windowStart)) {
1049 return yield* new UsageReadError({
1050 reason: "invalidWindow",
1051 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
1052 });
1054 const windowStartMs =
1055 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
1056​
1057 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
1058​
1059 // Pricing only matters once records are aggregated, so the rate table
1060 // loads while transcripts stream instead of gating them: a cold rates
1061 // fetch on a slow network no longer delays the scan by its own timeout.
1062 const [, scannedDirs] = yield* Effect.all(
1064 ensureRates(false),
1065 collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true),
1066 ],
1067 { concurrency: 2 },
1068 );
1069​
1070 const aggregator = new UsageAggregator({
1071 timeZone: input.timeZone,
1072 sinceDay: input.sinceDay,
1073 untilDay: input.untilDay,
1074 resolution: input.resolution ?? "day",
1075 ...hourlyWindow,
1076 rates,
1077 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
1078 modelAliases: resolveModelAliases(settings.usageModelAliases),
1079 });
1080​
1081 const sources: UsageSource[] = [];
1082​
1083 // Cleanup may remove transcripts, but the usage we already saved still
1084 // contributes to its source through the normal aggregation and dedupe
1085 // path. Like the walk, skip files last written before the window: they
1086 // cannot hold records inside it.
1087 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
1088 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
1089 const retainedFiles = [...(files ?? [])];
1090 const livePaths = new Set(retainedFiles.map((file) => file.path));
1091 for (const [filePath, entry] of fileCache) {
1092 if (
1093 entry.provider !== provider ||
1094 entry.mtimeMs < retainedSinceMs ||
1095 livePaths.has(filePath) ||
1096 !isWithinDirectory(filePath, dir)
1098 continue;
1099 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
1101 return retainedFiles;
1102 });
1103 const sharedSessions = sharedCodexSessions(filesByDir.flat());
1104​
1105 for (const [
1106 index,
1107 { provider, dir, volumeId, files, status, message, action, refreshing, hostId: sourceHostId },
1108 ] of scannedDirs.entries()) {
1109 let scannedFiles = 0;
1110 let skippedFiles = 0;
1111 // Distinct per directory. Buckets carry per-cell session counts, but a
1112 // session spans days and models, so clients total this figure instead.
1113 const sessionIds = new Set<string>();
1114​
1115 for (const file of filesByDir[index] ?? []) {
1116 if (file.records.length === 0) {
1117 skippedFiles += 1;
1118 continue;
1120 scannedFiles += 1;
1121 const codexEventOccurrences = new Map<string, number>();
1122 for (const record of file.records) {
1123 let usageRecord = record;
1124 if (record.provider === "codex" && sharedSessions.has(record.sessionId)) {
1125 // Match moved rollout copies without collapsing repeated equal events
1126 // within one rollout (timestamps can have only second precision).
1127 // Only sessions seen in several files can have a copy to match.
1128 const key = encodeUsageRecordKey([
1129 record.provider,
1130 record.sessionId,
1131 record.timestampMs,
1132 record.model,
1133 record.totals,
1134 ]);
1135 const occurrence = (codexEventOccurrences.get(key) ?? 0) + 1;
1136 codexEventOccurrences.set(key, occurrence);
1137 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
1139 // Only sessions contributing in-window count; the mtime slack can
1140 // admit boundary files whose records fall outside the range.
1141 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
1142 sessionIds.add(record.sessionId);
1146​
1147 sources.push({
1148 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
1149 // Clients exclude missing sources, so saved records remain an available source.
1150 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
1151 scannedFiles,
1152 skippedFiles,
1153 malformedRecords: 0,
1154 distinctSessions: sessionIds.size,
1155 message:
1156 message ?? (files === null ? "No transcript directory on this environment." : null),
1157 ...(action ? { action } : {}),
1158 ...(refreshing ? { refreshing } : {}),
1159 });
1161​
1162 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
1163 if (pruned > 0) cacheDirty = true;
1164​
1165 const aggregated = aggregator.finish();
1166 const readAt = yield* DateTime.now;
1167 const finishedAtMs = yield* Clock.currentTimeMillis;
1168​
1169 return {
1170 contractVersion: USAGE_CONTRACT_VERSION,
1171 readAt: DateTime.formatIso(readAt),
1172 timeZone: input.timeZone,
1173 sinceDay: input.sinceDay,
1174 untilDay: input.untilDay,
1175 buckets: aggregated.buckets,
1176 sources,
1177 pricing: pricing(),
1178 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
1179 } satisfies UsageSummary;
1180 });
1181​
1182 /**
1183 * In-flight scans by window and usage settings, so concurrent identical requests (the usage
1184 * page open on two clients at once) share one scan instead of racing over
1185 * the same corpus twice.
1186 */
1187 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
1188​
1189 const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string =>
1190 JSON.stringify([
1191 input.timeZone,
1192 input.sinceDay,
1193 input.untilDay,
1194 input.resolution ?? "day",
1195 input.sinceTime ?? null,
1196 input.untilTime ?? null,
1197 settings.usagePriceOverrides,
1198 settings.usageModelAliases,
1199 settings.cursorKeychainUsageEnabled,
1200 // A waiting read must never share a scan that answers with `refreshing`.
1201 input.awaitRefresh === true,
1202 ]);
1203​
1204 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
1205 const settings = yield* readSettings;
1206 const key = scanKey(input, settings);
1207 const deferred = yield* Effect.uninterruptible(
1208 Effect.gen(function* () {
1209 const existing = inflightScans.get(key);
1210 if (existing !== undefined) return existing;
1211​
1212 // Enrollment and detached-fiber creation must be atomic. Otherwise a
1213 // canceled first caller can leave a Deferred with no scan to finish it.
1214 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
1215 inflightScans.set(key, created);
1216 // Detached so one departing client cannot tear the scan out from under
1217 // the fibers awaiting it; a finished scan warms the cache either way.
1218 // The cache write is registered before the waiters resume, so they
1219 // can await it, but its fiber starts after they have the summary.
1220 yield* scanSummary(input, settings).pipe(
1221 Effect.onExit((exit) =>
1222 Effect.sync(() => inflightScans.delete(key)).pipe(
1223 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
1224 Effect.andThen(Deferred.done(created, exit)),
1225 ),
1226 ),
1227 Effect.forkDetach,
1228 );
1229 return created;
1230 }),
1231 );
1232 // Waiting stays interruptible. The detached scan continues for other
1233 // callers and still warms the cache if this caller leaves.
1234 return yield* Deferred.await(deferred);
1235 });
1236​
1237 // `awaitPersisted` is outside the service interface: tests use it to restart
1238 // against what a previous instance wrote.
1239 return { readSummary, refreshRates, awaitPersisted } as const;
1240});
1241​
1242export const layer = Layer.effect(UsageService, make);