Open History to see the last commit
1import {
2 defaultInstanceIdForDriver,
3 providerInstanceConfigEnabledFlag,
4 ProviderInstanceId,
5 resolveProviderInstanceEnabled,
6 type UsageAccessRequest,
7 USAGE_CONTRACT_VERSION,
8 type ServerSettings as ServerSettingsValue,
9 type UsageProviderKind,
10 type UsageSource,
11 type UsagePricing,
12 type UsageSummary,
13 type UsageSummaryInput,
14 UsageReadError,
15} from "@t3tools/contracts";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as DateTime from "effect/DateTime";
21import * as Deferred from "effect/Deferred";
22import * as Effect from "effect/Effect";
23import * as Exit from "effect/Exit";
24import * as Fiber from "effect/Fiber";
25import * as FileSystem from "effect/FileSystem";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Path from "effect/Path";
29import * as Schema from "effect/Schema";
30import * as Semaphore from "effect/Semaphore";
31import { HttpClient, HttpClientResponse } from "effect/http";
32
33import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
34import { formatMalformedUsageWarning } from "@t3tools/shared/usageFormat";
35import * as ServerConfig from "../config.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import { BUILT_IN_USAGE_DRIVERS, type BuiltInUsageReadersEnv } from "../provider/builtInDrivers.ts";
38import type { ProviderDriver } from "@t3tools/provider-core/server/driver";
39import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
40import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
41import type {
42 ProviderUsageInstance,
43 TranscriptUsageFormat,
44 UsageRecord,
45} from "@t3tools/provider-core/server/usage";
46import { grokUsageFormat } from "./grokTranscriptUsage.ts";
47import {
48 canonicalModelFilter,
49 resolveModelAliases,
50 usageTimestampFilter,
51 UsageAggregator,
52} from "./usageAggregation.ts";
53import {
54 createOverrideRateTable,
55 isUnlistedModel,
56 parseRateTable,
57 type RateTable,
58} from "./usagePricing.ts";
59import {
60 DESKTOP_HOST_SCOPE_ENV,
61 listTranscriptFiles,
62 readDirectoryVolumeId,
63 readPhysicalSourceId,
64 readTranscriptRecords,
65} from "./usageTranscriptReader.ts";
66import {
67 decodeScanCache,
68 dedupeWithinFile,
69 LEGACY_SCAN_CACHE_FILE_NAMES,
70 makeScanCacheWriter,
71 pruneScanCache,
72 SCAN_CACHE_FILE_NAME,
73 type CachedFile,
74 type ScanCache,
75} from "./usageScanCache.ts";
76
77const LITELLM_RATES_URL =
78 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
79const LITELLM_RATES_API_URL =
80 "https://api.github.com/repos/BerriAI/litellm/contents/model_prices_and_context_window.json?ref=main";
81
82const RATES_TTL_MS = 24 * 60 * 60 * 1000;
83
84const RATES_REFRESH_FLOOR_MS = 60 * 1000;
85
86// mtime slack includes writes just before local midnight on the window's first day.
87const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
88const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
89
90const STALE_TEMP_DIRECTORY_MS = 60 * 60 * 1000;
91
92const TRANSCRIPT_READ_CONCURRENCY = 4;
93
94const transcriptReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
95 driver.usage?.kind === "transcripts" ? [{ driver, reader: driver.usage }] : [],
96);
97
98const scanReaders = BUILT_IN_USAGE_DRIVERS.flatMap((driver) =>
99 driver.usage?.kind === "scan" ? [{ driver, reader: driver.usage }] : [],
100);
101
102const providerRateModels = new Map(
103 BUILT_IN_USAGE_DRIVERS.flatMap(({ usage }) =>
104 usage?.rateModel === undefined ? [] : [[usage.provider, usage.rateModel] as const],
105 ),
106);
107
108const transcriptFormats = new Map(
109 transcriptReaders.map(({ reader }) => [reader.provider, reader.format] as const),
110);
111transcriptFormats.set("grok", grokUsageFormat);
112
113interface TranscriptSource {
114 readonly provider: UsageProviderKind;
115 readonly format: TranscriptUsageFormat<unknown>;
116 readonly dir: string;
117 readonly volumeId: string;
118 readonly physicalSourceId?: string;
119 readonly fileName?: string;
120}
121
122const RatesCacheFile = Schema.Struct({
123 fetchedAtMs: Schema.Number,
124 document: Schema.Unknown,
125});
126const decodeRatesCache = Schema.decodeUnknownEffect(Schema.fromJsonString(RatesCacheFile));
127const encodeRatesCache = Schema.encodeEffect(Schema.fromJsonString(RatesCacheFile));
128
129const ScanCacheJson = Schema.fromJsonString(Schema.Unknown);
130const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
131const encodeUsageRecordKey = Schema.encodeSync(ScanCacheJson);
132const CachedSource = Schema.Struct({ dir: Schema.String, volumeId: Schema.String });
133
134function isLaterRead(a: CachedFile, b: CachedFile): boolean {
135 return a.mtimeMs > b.mtimeMs || (a.mtimeMs === b.mtimeMs && a.size > b.size);
136}
137
138const sharedSessionProviders: ReadonlySet<UsageProviderKind> = new Set(
139 transcriptReaders.flatMap(({ reader }) =>
140 reader.format.sharedSessionsAcrossFiles ? [reader.provider] : [],
141 ),
142);
143
144// Only shared sessions need cross-file dedupe; per-file occurrence counts make other keys unique.
145function sharedSessions(
146 files: readonly { readonly records: readonly UsageRecord[] }[],
147): ReadonlySet<string> {
148 const firstFile = new Map<string, number>();
149 const shared = new Set<string>();
150 for (const [index, file] of files.entries()) {
151 let previous = "";
152 for (const { provider, sessionId } of file.records) {
153 if (!sharedSessionProviders.has(provider) || sessionId === previous || sessionId.length === 0)
154 continue;
155 previous = sessionId;
156 const first = firstFile.get(sessionId);
157 if (first === undefined) firstFile.set(sessionId, index);
158 else if (first !== index) shared.add(sessionId);
159 }
160 }
161 return shared;
162}
163const decodeCachedSources = Schema.decodeUnknownOption(
164 Schema.Struct({
165 sources: Schema.Record(Schema.String, CachedSource),
166 coveredSince: Schema.optional(Schema.Record(Schema.String, Schema.Number)),
167 }),
168);
169
170export class UsageService extends Context.Service<
171 UsageService,
172 {
173 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
174 readonly refreshRates: Effect.Effect<UsagePricing>;
175 }
176>()("t3/usage/UsageService") {}
177
178export const make = Effect.gen(function* () {
179 const fileSystem = yield* FileSystem.FileSystem;
180 const path = yield* Path.Path;
181 const config = yield* ServerConfig.ServerConfig;
182 const settingsService = yield* ServerSettings.ServerSettingsService;
183 const httpClient = yield* HttpClient.HttpClient;
184 const hostEnvironment = yield* HostProcess.Environment;
185 const hostPlatform = yield* HostProcess.Platform;
186 const hostScope = hostEnvironment[DESKTOP_HOST_SCOPE_ENV]?.trim();
187 // A mount or a directory's on-disk name does not change under a running server.
188 // A miss is not cached: the directory may not exist yet.
189 const physicalSourceIds = new Map<string, Promise<string | undefined>>();
190 const physicalSourceId = (dir: string) =>
191 Effect.promise(() => {
192 const cached = physicalSourceIds.get(dir);
193 if (cached !== undefined) return cached;
194 const id = readPhysicalSourceId(dir, hostScope, hostPlatform);
195 physicalSourceIds.set(dir, id);
196 void id.then((resolved) => {
197 if (resolved === undefined && physicalSourceIds.get(dir) === id) {
198 physicalSourceIds.delete(dir);
199 }
200 });
201 return id;
202 });
203 const hostname = yield* HostProcess.Hostname;
204 const readerContext = yield* Effect.context<BuiltInUsageReadersEnv>();
205
206 const fileCache: ScanCache = new Map();
207 // Reads from concurrent windows can still hold the original record after it is corrected.
208 const resolvedRecords = new WeakMap<UsageRecord, UsageRecord>();
209 const correctedRecord = (record: UsageRecord) => resolvedRecords.get(record) ?? record;
210 const correctedBatch = (records: readonly UsageRecord[]) =>
211 records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records;
212 const sourceCache = new Map<string, typeof CachedSource.Type>();
213 // Earliest window start a complete scan read each transcript directory from.
214 const coveredSince = new Map<string, number>();
215 const coverageKey = (source: TranscriptSource) => `${source.provider}\0${source.dir}`;
216 let cacheDirty = false;
217 const cover = (source: TranscriptSource, windowStartMs: number) => {
218 if ((coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs) return;
219 coveredSince.set(coverageKey(source), windowStartMs);
220 cacheDirty = true;
221 };
222 const isWithinDirectory = (filePath: string, dir: string) => {
223 const relative = path.relative(dir, filePath);
224 return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
225 };
226
227 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
228 const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
229 const writeCacheFile = (filePath: string, contents: string | Iterable<string>) =>
230 writeFileStringAtomically({ filePath, contents }).pipe(
231 Effect.provideService(FileSystem.FileSystem, fileSystem),
232 Effect.provideService(Path.Path, path),
233 );
234 const hostIdPath = path.join(config.baseDir, "usage-host-id");
235 const explicitHostId = hostEnvironment["T3CODE_HOST_ID"]?.trim();
236 const hostId =
237 explicitHostId ||
238 (yield* fileSystem.readFileString(hostIdPath).pipe(
239 Effect.catchIf(
240 (error) => error.reason._tag === "NotFound",
241 () =>
242 Effect.scoped(
243 Effect.gen(function* () {
244 yield* fileSystem.makeDirectory(config.baseDir, { recursive: true });
245 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
246 directory: config.baseDir,
247 prefix: "usage-host-id.",
248 });
249 const tempFile = path.join(tempDirectory, "identity");
250 yield* fileSystem.writeFileString(tempFile, `${hostname}\n`);
251 // Publish complete contents without replacing another initializer's identity.
252 yield* fileSystem.link(tempFile, hostIdPath).pipe(
253 Effect.catchIf(
254 (error) => error.reason._tag === "AlreadyExists",
255 () => Effect.void,
256 ),
257 );
258 return yield* fileSystem.readFileString(hostIdPath);
259 }),
260 ),
261 ),
262 Effect.map((value) => value.trim() || hostname),
263 Effect.orElseSucceed(() => hostname),
264 ));
265 let rates: RateTable = new Map();
266 let ratesFetchedAtMs: number | null = null;
267 let ratesLastFailedAtMs: number | null = null;
268 let ratesStatus: UsagePricing["status"] = "unavailable";
269 const ratesLock = yield* Semaphore.make(1);
270
271 const pricing = (): UsagePricing => ({
272 status: ratesStatus,
273 source: LITELLM_RATES_URL,
274 fetchedAt:
275 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
276 knownModels: rates.size,
277 });
278
279 const fetchRates = (url: string, accept = "application/json") =>
280 httpClient.get(url, { headers: { accept } }).pipe(
281 Effect.flatMap(HttpClientResponse.filterStatusOk),
282 Effect.flatMap((response) => response.json),
283 Effect.map((document) => {
284 const parsed = parseRateTable(document);
285 return parsed.size > 0 ? { document, parsed } : null;
286 }),
287 Effect.timeout(10_000),
288 Effect.catchCause(() => Effect.succeed(null)),
289 );
290
291 // Outside ratesLock, which a slow fetch holds: a provisional answer prices with these.
292 const loadSavedRates = yield* Effect.cached(
293 fileSystem.readFileString(ratesCachePath).pipe(
294 Effect.flatMap((raw) => decodeRatesCache(raw)),
295 Effect.map((saved) => {
296 const parsed = parseRateTable(saved.document);
297 if (parsed.size === 0) return;
298 rates = parsed;
299 ratesFetchedAtMs = saved.fetchedAtMs;
300 ratesStatus = "cached";
301 }),
302 Effect.ignoreCause,
303 ),
304 );
305
306 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
307 const now = yield* Clock.currentTimeMillis;
308 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
309 yield* loadSavedRates;
310 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
311 if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return;
312
313 let fetched = yield* fetchRates(LITELLM_RATES_URL);
314 if (fetched === null) {
315 fetched = yield* fetchRates(LITELLM_RATES_API_URL, "application/vnd.github.raw+json");
316 }
317 if (fetched === null) {
318 ratesLastFailedAtMs = yield* Clock.currentTimeMillis;
319 if (rates.size > 0) ratesStatus = "cached";
320 return;
321 }
322
323 rates = fetched.parsed;
324 ratesFetchedAtMs = now;
325 ratesLastFailedAtMs = null;
326 ratesStatus = "fresh";
327
328 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched.document }).pipe(
329 Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
330 Effect.ignoreCause,
331 );
332 });
333
334 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
335
336 // Rates are kept for RATES_TTL_MS, so a model released after the table was fetched would stay unpriced
337 // that long. A scan that meets a model the table does not list refetches early: once per model against
338 // a fresh table, with loadRates keeping RATES_REFRESH_FLOOR_MS between attempts.
339 const checkedUnlistedModels = new Set<string>();
340 const refreshForUnlistedModels = Effect.fn("UsageService.refreshForUnlistedModels")(function* (
341 models: ReadonlySet<string>,
342 ) {
343 const unlisted = [...models].filter(
344 (model) => !checkedUnlistedModels.has(model) && isUnlistedModel(rates, model),
345 );
346 if (unlisted.length === 0) return;
347 yield* ensureRates(true);
348 const now = yield* Clock.currentTimeMillis;
349 // A failed fetch leaves the models unchecked, so a later scan tries again.
350 if (ratesFetchedAtMs === null || now - ratesFetchedAtMs >= RATES_REFRESH_FLOOR_MS) return;
351 for (const model of unlisted) checkedUnlistedModels.add(model);
352 });
353
354 const refreshRates = ensureRates(true).pipe(
355 Effect.map(pricing),
356 Effect.withSpan("UsageService.refreshRates"),
357 );
358
359 const readSettings = settingsService.getSettings.pipe(
360 Effect.catchCause(
361 (cause) =>
362 new UsageReadError({
363 reason: "scanFailed",
364 detail: "Server settings could not be read.",
365 cause: Cause.squash(cause),
366 }),
367 ),
368 );
369
370 // Only enabled instances, and only those the user allowed; the rest are never read.
371 const usageInstances = Effect.fn("UsageService.usageInstances")(function* <Config>(
372 driver: ProviderDriver<Config, unknown, unknown>,
373 settings: ServerSettingsValue,
374 access: "allowed" | "unasked" = "allowed",
375 ) {
376 const entries = Object.entries(settings.providerInstances).filter(
377 ([, instance]) => instance.driver === driver.driverKind,
378 );
379 const defaultId = defaultInstanceIdForDriver(driver.driverKind);
380 if (
381 driver.metadata.hasDefaultInstance !== false &&
382 !Object.hasOwn(settings.providerInstances, defaultId)
383 ) {
384 entries.push([defaultId, { driver: driver.driverKind }]);
385 }
386 const decodeConfig = Schema.decodeUnknownOption(driver.configSchema);
387 return yield* Effect.forEach(
388 entries.filter(
389 ([, instance]) =>
390 resolveProviderInstanceEnabled(instance) &&
391 (access === "allowed"
392 ? instance.usageAccess === "allowed"
393 : instance.usageAccess === undefined),
394 ),
395 Effect.fnUntraced(function* ([id, instance]) {
396 const instanceConfig: ProviderUsageInstance<Config> = {
397 instanceId: ProviderInstanceId.make(id),
398 config: Option.getOrUndefined(decodeConfig(instance.config ?? {})),
399 environment: yield* mergeProviderInstanceEnvironment(
400 instance.environment,
401 hostEnvironment,
402 ),
403 configured: Object.hasOwn(settings.providerInstances, id),
404 };
405 return instanceConfig;
406 }),
407 );
408 });
409
410 // Enabled instances nobody has answered for yet. Finding a transcript folder only resolves paths.
411 const accessRequests = Effect.fn("UsageService.accessRequests")(function* (
412 settings: ServerSettingsValue,
413 ) {
414 const requests: Array<UsageAccessRequest> = [];
415 for (const driver of BUILT_IN_USAGE_DRIVERS) {
416 const reader = driver.usage;
417 if (reader === undefined) continue;
418 for (const instance of yield* usageInstances(driver, settings, "unasked")) {
419 const paths =
420 reader.kind === "transcripts"
421 ? (yield* reader.directories(instance, { awaitRefresh: false })).flatMap((entry) =>
422 entry.refreshing ? [] : [entry.dir],
423 )
424 : [];
425 requests.push({
426 instanceId: instance.instanceId,
427 driver: driver.driverKind,
428 provider: reader.provider,
429 paths,
430 });
431 }
432 }
433 return requests;
434 });
435
436 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
437 settings: ServerSettingsValue,
438 retentionCutoffMs: number,
439 awaitRefresh: boolean,
440 ) {
441 const dirs: Array<TranscriptSource> = [];
442 const pending: Array<ScannedDir> = [];
443 const seen = new Set<string>();
444 const sources = yield* Effect.forEach(transcriptReaders, ({ driver, reader }) =>
445 Effect.gen(function* () {
446 const directories = yield* Effect.forEach(
447 yield* usageInstances(driver, settings),
448 (instance) => reader.directories(instance, { awaitRefresh }),
449 );
450 return {
451 provider: reader.provider,
452 format: reader.format,
453 directories: directories.flat(),
454 };
455 }),
456 );
457 // The retired ACP driver still has transcripts on disk. Honor existing usage grants.
458 const grokDirectories = yield* Effect.forEach(
459 Object.values(settings.providerInstances).filter(
460 (instance) =>
461 instance.driver === "grok" &&
462 instance.usageAccess === "allowed" &&
463 instance.enabled !== false &&
464 providerInstanceConfigEnabledFlag(instance.config) !== false &&
465 (instance.enabled === true ||
466 providerInstanceConfigEnabledFlag(instance.config) === true),
467 ),
468 (instance) =>
469 Effect.gen(function* () {
470 const environment = yield* mergeProviderInstanceEnvironment(
471 instance.environment?.filter(({ name }) => name.toUpperCase() === "GROK_HOME"),
472 hostEnvironment,
473 );
474 const home = yield* HostProcess.HomeDirectory;
475 return {
476 dir: path.resolve(
477 expandHomePath(environment.GROK_HOME?.trim() || path.join(home, ".grok"), home),
478 "sessions",
479 ),
480 fileName: "updates.jsonl",
481 };
482 }),
483 );
484 sources.push({ provider: "grok", format: grokUsageFormat, directories: grokDirectories });
485 for (const { provider, format, directories } of sources) {
486 for (const { dir: directory, fileName, refreshing } of directories) {
487 if (refreshing) {
488 const key = `${provider}\0${directory}`;
489 if (seen.has(key)) continue;
490 seen.add(key);
491 pending.push({ provider, dir: directory, volumeId: "", files: [], refreshing });
492 continue;
493 }
494 const sourceKey = provider + "\0" + directory;
495 const previous = sourceCache.get(sourceKey);
496 const dir = yield* fileSystem
497 .realPath(directory)
498 .pipe(Effect.orElseSucceed(() => previous?.dir ?? directory));
499 const currentVolumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
500 const hasRetainedHistory = fileCache
501 .entries()
502 .some(
503 ([filePath, entry]) =>
504 entry.provider === provider &&
505 entry.mtimeMs >= retentionCutoffMs &&
506 (entry.records.length + entry.tailRecords.length > 0 ||
507 entry.malformedRecords.length > 0) &&
508 isWithinDirectory(filePath, dir),
509 );
510 const volumeId =
511 previous?.dir === dir && (hasRetainedHistory || !currentVolumeId)
512 ? previous.volumeId || currentVolumeId
513 : currentVolumeId;
514 if (previous?.dir !== dir || previous.volumeId !== volumeId) {
515 sourceCache.set(sourceKey, { dir, volumeId });
516 cacheDirty = true;
517 }
518 const key = `${provider}\0${dir}`;
519 if (seen.has(key)) continue;
520 seen.add(key);
521 const sourceId = yield* physicalSourceId(dir);
522 dirs.push({
523 provider,
524 format,
525 dir,
526 volumeId,
527 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
528 ...(fileName === undefined ? {} : { fileName }),
529 });
530 }
531 }
532 return { dirs, pending };
533 });
534
535 // Share first loads so concurrent readers cannot scan against a still-empty cache.
536 const ensureScanCacheLoaded = yield* Effect.cached(
537 Effect.gen(function* () {
538 const readDocument = (filePath: string) =>
539 fileSystem.readFileString(filePath).pipe(
540 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
541 Effect.catchCause(() => Effect.succeed(null)),
542 );
543 let document = yield* readDocument(scanCachePath);
544 const current = document !== null;
545 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
546 if (document !== null) break;
547 document = yield* readDocument(path.join(config.stateDir, fileName));
548 cacheDirty = document !== null;
549 }
550 if (document === null) return;
551 const decoded = decodeScanCache(document, transcriptFormats);
552 for (const [path, entry] of decoded) fileCache.set(path, entry);
553 const saved = (document as { readonly files?: unknown }).files;
554 const complete =
555 typeof saved === "object" && saved !== null && Object.keys(saved).length === decoded.size;
556 const sources = decodeCachedSources(document);
557 if (Option.isSome(sources)) {
558 for (const [key, source] of Object.entries(sources.value.sources))
559 sourceCache.set(key, source);
560 // Coverage describes the saved files, so it needs every one, in this version's format.
561 if (current && complete && fileCache.size > 0) {
562 for (const [key, since] of Object.entries(sources.value.coveredSince ?? {}))
563 coveredSince.set(key, since);
564 }
565 }
566 }),
567 );
568
569 const writeScanCache = makeScanCacheWriter();
570 // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots.
571 const persistLock = yield* Semaphore.make(1);
572
573 // The saved cache supersedes older versions. Temp folders an aborted write left behind are
574 // removed once idle for an hour, so a write in progress from another server survives.
575 let supersededFilesRemoved = false;
576 const removeSupersededCacheFiles = Effect.gen(function* () {
577 for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) {
578 yield* fileSystem.remove(path.join(config.stateDir, fileName)).pipe(Effect.ignore);
579 }
580 const tempPrefixes = [SCAN_CACHE_FILE_NAME, ...LEGACY_SCAN_CACHE_FILE_NAMES].map(
581 (fileName) => `${fileName}.`,
582 );
583 const staleBeforeMs = (yield* Clock.currentTimeMillis) - STALE_TEMP_DIRECTORY_MS;
584 for (const name of yield* fileSystem.readDirectory(config.stateDir)) {
585 if (!tempPrefixes.some((prefix) => name.startsWith(prefix))) continue;
586 const tempPath = path.join(config.stateDir, name);
587 yield* fileSystem.stat(tempPath).pipe(
588 Effect.flatMap((info) => {
589 const mtimeMs = Option.getOrUndefined(info.mtime)?.getTime();
590 return info.type === "Directory" && mtimeMs !== undefined && mtimeMs <= staleBeforeMs
591 ? fileSystem.remove(tempPath, { recursive: true })
592 : Effect.void;
593 }),
594 Effect.ignore,
595 );
596 }
597 }).pipe(Effect.ignore);
598
599 // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry.
600 const persistCaches = Effect.gen(function* () {
601 if (cacheDirty) {
602 cacheDirty = false;
603 yield* Effect.sync(() =>
604 writeScanCache(fileCache, {
605 sources: Object.fromEntries(sourceCache),
606 coveredSince: Object.fromEntries(coveredSince),
607 }),
608 ).pipe(
609 Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
610 Effect.andThen(
611 Effect.suspend(() => {
612 if (supersededFilesRemoved) return Effect.void;
613 supersededFilesRemoved = true;
614 return removeSupersededCacheFiles;
615 }),
616 ),
617 Effect.catchCause(() =>
618 Effect.sync(() => {
619 cacheDirty = true;
620 }),
621 ),
622 );
623 }
624 }).pipe(persistLock.withPermit, Effect.withSpan("UsageService.persistCaches"));
625
626 const pendingPersists = new Set<Fiber.Fiber<void>>();
627 const schedulePersist = Effect.forkDetach(persistCaches).pipe(
628 Effect.map((fiber) => {
629 pendingPersists.add(fiber);
630 fiber.addObserver(() => pendingPersists.delete(fiber));
631 }),
632 );
633 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
634 Effect.asVoid,
635 );
636 yield* Effect.addFinalizer(() => awaitPersisted);
637
638 /**
639 * Reads run concurrently, and the caller stores updates in walk order rather
640 * than completion order: saved records of deleted transcripts aggregate in
641 * cache order, where the first copy of a duplicate decides its bucket. Untraced: a scan
642 * reads thousands of files, so scanTranscriptDir records the counts instead.
643 */
644 const readFileRecords = Effect.fnUntraced(function* (
645 filePath: string,
646 size: number,
647 mtimeMs: number,
648 provider: UsageProviderKind,
649 format: TranscriptUsageFormat<unknown>,
650 ): Effect.fn.Return<{
651 readonly records: readonly UsageRecord[];
652 readonly malformedRecords: readonly number[];
653 readonly failed?: true;
654 readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined };
655 }> {
656 const cached = fileCache.get(filePath);
657 // Provider is part of the identity: if both providers were ever pointed
658 // at one directory, a hit parsed by the other parser must not be reused.
659 if (
660 cached &&
661 cached.size === size &&
662 cached.mtimeMs === mtimeMs &&
663 cached.provider === provider
664 ) {
665 return {
666 records:
667 cached.tailRecords.length === 0
668 ? cached.records
669 : [...cached.records, ...cached.tailRecords],
670 malformedRecords: cached.malformedRecords,
671 };
672 }
673
674 // Only a strictly grown file may resume. Same size with a new mtime, or
675 // a shrunken file, means rewritten content; re-parse it whole.
676 const resumeFrom =
677 cached !== undefined && cached.provider === provider && size > cached.size
678 ? cached.position
679 : undefined;
680
681 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom));
682 // A read failure is not an empty transcript: caching it under this
683 // (size, mtime) would silently drop the file's usage until it changes.
684 if (parsed === null)
685 return {
686 records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [],
687 malformedRecords: cached?.provider === provider ? cached.malformedRecords : [],
688 failed: true,
689 };
690
691 const identity = (record: UsageRecord) =>
692 encodeUsageRecordKey([
693 record.provider,
694 record.sessionId,
695 record.timestampMs,
696 record.model,
697 record.rateModel,
698 record.totals,
699 record.reportedCostUsd,
700 record.dedupeKey,
701 ]);
702 if (!parsed.resumed && cached !== undefined && cached.provider === provider) {
703 // A whole-file re-parse re-emits saved requests unresolved. Keep their saved tier
704 // corrections, since the history that resolved them may no longer be available.
705 // Equal requests keep their own corrections by matching occurrences in order.
706 const saved = new Map<string, UsageRecord[]>();
707 for (const previous of [...cached.records, ...cached.tailRecords]) {
708 const corrected = correctedRecord(previous);
709 const key = identity(corrected);
710 const occurrences = saved.get(key);
711 if (occurrences === undefined) saved.set(key, [corrected]);
712 else occurrences.push(corrected);
713 }
714 for (const record of [...parsed.records, ...parsed.tailRecords]) {
715 const corrected = saved.get(identity(record))?.shift();
716 if (
717 record.unresolvedServiceTierTurnId !== undefined &&
718 corrected !== undefined &&
719 corrected.unresolvedServiceTierTurnId === undefined
720 ) {
721 resolvedRecords.set(record, corrected);
722 }
723 }
724 }
725 if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) {
726 // Completing a tentative line reparses it. Reuse its saved correction only when the
727 // same usage is emitted again, without putting inferred tiers in the parser state.
728 const reparsed = [...parsed.records, ...parsed.tailRecords];
729 for (const [index, previous] of cached.tailRecords.entries()) {
730 const record = reparsed[index];
731 const corrected = correctedRecord(previous);
732 if (
733 record?.unresolvedServiceTierTurnId !== undefined &&
734 corrected.unresolvedServiceTierTurnId === undefined &&
735 identity(record) === identity(corrected)
736 ) {
737 resolvedRecords.set(record, corrected);
738 }
739 }
740 }
741 const base = parsed.resumed && cached !== undefined ? cached.records : [];
742 const records = dedupeWithinFile([...base, ...parsed.records]);
743 const tailRecords = parsed.tailRecords;
744
745 return {
746 records: tailRecords.length === 0 ? records : [...records, ...tailRecords],
747 malformedRecords: parsed.malformedRecords,
748 update: {
749 entry: {
750 size,
751 mtimeMs,
752 provider,
753 records,
754 tailRecords,
755 malformedRecords: parsed.malformedRecords,
756 position: parsed.position,
757 },
758 replaces: cached,
759 },
760 };
761 });
762
763 interface ScannedDir {
764 readonly provider: UsageProviderKind;
765 readonly dir: string;
766 readonly volumeId: string;
767 readonly physicalSourceId?: string;
768 readonly hostId?: string;
769 readonly status?: UsageSource["status"];
770 readonly message?: string;
771 readonly files:
772 | readonly {
773 readonly path: string;
774 readonly records: readonly UsageRecord[];
775 readonly malformedRecords: readonly number[];
776 }[]
777 | null;
778 /** Every transcript path the walk listed, in walk order, whatever its mtime. */
779 readonly walked?: readonly string[];
780 readonly refreshing?: true;
781 }
782
783 const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* (
784 source: TranscriptSource,
785 windowStartMs: number,
786 fromMemory: boolean,
787 ) {
788 const { provider, format, dir, volumeId, physicalSourceId, fileName } = source;
789 const identity = {
790 provider,
791 dir,
792 volumeId,
793 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
794 };
795 const exists = yield* fileSystem
796 .exists(dir)
797 .pipe(Effect.catchCause(() => Effect.succeed(false)));
798 if (!exists) {
799 cover(source, windowStartMs);
800 return { ...identity, files: null } satisfies ScannedDir;
801 }
802 // scanSummary aggregates the saved files, as it does for a deleted directory.
803 if (fromMemory) return { ...identity, files: [] } satisfies ScannedDir;
804 const { files, walked, failedPaths } = yield* Effect.promise(() =>
805 listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
806 );
807 const read = yield* Effect.forEach(
808 files,
809 (file) =>
810 readFileRecords(file.path, file.size, file.mtimeMs, provider, format).pipe(
811 Effect.map((result) => ({ path: file.path, ...result })),
812 ),
813 { concurrency: TRANSCRIPT_READ_CONCURRENCY },
814 );
815 const parsedFiles = read.map(({ path, records, malformedRecords, update }) => {
816 if (update === undefined) return { path, records, malformedRecords };
817 // A scan of another window may have cached its own read of this file
818 // meanwhile. Then keep whichever read saw the later file, so a slower
819 // scan never replaces newer usage with older.
820 const current = fileCache.get(path);
821 if (
822 current === update.replaces ||
823 current === undefined ||
824 isLaterRead(update.entry, current)
825 ) {
826 fileCache.set(path, {
827 ...update.entry,
828 records: correctedBatch(update.entry.records),
829 tailRecords: correctedBatch(update.entry.tailRecords),
830 });
831 cacheDirty = true;
832 }
833 return { path, records, malformedRecords };
834 });
835 const livePaths = new Set(files.map((file) => file.path));
836 for (const file of read) {
837 if (file.failed || !file.path.endsWith(".jsonl.zst")) continue;
838 const originalPath = file.path.slice(0, -4);
839 // A successfully read archive replaces the original's saved records and diagnostics.
840 if (!livePaths.has(originalPath) && fileCache.delete(originalPath)) cacheDirty = true;
841 }
842 const unread = failedPaths + read.filter((file) => file.failed).length;
843 if (unread === 0) cover(source, windowStartMs);
844 yield* Effect.annotateCurrentSpan({
845 "usage.files": files.length,
846 "usage.files_parsed": read.filter((file) => file.update !== undefined).length,
847 });
848 return {
849 ...identity,
850 files: parsedFiles,
851 walked,
852 ...(unread > 0
853 ? {
854 status: "partial",
855 message: `${unread} transcript path(s) could not be read; usage may be incomplete.`,
856 }
857 : {}),
858 } satisfies ScannedDir;
859 });
860
861 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
862 { dirs, pending }: Effect.Success<ReturnType<typeof resolveTranscriptDirs>>,
863 windowStartMs: number,
864 settings: ServerSettingsValue,
865 retentionCutoffMs: number,
866 awaitRefresh: boolean,
867 fromMemory: boolean,
868 ) {
869 const scans = Effect.forEach(
870 scanReaders,
871 ({ driver, reader }) =>
872 usageInstances(driver, settings).pipe(
873 Effect.flatMap((instances) =>
874 reader.scan({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }),
875 ),
876 Effect.flatMap((sources) =>
877 Effect.forEach(sources, ({ volumeId, ...source }) =>
878 Effect.map(
879 // A reader's own volumeId names a remote account, not a local directory.
880 volumeId === undefined
881 ? Effect.all([
882 Effect.promise(() => readDirectoryVolumeId(source.dir)),
883 physicalSourceId(source.dir),
884 ])
885 : Effect.succeed<[string, string | undefined]>([volumeId, undefined]),
886 ([resolved, sourceId]): ScannedDir => ({
887 ...source,
888 files: source.files?.map((file) => ({ ...file, malformedRecords: [] })) ?? null,
889 provider: reader.provider,
890 volumeId: resolved,
891 ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }),
892 }),
893 ),
894 ),
895 ),
896 Effect.provideContext(readerContext),
897 ),
898 { concurrency: "unbounded" },
899 );
900
901 // Scan independent sources together, directories sequentially to bound open files; keep order, since the first copy decides a duplicate's bucket.
902 const [transcripts, scanDirs] = yield* Effect.all(
903 [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs, fromMemory)), scans],
904 { concurrency: "unbounded" },
905 );
906 const scanned: readonly ScannedDir[] = [...transcripts, ...pending, ...scanDirs.flat()];
907 return scanned;
908 });
909
910 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
911 input: UsageSummaryInput,
912 settings: ServerSettingsValue,
913 provisional: boolean,
914 ) {
915 if (input.sinceDay > input.untilDay) {
916 return yield* new UsageReadError({
917 reason: "invalidWindow",
918 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
919 });
920 }
921
922 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
923 if (input.resolution === "hour") {
924 const sinceTime =
925 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
926 const untilTime =
927 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
928 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
929 return yield* new UsageReadError({
930 reason: "invalidWindow",
931 detail: "Hourly usage requires valid sinceTime and untilTime instants",
932 });
933 }
934 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
935 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
936 const durationMs = untilTimeMs - sinceTimeMs;
937 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
938 return yield* new UsageReadError({
939 reason: "invalidWindow",
940 detail: "Hourly usage window must be greater than zero and at most 24 hours",
941 });
942 }
943 hourlyWindow = { sinceTimeMs, untilTimeMs };
944 }
945
946 const startedAtMs = yield* Clock.currentTimeMillis;
947 yield* ensureScanCacheLoaded;
948
949 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
950 if (Option.isNone(windowStart)) {
951 return yield* new UsageReadError({
952 reason: "invalidWindow",
953 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
954 });
955 }
956 const windowStartMs =
957 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
958
959 const retentionCutoffMs =
960 settings.usageHistoryRetentionDays === "unlimited"
961 ? 0
962 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000);
963
964 const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow });
965 const windowEndMs =
966 hourlyWindow?.untilTimeMs ??
967 Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS;
968
969 const awaitRefresh = input.awaitRefresh === true;
970 const collect = Effect.gen(function* () {
971 const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe(
972 Effect.provideContext(readerContext),
973 );
974 // A window no complete scan has read would show partial totals, so every directory must cover it.
975 // Saved files are keyed by path, so two providers reading one directory keep only one parse.
976 const fromMemory =
977 provisional &&
978 resolved.dirs.length > 0 &&
979 new Set(resolved.dirs.map((source) => source.dir)).size === resolved.dirs.length &&
980 resolved.dirs.every(
981 (source) => (coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs,
982 );
983 const [, scanned] = yield* Effect.all(
984 [
985 fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void,
986 collectDirs(
987 resolved,
988 windowStartMs,
989 settings,
990 retentionCutoffMs,
991 awaitRefresh,
992 fromMemory,
993 ),
994 ],
995 { concurrency: 2 },
996 );
997 return { scannedDirs: scanned, fromMemory };
998 });
999 const [{ scannedDirs, fromMemory }] = yield* Effect.all(
1000 [collect, provisional ? Effect.void : ensureRates(false)],
1001 { concurrency: 2 },
1002 );
1003
1004 const priceOverrides = createOverrideRateTable(settings.usagePriceOverrides);
1005 const modelAliases = resolveModelAliases(settings.usageModelAliases);
1006 const sources: UsageSource[] = [];
1007
1008 // Deleted transcripts' saved usage still aggregates and deduplicates normally.
1009 const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs);
1010 // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times.
1011 const withinDir = (dir: string) => {
1012 const foldersWithin = new Map<string, boolean>();
1013 return (filePath: string) => {
1014 const folder = path.dirname(filePath);
1015 let within = foldersWithin.get(folder);
1016 if (within === undefined) {
1017 within = isWithinDirectory(folder, dir);
1018 foldersWithin.set(folder, within);
1019 }
1020 return within;
1021 };
1022 };
1023 const filesByDir = scannedDirs.map(({ provider, dir, files }) => {
1024 const retainedFiles = [...(files ?? [])];
1025 const livePaths = new Set(retainedFiles.map((file) => file.path));
1026 const isRetained = withinDir(dir);
1027 for (const [filePath, entry] of fileCache) {
1028 if (
1029 entry.provider !== provider ||
1030 entry.mtimeMs < retainedSinceMs ||
1031 livePaths.has(filePath) ||
1032 !isRetained(filePath)
1033 )
1034 continue;
1035 retainedFiles.push({
1036 path: filePath,
1037 records:
1038 entry.tailRecords.length === 0
1039 ? entry.records
1040 : [...entry.records, ...entry.tailRecords],
1041 malformedRecords: entry.malformedRecords,
1042 });
1043 }
1044 return retainedFiles.flatMap((file) => {
1045 // A keyed copy outside the window still claims its key, so a later copy is not counted.
1046 const records = file.records.filter(
1047 (record) => record.dedupeKey !== null || inWindow(record.timestampMs),
1048 );
1049 const malformedRecords = file.malformedRecords.filter(inWindow);
1050 return records.length === 0 && malformedRecords.length === 0
1051 ? []
1052 : [{ ...file, records, malformedRecords }];
1053 });
1054 });
1055 // Usage two transcripts share counts in the first one, so saved files take the order an exact
1056 // scan reads them in: walked files in walk order, then the directory's deleted files.
1057 for (const { provider, dir, walked } of fromMemory ? [] : scannedDirs) {
1058 if (walked === undefined) continue;
1059 const within = withinDir(dir);
1060 const saved = [...fileCache.keys()];
1061 const members = new Set(
1062 saved.filter(
1063 (filePath) => fileCache.get(filePath)!.provider === provider && within(filePath),
1064 ),
1065 );
1066 if (members.size < 2) continue;
1067 const listed = new Set(walked);
1068 const target = [
1069 ...walked.filter((filePath) => members.has(filePath)),
1070 ...saved.filter((filePath) => members.has(filePath) && !listed.has(filePath)),
1071 ];
1072 let next = 0;
1073 const ordered = saved.map((filePath) => (members.has(filePath) ? target[next++]! : filePath));
1074 if (ordered.every((filePath, index) => filePath === saved[index])) continue;
1075 const entries = new Map(fileCache);
1076 fileCache.clear();
1077 for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!);
1078 cacheDirty = true;
1079 }
1080
1081 // The models priced below, as UsageAggregator resolves them: an alias replaces rateModel.
1082 const rateModels = new Set<string>();
1083 for (const files of filesByDir) {
1084 for (const file of files) {
1085 for (const record of file.records) {
1086 const alias = modelAliases.get(record.model);
1087 const model = alias ?? record.model;
1088 if (priceOverrides.has(model.trim())) continue;
1089 rateModels.add(alias === undefined ? (record.rateModel ?? model) : model);
1090 }
1091 }
1092 }
1093 // A saved answer prices with saved rates and the full scan after it refetches.
1094 if (!fromMemory) yield* refreshForUnlistedModels(rateModels);
1095
1096 const summaryPricing = pricing();
1097
1098 const aggregator = new UsageAggregator({
1099 timeZone: input.timeZone,
1100 sinceDay: input.sinceDay,
1101 untilDay: input.untilDay,
1102 resolution: input.resolution ?? "day",
1103 ...hourlyWindow,
1104 rates,
1105 priceOverrides,
1106 modelAliases,
1107 rateModel: (provider, model) => providerRateModels.get(provider)?.(model),
1108 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1109 });
1110
1111 let resolvedAny = false;
1112 for (const { reader } of transcriptReaders) {
1113 if (reader.resolveServiceTiers === undefined || fromMemory) continue;
1114 const pending = new Set<UsageRecord>();
1115 for (const [index, files] of filesByDir.entries()) {
1116 if (scannedDirs[index]?.provider !== reader.provider) continue;
1117 for (const file of files) {
1118 for (const raw of file.records) {
1119 const record = correctedRecord(raw);
1120 if (
1121 record.provider === reader.provider &&
1122 record.unresolvedServiceTierTurnId !== undefined &&
1123 record.timestampMs >= windowStartMs &&
1124 record.timestampMs < windowEndMs
1125 ) {
1126 pending.add(record);
1127 }
1128 }
1129 }
1130 }
1131 if (pending.size === 0) continue;
1132 const resolved = yield* reader
1133 .resolveServiceTiers([...pending])
1134 .pipe(Effect.provideContext(readerContext));
1135 for (const [record, speed] of resolved) {
1136 const { unresolvedServiceTierTurnId: _turnId, ...rest } = record;
1137 resolvedRecords.set(record, { ...rest, speed });
1138 resolvedAny = true;
1139 }
1140 }
1141 if (resolvedAny) {
1142 for (const [filePath, entry] of fileCache) {
1143 const records = correctedBatch(entry.records);
1144 const tailRecords = correctedBatch(entry.tailRecords);
1145 if (records === entry.records && tailRecords === entry.tailRecords) continue;
1146 // Update the current entry by identity; a slow resolver cannot restore an older file.
1147 fileCache.set(filePath, { ...entry, records, tailRecords });
1148 cacheDirty = true;
1149 }
1150 }
1151 const crossFileSessions = sharedSessions(filesByDir.flat());
1152
1153 for (const [
1154 index,
1155 {
1156 provider,
1157 dir,
1158 volumeId,
1159 physicalSourceId,
1160 files,
1161 status,
1162 message,
1163 refreshing,
1164 hostId: sourceHostId,
1165 },
1166 ] of scannedDirs.entries()) {
1167 let scannedFiles = 0;
1168 let skippedFiles = 0;
1169 let malformedRecords = 0;
1170 // Distinct per directory. Buckets carry per-cell session counts, but a
1171 // session spans days and models, so clients total this figure instead.
1172 const sessionIds = new Set<string>();
1173 let counted = false;
1174
1175 for (const file of filesByDir[index] ?? []) {
1176 malformedRecords += file.malformedRecords.length;
1177 if (file.records.length === 0) {
1178 skippedFiles += 1;
1179 continue;
1180 }
1181 scannedFiles += 1;
1182 const eventOccurrences = new Map<string, number>();
1183 for (const rawRecord of file.records) {
1184 const record = correctedRecord(rawRecord);
1185 let usageRecord = record;
1186 if (
1187 sharedSessionProviders.has(record.provider) &&
1188 crossFileSessions.has(record.sessionId)
1189 ) {
1190 // Dedupe moved copies but retain repeated equal events within a file, including second-precision timestamps.
1191 const key = encodeUsageRecordKey([
1192 record.provider,
1193 record.sessionId,
1194 record.timestampMs,
1195 record.model,
1196 record.totals,
1197 ]);
1198 const occurrence = (eventOccurrences.get(key) ?? 0) + 1;
1199 eventOccurrences.set(key, occurrence);
1200 usageRecord = { ...record, dedupeKey: key + ":" + occurrence };
1201 }
1202 if (aggregator.add(usageRecord, dir)) {
1203 counted = true;
1204 if (record.sessionId.length > 0) sessionIds.add(record.sessionId);
1205 }
1206 }
1207 }
1208
1209 const sourceMessage =
1210 message ?? (files === null ? "No transcript directory on this environment." : null);
1211 sources.push({
1212 fingerprint: {
1213 hostId: sourceHostId ?? hostId,
1214 provider,
1215 resolvedHomePath: dir,
1216 volumeId,
1217 ...(physicalSourceId === undefined ? {} : { physicalSourceId }),
1218 },
1219 status:
1220 files === null && scannedFiles === 0
1221 ? "missing"
1222 : malformedRecords > 0
1223 ? status === undefined || status === "ok"
1224 ? "partial"
1225 : status
1226 : (status ?? "ok"),
1227 scannedFiles,
1228 skippedFiles,
1229 malformedRecords,
1230 distinctSessions: sessionIds.size,
1231 message:
1232 malformedRecords > 0
1233 ? [sourceMessage, formatMalformedUsageWarning(malformedRecords)]
1234 .filter(Boolean)
1235 .join(" ")
1236 : sourceMessage,
1237 // A saved answer misses what changed since its scan, so the client must ask again. An
1238 // empty source stays unmarked: it would only flash a loading row.
1239 ...(refreshing || (fromMemory && counted && transcriptFormats.has(provider))
1240 ? { refreshing: true }
1241 : {}),
1242 });
1243 }
1244
1245 yield* settingsService
1246 .withSettingsSnapshot((currentSettings) =>
1247 Effect.sync(() => {
1248 if (settings.usageHistoryRetentionDays === currentSettings.usageHistoryRetentionDays) {
1249 const pruned = pruneScanCache(fileCache, retentionCutoffMs);
1250 if (pruned > 0) {
1251 cacheDirty = true;
1252 // Pruned files are no longer saved, so nothing before the cutoff stays covered.
1253 for (const [key, since] of coveredSince) {
1254 if (since < retentionCutoffMs) coveredSince.set(key, retentionCutoffMs);
1255 }
1256 }
1257 }
1258 }),
1259 )
1260 .pipe(
1261 Effect.catchCause((cause) =>
1262 Effect.logWarning("failed to read settings before pruning the usage cache", { cause }),
1263 ),
1264 );
1265
1266 const aggregated = aggregator.finish();
1267 const readAt = yield* DateTime.now;
1268 const finishedAtMs = yield* Clock.currentTimeMillis;
1269
1270 const summary = {
1271 contractVersion: USAGE_CONTRACT_VERSION,
1272 readAt: DateTime.formatIso(readAt),
1273 timeZone: input.timeZone,
1274 sinceDay: input.sinceDay,
1275 untilDay: input.untilDay,
1276 buckets: aggregated.buckets,
1277 sources,
1278 pricing: summaryPricing,
1279 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
1280 ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }),
1281 accessRequests: yield* accessRequests(settings).pipe(Effect.provideContext(readerContext)),
1282 } satisfies UsageSummary;
1283 return { summary, fromMemory };
1284 });
1285
1286 const readWindow = Effect.fn("UsageService.readWindow")(function* (
1287 input: UsageSummaryInput,
1288 settings: ServerSettingsValue,
1289 provisional: boolean,
1290 ) {
1291 const { summary, fromMemory } = yield* scanSummary(input, settings, provisional);
1292 // With nothing marked refreshing the client would keep a saved answer as final.
1293 return fromMemory && !summary.sources.some((source) => source.refreshing === true)
1294 ? (yield* scanSummary(input, settings, false)).summary
1295 : summary;
1296 });
1297
1298 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
1299
1300 const scanKey = (
1301 input: UsageSummaryInput,
1302 settings: ServerSettingsValue,
1303 provisional: boolean,
1304 ): string =>
1305 JSON.stringify([
1306 input.timeZone,
1307 input.sinceDay,
1308 input.untilDay,
1309 input.resolution ?? "day",
1310 input.sinceTime ?? null,
1311 input.untilTime ?? null,
1312 settings,
1313 input.awaitRefresh === true,
1314 provisional,
1315 input.modelFilter ?? null,
1316 ]);
1317
1318 const readSummary = Effect.fn("UsageService.readSummary")(function* (
1319 requested: UsageSummaryInput,
1320 ) {
1321 const { modelFilter: requestedFilter, ...unfiltered } = requested;
1322 const modelFilter = canonicalModelFilter(requestedFilter);
1323 const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter };
1324 const settings = yield* readSettings;
1325 const provisional = input.provisional === true && input.awaitRefresh !== true;
1326 const key = scanKey(input, settings, provisional);
1327 const deferred = yield* Effect.uninterruptible(
1328 Effect.gen(function* () {
1329 const existing = inflightScans.get(key);
1330 if (existing !== undefined) return existing;
1331
1332 // Register and fork atomically so cancellation cannot leave a Deferred without a scan.
1333 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
1334 inflightScans.set(key, created);
1335 // Detach so caller departure cannot cancel shared scans; finished scans warm the cache.
1336 // Register writes before releasing waiters, but start writing after delivering their summary.
1337 yield* readWindow(input, settings, provisional).pipe(
1338 Effect.onExit((exit) =>
1339 Effect.sync(() => inflightScans.delete(key)).pipe(
1340 Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void),
1341 Effect.andThen(Deferred.done(created, exit)),
1342 ),
1343 ),
1344 Effect.forkDetach,
1345 );
1346 return created;
1347 }),
1348 );
1349 return yield* Deferred.await(deferred);
1350 });
1351
1352 return { readSummary, refreshRates, awaitPersisted } as const;
1353});
1354
1355export const layer = Layer.effect(UsageService, make);