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

UsageService.ts

898 lines34.8 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 { 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<
275 Pick<ProviderInstanceConfig, "config" | "environment"> & { instanceId: ProviderInstanceId }
276 > = Object.entries(settings.providerInstances)
277 .filter(([, instance]) => instance.driver === driver)
278 .map(([id, instance]) => ({ ...instance, instanceId: ProviderInstanceId.make(id) }));
279 if (!Object.hasOwn(settings.providerInstances, driver)) {
280 instances.push({
281 config: settings.providers[driver],
282 instanceId: ProviderInstanceId.make(driver),
283 });
284 }
285 for (const instance of instances) {
286 const environment = mergeProviderInstanceEnvironment(instance.environment, hostEnvironment);
287 const provider = driver === "claudeAgent" ? "claude" : driver;
288 let home: string;
289 if (driver === "codex") {
290 const decoded = decodeCodexSettings(instance.config ?? {});
291 if (Option.isNone(decoded)) continue;
292 const codexConfig = decoded.value;
293 const environmentHome = environment.CODEX_HOME?.trim();
294 const layout = yield* resolveCodexHomeLayout(
295 codexConfig.setupMode !== "managed" &&
296 !codexConfig.homePath.trim() &&
297 !codexConfig.shadowHomePath.trim() &&
298 environmentHome
299 ? { ...codexConfig, homePath: environmentHome }
300 : codexConfig,
301 );
302 home = layout.sharedHomePath;
303 } else if (driver === "claudeAgent") {
304 const decoded = decodeClaudeSettings(instance.config ?? {});
305 if (Option.isNone(decoded)) continue;
306 const configured = decoded.value.homePath.trim();
307 home = configured
308 ? expandHomePath(configured)
309 : environment.CLAUDE_CONFIG_DIR?.trim() || path.join(NodeOS.homedir(), ".claude");
310 } else {
311 home = expandHomePath(
312 environment.GROK_HOME?.trim() || path.join(NodeOS.homedir(), ".grok"),
313 );
314 }
315 const directory = path.resolve(home, provider === "claude" ? "projects" : "sessions");
316 const sourceKey = provider + "\0" + directory;
317 const previous = sourceCache.get(sourceKey);
318 // Keep canonical paths and source fingerprints stable after root cleanup,
319 // including aliases and clients merging pre-cleanup environment summaries.
320 const dir = yield* fileSystem
321 .realPath(directory)
322 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
323 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
324 const hasRetainedHistory = fileCache
325 .entries()
326 .some(
327 ([filePath, entry]) =>
328 entry.provider === provider &&
329 entry.mtimeMs >= retentionCutoffMs &&
330 entry.records.length + entry.tailRecords.length > 0 &&
331 isWithinDirectory(filePath, dir),
332 );
333 // A recreated directory still reports the retained history under its old identity.
334 const volumeId =
335 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
336 ? previous.volumeId || currentVolumeId
337 : currentVolumeId;
338 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
339 sourceCache.set(sourceKey, { dir, volumeId });
340 cacheDirty = true;
341 }
342 const key = `${provider}\0${dir}`;
343 if (seen.has(key)) continue;
344 seen.add(key);
345 dirs.push({
346 provider,
347 dir,
348 volumeId,
349 ...(provider === "grok" ? { fileName: "updates.jsonl" } : {}),
350 });
351 }
352 }
353 return dirs;
354 });
355​
356 /**
357 * Loads the persisted scan cache exactly once per process.
358 *
359 * `Effect.cached` makes concurrent first readers await the same load rather
360 * than each seeing a "loaded" flag set before the read finished and cold
361 * scanning against an empty cache.
362 */
363 const ensureScanCacheLoaded = yield* Effect.cached(
364 Effect.gen(function* () {
365 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
366 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
367 Effect.catchCause(() => Effect.succeed(null)),
368 );
369 if (document === null) return;
370 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
371 const sources = decodeCachedSources(document);
372 if (Option.isSome(sources)) {
373 for (const [key, source] of Object.entries(sources.value.sources))
374 sourceCache.set(key, source);
375 }
376 }),
377 );
378​
379 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
380 if (!cacheDirty) return;
381 // Cleared only after the write lands, so a failed persist is retried on
382 // the next scan instead of leaving disk permanently stale.
383 yield* encodeScanCacheFile({
384 ...encodeScanCache(fileCache),
385 sources: Object.fromEntries(sourceCache),
386 }).pipe(
387 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
388 Effect.map(() => {
389 cacheDirty = false;
390 }),
391 // A cache we cannot write is a slower next start, not a failed read.
392 Effect.ignoreCause,
393 );
394 });
395​
396 /**
397 * Parses one transcript, reusing the cached result when it is unchanged.
398 *
399 * A file that only grew re-parses from the cached position, so an actively
400 * written multi-hundred-megabyte rollout costs its appended bytes per scan
401 * rather than a full re-read. The reader verifies the position's guard bytes
402 * and silently restarts from byte 0 when they no longer match.
403 */
404 const readFileRecords = (
405 filePath: string,
406 size: number,
407 mtimeMs: number,
408 provider: UsageProviderKind,
409 ): Effect.Effect<readonly UsageRecord[]> =>
410 Effect.gen(function* () {
411 const cached = fileCache.get(filePath);
412 // Provider is part of the identity: if both providers were ever pointed
413 // at one directory, a hit parsed by the other parser must not be reused.
414 if (
415 cached &&
416 cached.size === size &&
417 cached.mtimeMs === mtimeMs &&
418 cached.provider === provider
419 ) {
420 return cached.tailRecords.length === 0
421 ? cached.records
422 : [...cached.records, ...cached.tailRecords];
423 }
424​
425 // Only a strictly grown file may resume. Same size with a new mtime, or
426 // a shrunken file, means rewritten content; re-parse it whole.
427 const resumeFrom =
428 cached !== undefined && cached.provider === provider && size > cached.size
429 ? cached.position
430 : undefined;
431​
432 const parsed = yield* Effect.promise(() =>
433 readTranscriptRecords(filePath, provider, resumeFrom),
434 );
435 // A read failure is not an empty transcript: caching it under this
436 // (size, mtime) would silently drop the file's usage until it changes.
437 if (parsed === null)
438 return cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [];
439​
440 // Stored already de-duplicated within the file, which is 99% of all
441 // duplicates. The aggregator still runs the cross-file dedupe pass. One
442 // seen set spans the cached base, the new lines, and the tail so a
443 // resumed parse dedupes exactly like a full one.
444 const base = parsed.resumed && cached !== undefined ? cached.records : [];
445 const seen = new Set<string>();
446 const records = dedupeWithinFile([...base, ...parsed.records], seen);
447 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
448​
449 fileCache.set(filePath, {
450 size,
451 mtimeMs,
452 provider,
453 records,
454 tailRecords,
455 position: parsed.position,
456 });
457 cacheDirty = true;
458 return tailRecords.length === 0 ? records : [...records, ...tailRecords];
459 });
460​
461 /** One provider directory's walk and parse, before rates are involved. */
462 interface ScannedDir {
463 readonly provider: UsageProviderKind;
464 readonly dir: string;
465 readonly volumeId: string;
466 readonly hostId?: string;
467 readonly status?: UsageSource["status"];
468 readonly message?: string;
469 readonly action?: UsageSource["action"];
470 /** Parsed records per file, or `null` when the directory does not exist. */
471 readonly files:
472 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
473 | null;
474 }
475​
476 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
477 windowStartMs: number,
478 settings: ServerSettingsValue,
479 retentionCutoffMs: number,
480 ) {
481 // The home resolvers ask for `Path` themselves; satisfy them from the
482 // instance we already hold so the scan stays context-free.
483 const dirs = yield* resolveTranscriptDirs(settings, retentionCutoffMs).pipe(
484 Effect.provideService(Path.Path, path),
485 );
486 const scanned: ScannedDir[] = [];
487 for (const { provider, dir, volumeId, fileName } of dirs) {
488 const exists = yield* fileSystem
489 .exists(dir)
490 .pipe(Effect.catchCause(() => Effect.succeed(false)));
491 if (!exists) {
492 scanned.push({ provider, dir, volumeId, files: null });
493 continue;
494 }
495 const files = yield* Effect.promise(() =>
496 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
497 );
498 const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = [];
499 for (const file of files) {
500 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
501 parsedFiles.push({ path: file.path, records });
502 }
503 scanned.push({ provider, dir, volumeId, files: parsedFiles });
504 }
505​
506 const home = NodeOS.homedir();
507 const envRoots = Effect.fnUntraced(function* (key: string, defaults: readonly string[]) {
508 const roots = hostEnvironment[key]
509 ?.split(",")
510 .map((value) => value.trim())
511 .filter(Boolean);
512 const canonical = new Set<string>();
513 for (const root of roots?.length ? roots : defaults) {
514 const resolved = path.resolve(expandHomePath(root));
515 canonical.add(
516 yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)),
517 );
518 }
519 return [...canonical];
520 });
521 const dataHome = hostEnvironment["XDG_DATA_HOME"]?.trim();
522 for (const dir of yield* envRoots("OPENCODE_DATA_DIR", [
523 path.join(
524 dataHome && path.isAbsolute(dataHome) ? dataHome : path.join(home, ".local", "share"),
525 "opencode",
526 ),
527 ])) {
528 const result = yield* Effect.promise(() => readOpenCodeUsage(dir, windowStartMs));
529 scanned.push({
530 provider: "opencode",
531 dir,
532 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
533 files: result.missing && !result.error ? null : result.files,
534 status: result.error ? "partial" : "ok",
535 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
536 });
537 }
538 const antigravityRoots = yield* envRoots("ANTIGRAVITY_DATA_DIR", [
539 ...["antigravity", "antigravity-cli", "antigravity-ide", "antigravity-backup"].map((name) =>
540 path.join(home, ".gemini", name),
541 ),
542 path.join(home, ".config", "antigravity"),
543 ]);
544 for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {
545 if (instance.driver === "antigravity") {
546 const directories = yield* resolveAntigravityInstanceDirectories(
547 config.stateDir,
548 ProviderInstanceId.make(instanceId),
549 ).pipe(
550 Effect.provideService(Crypto.Crypto, crypto),
551 Effect.provideService(Path.Path, path),
552 Effect.mapError(
553 (cause) =>
554 new UsageReadError({
555 reason: "scanFailed",
556 detail: "Antigravity profile directory could not be resolved.",
557 cause,
558 }),
559 ),
560 );
561 antigravityRoots.push(path.join(directories.profile, "antigravity-acp"));
562 }
563 }
564 const antigravityDirs = new Set<string>();
565 for (const root of antigravityRoots) {
566 const resolvedRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));
567 const nested = path.join(resolvedRoot, "conversations");
568 const dir = (yield* fileSystem
569 .exists(nested)
570 .pipe(Effect.catchCause(() => Effect.succeed(false))))
571 ? nested
572 : resolvedRoot;
573 antigravityDirs.add(yield* fileSystem.realPath(dir).pipe(Effect.orElseSucceed(() => dir)));
574 }
575 const antigravity = yield* Effect.promise(() =>
576 readAntigravityUsage([...antigravityDirs], windowStartMs),
577 );
578 for (const dir of antigravityDirs) {
579 const exists = yield* fileSystem
580 .exists(dir)
581 .pipe(Effect.catchCause(() => Effect.succeed(false)));
582 const failed = antigravity.errors.some(
583 (error) => error === dir || error.startsWith(`${dir}${path.sep}`),
584 );
585 scanned.push({
586 provider: "antigravity",
587 dir,
588 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(dir)),
589 files: !exists && !failed ? null : antigravity.files.filter((file) => file.root === dir),
590 status: failed ? "partial" : "ok",
591 ...(failed ? { message: "Some Antigravity history could not be read." } : {}),
592 });
593 }
594 const cursorUserHome =
595 (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home;
596 const configHome = hostEnvironment["XDG_CONFIG_HOME"]?.trim();
597 const cursorHome =
598 platform === "darwin"
599 ? path.join(cursorUserHome, "Library", "Application Support")
600 : platform === "win32"
601 ? hostEnvironment["APPDATA"] || path.join(cursorUserHome, "AppData", "Roaming")
602 : configHome && path.isAbsolute(configHome)
603 ? configHome
604 : path.join(cursorUserHome, ".config");
605 const cursorAuthPath =
606 platform === "darwin"
607 ? path.join(cursorUserHome, ".cursor", "auth.json")
608 : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json");
609 const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"];
610 const loginUnavailable =
611 Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) ||
612 Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) ||
613 credentialStore === "memory";
614 if (
615 platform === "darwin" &&
616 credentialStore !== "file" &&
617 !loginUnavailable &&
618 !settings.cursorKeychainUsageEnabled
619 ) {
620 scanned.push({
621 provider: "cursor",
622 dir: cursorAuthPath,
623 volumeId: "",
624 files: null,
625 message: "Cursor account usage is off on this environment.",
626 action: "enableCursorKeychain",
627 });
628 return scanned;
629 }
630 const cursorUntilMs = yield* Clock.currentTimeMillis;
631 const account = loginUnavailable
632 ? {
633 accountKey: null,
634 records: [],
635 missing: true,
636 error: "Cursor account history needs a Cursor CLI login on this server.",
637 }
638 : yield* Effect.promise(() =>
639 readCursorAccountUsage(
640 platform === "darwin" && credentialStore !== "file"
641 ? { kind: "keychain" }
642 : cursorAuthPath,
643 windowStartMs,
644 cursorUntilMs,
645 ),
646 );
647 // No saved login means there is no account source to report, not a setup error.
648 if (account.missing && account.error === null) return scanned;
649 if (account.accountKey !== null && account.error === null && !account.missing) {
650 // The same account includes CLI and desktop history from every machine.
651 // A stable remote fingerprint prevents connected environments counting it twice.
652 const source = `cursor-account:${account.accountKey}`;
653 scanned.push({
654 provider: "cursor",
655 dir: source,
656 hostId: "cursor.com",
657 volumeId: account.accountKey,
658 files: [{ path: source, records: account.records }],
659 status: "ok",
660 });
661 return scanned;
662 }
663 scanned.push({
664 provider: "cursor",
665 dir: cursorAuthPath,
666 volumeId: yield* Effect.promise(() => readDirectoryVolumeId(cursorAuthPath)),
667 // Never combine a local fallback with another server's account-wide history.
668 files: null,
669 message:
670 account.error ?? "Cursor account history needs a Cursor CLI login saved on this server.",
671 });
672 return scanned;
673 });
674​
675 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
676 input: UsageSummaryInput,
677 settings: ServerSettingsValue,
678 ) {
679 if (input.sinceDay > input.untilDay) {
680 return yield* new UsageReadError({
681 reason: "invalidWindow",
682 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
683 });
684 }
685​
686 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
687 if (input.resolution === "hour") {
688 const sinceTime =
689 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
690 const untilTime =
691 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
692 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
693 return yield* new UsageReadError({
694 reason: "invalidWindow",
695 detail: "Hourly usage requires valid sinceTime and untilTime instants",
696 });
697 }
698 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
699 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
700 const durationMs = untilTimeMs - sinceTimeMs;
701 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
702 return yield* new UsageReadError({
703 reason: "invalidWindow",
704 detail: "Hourly usage window must be greater than zero and at most 24 hours",
705 });
706 }
707 hourlyWindow = { sinceTimeMs, untilTimeMs };
708 }
709​
710 const startedAtMs = yield* Clock.currentTimeMillis;
711 yield* ensureScanCacheLoaded;
712​
713 const hostId = NodeOS.hostname();
714 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
715 if (Option.isNone(windowStart)) {
716 return yield* new UsageReadError({
717 reason: "invalidWindow",
718 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
719 });
720 }
721 const windowStartMs =
722 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
723​
724 const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
725​
726 // Pricing only matters once records are aggregated, so the rate table
727 // loads while transcripts stream instead of gating them: a cold rates
728 // fetch on a slow network no longer delays the scan by its own timeout.
729 const [, scannedDirs] = yield* Effect.all(
730 [ensureRates(false), collectDirs(windowStartMs, settings, retentionCutoffMs)],
731 { concurrency: 2 },
732 );
733​
734 const aggregator = new UsageAggregator({
735 timeZone: input.timeZone,
736 sinceDay: input.sinceDay,
737 untilDay: input.untilDay,
738 resolution: input.resolution ?? "day",
739 ...hourlyWindow,
740 rates,
741 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
742 });
743​
744 const sources: UsageSource[] = [];
745​
746 for (const {
747 provider,
748 dir,
749 volumeId,
750 files,
751 status,
752 message,
753 action,
754 hostId: sourceHostId,
755 } of scannedDirs) {
756 const retainedFiles = [...(files ?? [])];
757 const livePaths = new Set(retainedFiles.map((file) => file.path));
758 // Cleanup may remove transcripts, but the usage we already saved still
759 // contributes to this source. Keep the normal aggregation and dedupe path.
760 for (const [filePath, entry] of fileCache) {
761 if (
762 entry.provider !== provider ||
763 entry.mtimeMs < retentionCutoffMs ||
764 livePaths.has(filePath) ||
765 !isWithinDirectory(filePath, dir)
766 )
767 continue;
768 retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] });
769 }
770 let scannedFiles = 0;
771 let skippedFiles = 0;
772 // Distinct per directory. Buckets carry per-cell session counts, but a
773 // session spans days and models, so clients total this figure instead.
774 const sessionIds = new Set<string>();
775​
776 for (const file of retainedFiles) {
777 if (file.records.length === 0) {
778 skippedFiles += 1;
779 continue;
780 }
781 scannedFiles += 1;
782 const codexEventOccurrences = new Map<string, number>();
783 for (const record of file.records) {
784 let usageRecord = record;
785 if (record.provider === "codex" && record.sessionId.length > 0) {
786 // Match moved rollout copies without collapsing repeated equal events
787 // within one rollout (timestamps can have only second precision).
788 const key = encodeUsageRecordKey([
789 record.provider,
790 record.sessionId,
791 record.timestampMs,
792 record.model,
793 record.totals,
794 ]);
795 const occurrence = (codexEventOccurrences.get(key) ?? 0) + 1;
796 codexEventOccurrences.set(key, occurrence);
797 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
798 }
799 // Only sessions contributing in-window count; the mtime slack can
800 // admit boundary files whose records fall outside the range.
801 if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) {
802 sessionIds.add(record.sessionId);
803 }
804 }
805 }
806​
807 sources.push({
808 fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId },
809 // Clients exclude missing sources, so saved records remain an available source.
810 status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"),
811 scannedFiles,
812 skippedFiles,
813 malformedRecords: 0,
814 distinctSessions: sessionIds.size,
815 message:
816 message ?? (files === null ? "No transcript directory on this environment." : null),
817 ...(action ? { action } : {}),
818 });
819 }
820​
821 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
822 if (pruned > 0) cacheDirty = true;
823 yield* persistScanCache();
824​
825 const aggregated = aggregator.finish();
826 const readAt = yield* DateTime.now;
827 const finishedAtMs = yield* Clock.currentTimeMillis;
828​
829 return {
830 contractVersion: USAGE_CONTRACT_VERSION,
831 readAt: DateTime.formatIso(readAt),
832 timeZone: input.timeZone,
833 sinceDay: input.sinceDay,
834 untilDay: input.untilDay,
835 buckets: aggregated.buckets,
836 sources,
837 pricing: pricing(),
838 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
839 } satisfies UsageSummary;
840 });
841​
842 /**
843 * In-flight scans by window and custom prices, so concurrent identical requests (the usage
844 * page open on two clients at once) share one scan instead of racing over
845 * the same corpus twice.
846 */
847 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
848​
849 const scanKey = (
850 input: UsageSummaryInput,
851 priceOverrides: ServerSettingsValue["usagePriceOverrides"],
852 cursorKeychainUsageEnabled: boolean,
853 ): string =>
854 JSON.stringify([
855 input.timeZone,
856 input.sinceDay,
857 input.untilDay,
858 input.resolution ?? "day",
859 input.sinceTime ?? null,
860 input.untilTime ?? null,
861 priceOverrides,
862 cursorKeychainUsageEnabled,
863 ]);
864​
865 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
866 const settings = yield* readSettings;
867 const key = scanKey(input, settings.usagePriceOverrides, settings.cursorKeychainUsageEnabled);
868 const deferred = yield* Effect.uninterruptible(
869 Effect.gen(function* () {
870 const existing = inflightScans.get(key);
871 if (existing !== undefined) return existing;
872​
873 // Enrollment and detached-fiber creation must be atomic. Otherwise a
874 // canceled first caller can leave a Deferred with no scan to finish it.
875 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
876 inflightScans.set(key, created);
877 // Detached so one departing client cannot tear the scan out from under
878 // the fibers awaiting it; a finished scan warms the cache either way.
879 yield* scanSummary(input, settings).pipe(
880 Effect.onExit((exit) =>
881 Effect.sync(() => inflightScans.delete(key)).pipe(
882 Effect.andThen(Deferred.done(created, exit)),
883 ),
884 ),
885 Effect.forkDetach,
886 );
887 return created;
888 }),
889 );
890 // Waiting stays interruptible. The detached scan continues for other
891 // callers and still warms the cache if this caller leaves.
892 return yield* Deferred.await(deferred);
893 });
894​
895 return { readSummary, refreshRates } as const;
896});
897​
898export const layer = Layer.effect(UsageService, make);