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

UsageService.ts

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