Open History to see the last commit
1/**
2 * UsageService - scans provider transcripts and returns priced usage buckets.
3 *
4 * The scan reads the provider CLIs' own session files rather than T3 Code's
5 * orchestration projections, so usage covers turns driven outside T3 Code too.
6 * 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.
11 *
12 * @module UsageService
13 */
14import * as NodeOS from "node:os";
15
16import {
17 USAGE_CONTRACT_VERSION,
18 type UsageProviderKind,
19 type UsageSource,
20 type UsageSummary,
21 type UsageSummaryInput,
22 UsageReadError,
23} from "@t3tools/contracts";
24import * as Cause from "effect/Cause";
25import * as Clock from "effect/Clock";
26import * as Context from "effect/Context";
27import * as DateTime from "effect/DateTime";
28import * as Effect from "effect/Effect";
29import * as FileSystem from "effect/FileSystem";
30import * as Layer from "effect/Layer";
31import * as Option from "effect/Option";
32import * as Path from "effect/Path";
33import * as Schema from "effect/Schema";
34import { HttpClient, HttpClientResponse } from "effect/unstable/http";
35
36import { ServerConfig } from "../config.ts";
37import { expandHomePath } from "../pathExpansion.ts";
38import * as ServerSettings from "../serverSettings.ts";
39import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
40import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";
41import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
42import { UsageAggregator } from "./usageAggregation.ts";
43import {
44 mergeRateTables,
45 parseOpenCodeRates,
46 parseRateTable,
47 type RateTable,
48} from "./usagePricing.ts";
49import {
50 listOpenCodeDatabaseFiles,
51 listTranscriptFiles,
52 readDirectoryVolumeId,
53 readTranscriptRecords,
54 type OpenCodeStoreFile,
55 type OpenCodeWalIdentity,
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/**
70 * Source of OpenCode's go/zen model prices. models.dev publishes a different
71 * document layout to LiteLLM (per-million-token `cost` on each model), so it is
72 * fetched and parsed separately and merged over the LiteLLM table.
73 */
74const MODELS_DEV_URL = "https://models.dev/api.json";
75
76/** Rates move rarely; a day-old table keeps the page working offline. */
77const RATES_TTL_MS = 24 * 60 * 60 * 1000;
78
79/** Combined label for where the served rate table came from. */
80const PRICING_SOURCE_LABEL = "LiteLLM + models.dev (opencode go/zen)";
81
82/**
83 * Files are filtered by mtime before opening. The slack covers a session whose
84 * last write lands just before local midnight on the window's first day.
85 */
86const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
87const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
88
89/** Longest window the UI offers, plus slack. Older entries are pruned. */
90const CACHE_RETENTION_DAYS = 90;
91
92/** On-disk shape of the rate snapshot. */
93const RatesCacheFile = Schema.Struct({
94 fetchedAtMs: Schema.Number,
95 document: Schema.Unknown,
96});
97const decodeRatesCache = Schema.decodeUnknownEffect(
98 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
99);
100const encodeRatesCache = Schema.encodeEffect(
101 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
102);
103
104/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
105const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
106const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
107const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
108
109export class UsageService extends Context.Service<
110 UsageService,
111 {
112 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
113 }
114>()("t3/usage/UsageService") {}
115
116/** Empty summary, for suites that only need the RPC surface to resolve. */
117export const layerTest = Layer.succeed(
118 UsageService,
119 UsageService.of({
120 readSummary: (input) =>
121 Effect.succeed({
122 contractVersion: USAGE_CONTRACT_VERSION,
123 readAt: "1970-01-01T00:00:00.000Z",
124 timeZone: input.timeZone,
125 sinceDay: input.sinceDay,
126 untilDay: input.untilDay,
127 buckets: [],
128 sources: [],
129 pricing: {
130 status: "unavailable",
131 source: PRICING_SOURCE_LABEL,
132 fetchedAt: null,
133 knownModels: 0,
134 },
135 scanDurationMs: 0,
136 }),
137 }),
138);
139
140export const make = Effect.gen(function* () {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const config = yield* ServerConfig;
144 const settingsService = yield* ServerSettings.ServerSettingsService;
145 const httpClient = yield* HttpClient.HttpClient;
146
147 const fileCache: ScanCache = new Map();
148 let cacheDirty = false;
149
150 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
151 const openCodeRatesCachePath = path.join(config.stateDir, "usage-model-rates-modelsdev.json");
152 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
153 let litellmRates: RateTable = new Map();
154 let ratesFetchedAtMs: number | null = null;
155 let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";
156 /**
157 * The models.dev go/zen overlay, kept apart from `litellmRates`. Either
158 * source may refresh on its own clock; the overlay is re-merged into the
159 * served table at read time so one source expiring can never evict the
160 * other's prices.
161 */
162 let openCodeRates: RateTable = new Map();
163 let openCodeRatesFetchedAtMs: number | null = null;
164
165 /**
166 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
167 * the on-disk snapshot. With neither, every model reports as unpriced rather
168 * than the page failing.
169 */
170 const ensureRates = Effect.fn("UsageService.ensureRates")(function* () {
171 const now = yield* Clock.currentTimeMillis;
172 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;
173
174 if (ratesFetchedAtMs === null) {
175 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
176 Effect.flatMap((raw) => decodeRatesCache(raw)),
177 Effect.catchCause(() => Effect.succeed(null)),
178 );
179 if (fromDisk !== null) {
180 const parsed = parseRateTable(fromDisk.document);
181 if (parsed.size > 0) {
182 litellmRates = parsed;
183 ratesFetchedAtMs = fromDisk.fetchedAtMs;
184 ratesStatus = "cached";
185 if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
186 }
187 }
188 }
189
190 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
191 Effect.flatMap(HttpClientResponse.filterStatusOk),
192 Effect.flatMap((response) => response.json),
193 Effect.timeout(10_000),
194 Effect.catchCause(() => Effect.succeed(null)),
195 );
196 if (fetched === null) {
197 // The refresh failed; whatever we are serving is now past its TTL and
198 // must not keep claiming to be fresh.
199 if (litellmRates.size > 0) ratesStatus = "cached";
200 return;
201 }
202
203 const parsed = parseRateTable(fetched);
204 if (parsed.size === 0) return;
205
206 litellmRates = parsed;
207 ratesFetchedAtMs = now;
208 ratesStatus = "fresh";
209
210 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
211 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
212 Effect.catchCause(() => Effect.void),
213 );
214 });
215
216 /**
217 * Loads OpenCode's go/zen rates from models.dev into the dedicated overlay
218 * table.
219 *
220 * Mirrors `ensureRates`: fresh copy preferred, then the on-disk snapshot,
221 * and silence (rather than failure) when neither exists. models.dev keys its
222 * entries by `providerID/modelID`, so go and zen prices for one model id stay
223 * distinct. The same `RatesCacheFile` shape is reused under its own path.
224 *
225 * The overlay is merged over `litellmRates` at read time, so this function
226 * only needs to refresh its own table; it never touches `litellmRates`.
227 */
228 const ensureOpenCodeRates = Effect.fn("UsageService.ensureOpenCodeRates")(function* () {
229 const now = yield* Clock.currentTimeMillis;
230 if (openCodeRatesFetchedAtMs !== null && now - openCodeRatesFetchedAtMs < RATES_TTL_MS) return;
231
232 if (openCodeRatesFetchedAtMs === null) {
233 const fromDisk = yield* fileSystem.readFileString(openCodeRatesCachePath).pipe(
234 Effect.flatMap((raw) => decodeRatesCache(raw)),
235 Effect.catchCause(() => Effect.succeed(null)),
236 );
237 if (fromDisk !== null) {
238 const parsed = parseOpenCodeRates(fromDisk.document);
239 if (parsed.size > 0) {
240 openCodeRates = parsed;
241 openCodeRatesFetchedAtMs = fromDisk.fetchedAtMs;
242 if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;
243 }
244 }
245 }
246
247 const fetched = yield* httpClient.get(MODELS_DEV_URL).pipe(
248 Effect.flatMap(HttpClientResponse.filterStatusOk),
249 Effect.flatMap((response) => response.json),
250 Effect.timeout(10_000),
251 Effect.catchCause(() => Effect.succeed(null)),
252 );
253 if (fetched === null) return;
254
255 const parsed = parseOpenCodeRates(fetched);
256 if (parsed.size === 0) return;
257
258 openCodeRates = parsed;
259 openCodeRatesFetchedAtMs = now;
260
261 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
262 Effect.flatMap((serialized) =>
263 fileSystem.writeFileString(openCodeRatesCachePath, serialized),
264 ),
265 Effect.catchCause(() => Effect.void),
266 );
267 });
268
269 /**
270 * Claude's config dir is the home itself when overridden, but a default
271 * install nests transcripts under `~/.claude/projects`. Probe both.
272 */
273 const resolveClaudeTranscriptDir = (homePath: string) =>
274 Effect.gen(function* () {
275 const nested = path.join(homePath, ".claude", "projects");
276 const nestedExists = yield* fileSystem
277 .exists(nested)
278 .pipe(Effect.catchCause(() => Effect.succeed(false)));
279 return nestedExists ? nested : path.join(homePath, "projects");
280 });
281
282 /**
283 * OpenCode's session store directory, mirroring the CLI's own resolution:
284 * an explicit `OPENCODE_DATA_DIR` wins, then the XDG data home, then the
285 * platform default (`~/.local/share/opencode`, or `~/Library/Application
286 * Support/opencode` on macOS).
287 */
288 const resolveOpenCodeDataDir = Effect.fn("UsageService.resolveOpenCodeDataDir")(function* () {
289 const env = yield* HostProcessEnvironment;
290 const platform = yield* HostProcessPlatform;
291
292 const fromEnv = env.OPENCODE_DATA_DIR;
293 if (fromEnv !== undefined && fromEnv.trim().length > 0) {
294 return path.resolve(expandHomePath(fromEnv));
295 }
296 const xdgDataHome = env.XDG_DATA_HOME;
297 if (xdgDataHome !== undefined && xdgDataHome.trim().length > 0) {
298 return path.join(path.resolve(expandHomePath(xdgDataHome)), "opencode");
299 }
300 if (platform === "darwin") {
301 return path.join(NodeOS.homedir(), "Library", "Application Support", "opencode");
302 }
303 return path.join(NodeOS.homedir(), ".local", "share", "opencode");
304 });
305
306 /** Resolves the transcript directory for each provider. */
307 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {
308 // A settings failure must surface as an error: swallowing it here would
309 // present "zero usage from every provider" as a valid answer.
310 const settings = yield* settingsService.getSettings.pipe(
311 Effect.catchCause(
312 (cause) =>
313 new UsageReadError({
314 reason: "scanFailed",
315 // Bounded description; the squashed failure travels as the cause.
316 // Squashed, not the Cause tree: a full tree in a Defect field is
317 // the unbounded wire payload the bounded detail exists to avoid.
318 detail: "Server settings could not be read.",
319 cause: Cause.squash(cause),
320 }),
321 ),
322 );
323
324 const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
325 const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
326 const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
327
328 return [
329 { provider: "claude" as const, dir: claudeDir },
330 { provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") },
331 { provider: "opencode" as const, dir: yield* resolveOpenCodeDataDir() },
332 ];
333 });
334
335 /**
336 * Loads the persisted scan cache exactly once per process.
337 *
338 * `Effect.cached` makes concurrent first readers await the same load rather
339 * than each seeing a "loaded" flag set before the read finished and cold
340 * scanning against an empty cache.
341 */
342 const ensureScanCacheLoaded = yield* Effect.cached(
343 Effect.gen(function* () {
344 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
345 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
346 Effect.catchCause(() => Effect.succeed(null)),
347 );
348 if (document === null) return;
349 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
350 }),
351 );
352
353 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
354 if (!cacheDirty) return;
355 // Cleared only after the write lands, so a failed persist is retried on
356 // the next scan instead of leaving disk permanently stale.
357 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
358 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
359 Effect.map(() => {
360 cacheDirty = false;
361 }),
362 // A cache we cannot write is a slower next start, not a failed read.
363 Effect.catchCause(() => Effect.void),
364 );
365 });
366
367 /**
368 * Parses one transcript, reusing the cached result when it is unchanged.
369 *
370 * OpenCode's store runs in WAL mode, so its live tail is the sidecar WAL
371 * file: a hit is only valid when that is unchanged too, or a session written
372 * since the last checkpoint would keep serving stale usage.
373 */
374 const readFileRecords = (
375 filePath: string,
376 size: number,
377 mtimeMs: number,
378 provider: UsageProviderKind,
379 wal: OpenCodeWalIdentity | null,
380 ): Effect.Effect<readonly UsageRecord[]> =>
381 Effect.gen(function* () {
382 const cached = fileCache.get(filePath);
383 // Provider is part of the identity: if both providers were ever pointed
384 // at one directory, a hit parsed by the other parser must not be reused.
385 const walMatches =
386 (cached?.wal?.size ?? null) === (wal?.size ?? null) &&
387 (cached?.wal?.mtimeMs ?? null) === (wal?.mtimeMs ?? null);
388 if (
389 cached &&
390 cached.size === size &&
391 cached.mtimeMs === mtimeMs &&
392 cached.provider === provider &&
393 walMatches
394 ) {
395 return cached.records;
396 }
397
398 const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));
399 // A read failure is not an empty transcript: caching it under this
400 // (size, mtime) would silently drop the file's usage until it changes.
401 if (parsed === null) return [];
402 // Stored already de-duplicated within the file, which is 99% of all
403 // duplicates. The aggregator still runs the cross-file dedupe pass.
404 const records = dedupeWithinFile(parsed);
405
406 fileCache.set(filePath, {
407 size,
408 mtimeMs,
409 provider,
410 records,
411 ...(wal === null ? {} : { wal }),
412 });
413 cacheDirty = true;
414 return records;
415 });
416
417 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
418 if (input.sinceDay > input.untilDay) {
419 return yield* new UsageReadError({
420 reason: "invalidWindow",
421 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
422 });
423 }
424
425 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
426 if (input.resolution === "hour") {
427 const sinceTime =
428 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
429 const untilTime =
430 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
431 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
432 return yield* new UsageReadError({
433 reason: "invalidWindow",
434 detail: "Hourly usage requires valid sinceTime and untilTime instants",
435 });
436 }
437 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
438 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
439 const durationMs = untilTimeMs - sinceTimeMs;
440 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
441 return yield* new UsageReadError({
442 reason: "invalidWindow",
443 detail: "Hourly usage window must be greater than zero and at most 24 hours",
444 });
445 }
446 hourlyWindow = { sinceTimeMs, untilTimeMs };
447 }
448
449 const startedAtMs = yield* Clock.currentTimeMillis;
450 yield* ensureRates();
451 yield* ensureOpenCodeRates();
452 yield* ensureScanCacheLoaded;
453
454 const hostId = NodeOS.hostname();
455 // The home resolvers ask for `Path` themselves; satisfy them from the
456 // instance we already hold so `readSummary` stays context-free.
457 const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));
458 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
459 if (Option.isNone(windowStart)) {
460 return yield* new UsageReadError({
461 reason: "invalidWindow",
462 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
463 });
464 }
465 const windowStartMs =
466 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
467
468 // Always re-compose the served table, regardless of which source refreshed
469 // this pass: a LiteLLM refresh on its own clock must not drop the still
470 // valid OpenCode go/zen overlay (and vice versa).
471 const servedRates = mergeRateTables(litellmRates, openCodeRates);
472
473 const aggregator = new UsageAggregator({
474 timeZone: input.timeZone,
475 sinceDay: input.sinceDay,
476 untilDay: input.untilDay,
477 rates: servedRates,
478 resolution: input.resolution ?? "day",
479 ...hourlyWindow,
480 rates,
481 });
482
483 const sources: UsageSource[] = [];
484 const livePaths = new Set<string>();
485 const walkedRoots: string[] = [];
486
487 for (const { provider, dir } of dirs) {
488 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
489 const exists = yield* fileSystem
490 .exists(dir)
491 .pipe(Effect.catchCause(() => Effect.succeed(false)));
492
493 if (!exists) {
494 sources.push({
495 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
496 status: "missing",
497 scannedFiles: 0,
498 skippedFiles: 0,
499 malformedRecords: 0,
500 distinctSessions: 0,
501 message: "No transcript directory on this environment.",
502 });
503 continue;
504 }
505
506 walkedRoots.push(dir);
507 const files = yield* Effect.promise(() =>
508 provider === "opencode"
509 ? listOpenCodeDatabaseFiles(dir, windowStartMs)
510 : listTranscriptFiles(dir, windowStartMs),
511 );
512 let scannedFiles = 0;
513 let skippedFiles = 0;
514 // Distinct per directory. Buckets carry per-cell session counts, but a
515 // session spans days and models, so clients total this figure instead.
516 const sessionIds = new Set<string>();
517
518 for (const file of files) {
519 livePaths.add(file.path);
520 const wal = provider === "opencode" ? (file as OpenCodeStoreFile).wal : null;
521 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider, wal);
522 if (records.length === 0) {
523 skippedFiles += 1;
524 continue;
525 }
526 scannedFiles += 1;
527 for (const record of records) {
528 // Only sessions that contributed in-window count: the mtime slack
529 // admits boundary files whose records fall outside the range.
530 if (aggregator.add(record) && record.sessionId.length > 0) {
531 sessionIds.add(record.sessionId);
532 }
533 }
534 }
535
536 sources.push({
537 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
538 status: "ok",
539 scannedFiles,
540 skippedFiles,
541 malformedRecords: 0,
542 distinctSessions: sessionIds.size,
543 message: null,
544 });
545 }
546
547 const pruned = pruneScanCache(fileCache, {
548 livePaths,
549 walkedRoots,
550 windowStartMs,
551 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
552 });
553 if (pruned > 0) cacheDirty = true;
554 yield* persistScanCache();
555
556 const aggregated = aggregator.finish();
557 const readAt = yield* DateTime.now;
558 const finishedAtMs = yield* Clock.currentTimeMillis;
559
560 return {
561 contractVersion: USAGE_CONTRACT_VERSION,
562 readAt: DateTime.formatIso(readAt),
563 timeZone: input.timeZone,
564 sinceDay: input.sinceDay,
565 untilDay: input.untilDay,
566 buckets: aggregated.buckets,
567 sources,
568 pricing: {
569 status: ratesStatus,
570 source: PRICING_SOURCE_LABEL,
571 fetchedAt:
572 ratesFetchedAtMs === null
573 ? null
574 : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
575 knownModels: servedRates.size,
576 },
577 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
578 } satisfies UsageSummary;
579 });
580
581 return { readSummary } as const;
582});
583
584export const layer = Layer.effect(UsageService, make);