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

UsageService.ts

697 lines27.0 KB

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