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

UsageService.ts

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