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

UsageService.ts

897 lines33.6 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) plus T3's canonical Devin ACP event logs. CLI usage covers turns
6 * driven outside T3 Code too; Devin ACP usage is limited to sessions driven by
7 * this server. Optional official account ACUs are fetched separately when a
8 * billing-capable Devin service credential is configured.
9 *
10 * Transcripts are append-only, so parsed records are memoised per file by
11 * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
12 * scans only reparse files that changed, and a file that merely grew resumes
13 * from its cached parse position so only the appended bytes are read.
14 *
15 * @module UsageService
16 */
17import * as NodeOS from "node:os";
18​
19import {
20 USAGE_CONTRACT_VERSION,
21 resolveProviderInstanceEnabled,
22 type ServerSettings as ServerSettingsValue,
23 type UsageAccountConsumption,
24 type UsageProviderKind,
25 type UsageSource,
26 type UsagePricing,
27 type UsageSummary,
28 type UsageSummaryInput,
29 UsageReadError,
30} from "@t3tools/contracts";
31import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
32import * as Cause from "effect/Cause";
33import * as Clock from "effect/Clock";
34import * as Context from "effect/Context";
35import * as DateTime from "effect/DateTime";
36import * as Deferred from "effect/Deferred";
37import * as Effect from "effect/Effect";
38import * as FileSystem from "effect/FileSystem";
39import * as Layer from "effect/Layer";
40import * as Option from "effect/Option";
41import * as Path from "effect/Path";
42import * as Result from "effect/Result";
43import * as Schema from "effect/Schema";
44import * as Semaphore from "effect/Semaphore";
45import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
46​
47import { ServerConfig } from "../config.ts";
48import { expandHomePath } from "../pathExpansion.ts";
49import * as ServerSettings from "../serverSettings.ts";
50import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";
51import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
52import { UsageAggregator } from "./usageAggregation.ts";
53import {
54 createOverrideRateTable,
55 parseProviderModelRateTable,
56 parseRateTable,
57 type ModelRate,
58 type RateTable,
59} from "./usagePricing.ts";
60import {
61 listProviderEventLogFiles,
62 listTranscriptFiles,
63 readDirectoryVolumeId,
64 readTranscriptRecords,
65} from "./usageTranscriptReader.ts";
66import {
67 decodeScanCache,
68 dedupeWithinFile,
69 encodeScanCache,
70 pruneScanCache,
71 type ScanCache,
72} from "./usageScanCache.ts";
73import type { UsageRecord } from "./usageTranscripts.ts";
74import { parseDevinAccountConsumptionPayload } from "./devinAccountUsage.ts";
75​
76const LITELLM_RATES_URL =
77 "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
78const DEVIN_RATES_SOURCE = "Devin CLI model catalog (local provider snapshot)";
79const DEVIN_ACCOUNT_API_BASE = "https://api.devin.ai/v3";
80const DEVIN_ACCOUNT_SOURCE = "Devin organization consumption API (ACUs)";
81const DEVIN_ACCOUNT_API_KEY_ENV_NAMES = ["DEVIN_API_KEY", "DEVIN_PERSONAL_ACCESS_TOKEN"] as const;
82const DEVIN_ACCOUNT_ORG_ENV_NAMES = ["DEVIN_ORG_ID", "DEVIN_ORGANIZATION_ID"] as const;
83const DEVIN_ACCOUNT_REQUEST_TIMEOUT_MS = 10_000;
84const DEVIN_ACCOUNT_CACHE_TTL_MS = 5 * 60 * 1_000;
85​
86function nonEmptyString(value: string | undefined): string | undefined {
87 const trimmed = value?.trim();
88 return trimmed && trimmed.length > 0 ? trimmed : undefined;
90​
91function findEnvironmentValue(
92 environment: NodeJS.ProcessEnv,
93 names: readonly string[],
94): string | undefined {
95 const wanted = new Set(names.map((name) => name.toUpperCase()));
96 for (const [name, value] of Object.entries(environment)) {
97 if (wanted.has(name.toUpperCase())) {
98 const resolved = nonEmptyString(value);
99 if (resolved !== undefined) return resolved;
100 }
101 }
102 return undefined;
104​
105function findDevinProviderEnvironmentValue(
106 settings: ServerSettingsValue,
107 names: readonly string[],
108): string | undefined {
109 const wanted = new Set(names.map((name) => name.toUpperCase()));
110 for (const instance of Object.values(settings.providerInstances)) {
111 if (String(instance.driver).toLowerCase() !== "devin") continue;
112 for (const variable of instance.environment ?? []) {
113 if (!wanted.has(variable.name.toUpperCase())) continue;
114 const resolved = nonEmptyString(variable.value);
115 if (resolved !== undefined) return resolved;
116 }
117 }
118 return undefined;
120​
121function isDevinEnabled(settings: ServerSettingsValue): boolean {
122 if (settings.providers.devin.enabled === true) return true;
123 return Object.values(settings.providerInstances).some(
124 (instance) =>
125 String(instance.driver).toLowerCase() === "devin" && resolveProviderInstanceEnabled(instance),
126 );
128​
129function accountConsumptionStatus(input: {
130 readonly status: UsageAccountConsumption["status"];
131 readonly message: string | null;
132 readonly fetchedAt?: string | null;
133 readonly totalAcus?: number;
134 readonly days?: UsageAccountConsumption["days"];
135}): UsageAccountConsumption {
136 return {
137 provider: "devin",
138 status: input.status,
139 source: DEVIN_ACCOUNT_SOURCE,
140 fetchedAt: input.fetchedAt ?? null,
141 totalAcus: input.totalAcus ?? 0,
142 days: input.days ?? [],
143 message: input.message,
144 };
146​
147function epochSecondsForDay(day: string, offsetDays: number): number | null {
148 const milliseconds = Date.parse(`${day}T00:00:00.000Z`);
149 if (!Number.isFinite(milliseconds)) return null;
150 return Math.floor((milliseconds + offsetDays * 24 * 60 * 60 * 1_000) / 1_000);
152​
153function selectAccountWindow(
154 parsed: ReturnType<typeof parseDevinAccountConsumptionPayload>,
155 input: UsageSummaryInput,
156): { readonly totalAcus: number; readonly days: UsageAccountConsumption["days"] } | null {
157 if (parsed === null) return null;
158 const days = parsed.days.filter((day) => day.day >= input.sinceDay && day.day <= input.untilDay);
159 return {
160 // If the endpoint returned no date rows, retain its required total. When
161 // rows are present, summing the selected rows avoids leaking an adjacent
162 // day from the one-day query padding used for Devin's PST billing boundary.
163 totalAcus:
164 parsed.days.length === 0 ? parsed.totalAcus : days.reduce((sum, day) => sum + day.acus, 0),
165 days,
166 };
168​
169/** Rates move rarely; a day-old table keeps the page working offline. */
170const RATES_TTL_MS = 24 * 60 * 60 * 1000;
171​
172/** An explicit refresh ignores the TTL, but not a table fetched this recently. */
173const RATES_REFRESH_FLOOR_MS = 60 * 1000;
174​
175/**
176 * Files are filtered by mtime before opening. The slack covers a session whose
177 * last write lands just before local midnight on the window's first day.
178 */
179const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;
180const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;
181​
182/** Longest window the UI offers, plus slack. Older entries are pruned. */
183const CACHE_RETENTION_DAYS = 90;
184​
185/** On-disk shape of the rate snapshot. */
186const RatesCacheFile = Schema.Struct({
187 fetchedAtMs: Schema.Number,
188 document: Schema.Unknown,
189});
190const decodeRatesCache = Schema.decodeUnknownEffect(
191 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
192);
193const encodeRatesCache = Schema.encodeEffect(
194 Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),
195);
196​
197/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */
198const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);
199const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);
200const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);
201const decodeProviderSnapshotJson = Schema.decodeUnknownEffect(
202 Schema.fromJsonString(
203 Schema.Struct({ driver: Schema.Literal("devin"), models: Schema.Array(Schema.Unknown) }),
204 ),
205);
206​
207export class UsageService extends Context.Service<
208 UsageService,
209 {
210 readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;
211 /** Refetches the rate table ahead of its TTL. See `ensureRates`. */
212 readonly refreshRates: Effect.Effect<UsagePricing>;
213 }
214>()("t3/usage/UsageService") {}
215​
216const EMPTY_PRICING: UsagePricing = {
217 status: "unavailable",
218 source: LITELLM_RATES_URL,
219 fetchedAt: null,
220 knownModels: 0,
221};
222​
223/** Empty summary, for suites that only need the RPC surface to resolve. */
224export const layerTest = Layer.succeed(
225 UsageService,
226 UsageService.of({
227 readSummary: (input) =>
228 Effect.succeed({
229 contractVersion: USAGE_CONTRACT_VERSION,
230 readAt: "1970-01-01T00:00:00.000Z",
231 timeZone: input.timeZone,
232 sinceDay: input.sinceDay,
233 untilDay: input.untilDay,
234 buckets: [],
235 sources: [],
236 pricing: EMPTY_PRICING,
237 scanDurationMs: 0,
238 }),
239 refreshRates: Effect.succeed(EMPTY_PRICING),
240 }),
241);
242​
243export const make = Effect.gen(function* () {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const config = yield* ServerConfig;
247 const settingsService = yield* ServerSettings.ServerSettingsService;
248 const httpClient = yield* HttpClient.HttpClient;
249 const hostEnvironment = yield* HostProcessEnvironment;
250​
251 const fileCache: ScanCache = new Map();
252 let cacheDirty = false;
253​
254 const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
255 const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");
256 let liteLlmRates: RateTable = new Map();
257 let devinRates: RateTable = new Map();
258 let ratesFetchedAtMs: number | null = null;
259 let ratesStatus: UsagePricing["status"] = "unavailable";
260 // One fetch at a time. A burst of refreshes from several clients waits on
261 // the first fetch and then sees a table young enough to skip its own.
262 const ratesLock = yield* Semaphore.make(1);
263​
264 const pricing = (): UsagePricing => ({
265 status: ratesStatus,
266 source:
267 devinRates.size > 0 ? `${LITELLM_RATES_URL} + ${DEVIN_RATES_SOURCE}` : LITELLM_RATES_URL,
268 fetchedAt:
269 ratesFetchedAtMs === null ? null : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),
270 knownModels: liteLlmRates.size + devinRates.size,
271 });
272 const devinAccountCache = new Map<
273 string,
274 { readonly fetchedAtMs: number; readonly value: UsageAccountConsumption }
275 >();
276​
277 /**
278 * Loads the LiteLLM rate table, preferring a fresh copy and falling back to
279 * the on-disk snapshot. With neither, every model reports as unpriced rather
280 * than the page failing. `force` refetches inside the TTL so a model that
281 * LiteLLM added since the last fetch gets priced now.
282 */
283 const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) {
284 const now = yield* Clock.currentTimeMillis;
285 const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS;
286 if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return;
287​
288 if (ratesFetchedAtMs === null) {
289 const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(
290 Effect.flatMap((raw) => decodeRatesCache(raw)),
291 Effect.catchCause(() => Effect.succeed(null)),
292 );
293 if (fromDisk !== null) {
294 const parsed = parseRateTable(fromDisk.document);
295 if (parsed.size > 0) {
296 liteLlmRates = parsed;
297 ratesFetchedAtMs = fromDisk.fetchedAtMs;
298 ratesStatus = "cached";
299 if (now - fromDisk.fetchedAtMs < maxAgeMs) return;
300 }
301 }
302 }
303​
304 const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(
305 Effect.flatMap(HttpClientResponse.filterStatusOk),
306 Effect.flatMap((response) => response.json),
307 Effect.timeout(10_000),
308 Effect.catchCause(() => Effect.succeed(null)),
309 );
310 if (fetched === null) {
311 // The refresh failed; whatever we are serving is now past its TTL and
312 // must not keep claiming to be fresh.
313 if (liteLlmRates.size > 0) ratesStatus = "cached";
314 return;
315 }
316​
317 const parsed = parseRateTable(fetched);
318 if (parsed.size === 0) return;
319​
320 liteLlmRates = parsed;
321 ratesFetchedAtMs = now;
322 ratesStatus = "fresh";
323​
324 yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
325 Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
326 Effect.catchCause(() => Effect.void),
327 );
328 });
329​
330 const ensureRates = (force: boolean) => ratesLock.withPermit(loadRates(force));
331​
332 const refreshRates = ensureRates(true).pipe(
333 Effect.map(pricing),
334 Effect.withSpan("UsageService.refreshRates"),
335 );
336​
337 /**
338 * Provider probes persist their model catalog in the status-cache directory.
339 * Retain Devin's advertised per-million prices for Devin records so
340 * canonical ACP records can be priced even when the public LiteLLM table
341 * does not yet contain a newly launched Devin model.
342 */
343 const ensureDevinRates = Effect.fn("UsageService.ensureDevinRates")(function* () {
344 const entries = yield* fileSystem
345 .readDirectory(config.providerStatusCacheDir)
346 .pipe(Effect.catchCause(() => Effect.succeed([] as ReadonlyArray<string>)));
347 const merged = new Map<string, ModelRate>();
348 for (const entry of entries) {
349 if (!entry.toLowerCase().endsWith(".json")) continue;
350 const raw = yield* fileSystem
351 .readFileString(path.join(config.providerStatusCacheDir, entry))
352 .pipe(Effect.catchCause(() => Effect.succeed(null)));
353 if (raw === null) continue;
354 const document = yield* decodeProviderSnapshotJson(raw).pipe(Effect.option);
355 if (Option.isNone(document)) continue;
356 for (const [model, rate] of parseProviderModelRateTable(document.value)) {
357 merged.set(model, rate);
358 }
359 }
360 devinRates = merged;
361 });
362​
363 /**
364 * Optionally reads official account-level Devin ACUs. The normal CLI login
365 * token is intentionally not inspected or reused: Devin's organization
366 * consumption endpoint requires a separately provisioned service credential
367 * with billing permission. Missing credentials simply produce an explicit
368 * not-configured state and never make the usage scan fail.
369 */
370 const readDevinAccountUsage = Effect.fn("UsageService.readDevinAccountUsage")(function* (
371 input: UsageSummaryInput,
372 settings: ServerSettingsValue,
373 ) {
374 if (!isDevinEnabled(settings)) return undefined;
375​
376 const apiKey =
377 findDevinProviderEnvironmentValue(settings, DEVIN_ACCOUNT_API_KEY_ENV_NAMES) ??
378 findEnvironmentValue(hostEnvironment, DEVIN_ACCOUNT_API_KEY_ENV_NAMES);
379 const organizationId =
380 findDevinProviderEnvironmentValue(settings, DEVIN_ACCOUNT_ORG_ENV_NAMES) ??
381 findEnvironmentValue(hostEnvironment, DEVIN_ACCOUNT_ORG_ENV_NAMES);
382 if (apiKey === undefined || organizationId === undefined) {
383 const missing = [
384 apiKey === undefined ? "DEVIN_API_KEY" : null,
385 organizationId === undefined ? "DEVIN_ORG_ID" : null,
386 ].filter((name): name is string => name !== null);
387 return accountConsumptionStatus({
388 status: "notConfigured",
389 message: `Optional account ACU data needs ${missing.join(" and ")} as Devin provider environment variables.`,
390 });
391 }
392​
393 const timeAfter = epochSecondsForDay(input.sinceDay, -1);
394 const timeBefore = epochSecondsForDay(input.untilDay, 2);
395 if (timeAfter === null || timeBefore === null) {
396 return accountConsumptionStatus({
397 status: "failed",
398 message: "The requested usage window is not a valid date range.",
399 });
400 }
401​
402 const cacheKey = `${organizationId}\u0000${input.sinceDay}\u0000${input.untilDay}`;
403 const now = yield* Clock.currentTimeMillis;
404 const cached = devinAccountCache.get(cacheKey);
405 if (cached !== undefined && now - cached.fetchedAtMs < DEVIN_ACCOUNT_CACHE_TTL_MS) {
406 return cached.value;
407 }
408​
409 const endpoint = new URL(
410 `${DEVIN_ACCOUNT_API_BASE}/organizations/${encodeURIComponent(organizationId)}/consumption/daily`,
411 );
412 endpoint.searchParams.set("time_after", String(timeAfter));
413 endpoint.searchParams.set("time_before", String(timeBefore));
414 const request = HttpClientRequest.get(endpoint.toString()).pipe(
415 HttpClientRequest.acceptJson,
416 HttpClientRequest.bearerToken(apiKey),
417 );
418 const responseResult = yield* httpClient
419 .execute(request)
420 .pipe(Effect.timeout(DEVIN_ACCOUNT_REQUEST_TIMEOUT_MS), Effect.result);
421 if (Result.isFailure(responseResult)) {
422 const value = accountConsumptionStatus({
423 status: "failed",
424 message: "Devin account consumption could not be reached.",
425 });
426 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
427 return value;
428 }
429​
430 const response = responseResult.success;
431 if (response.status === 401 || response.status === 403) {
432 const value = accountConsumptionStatus({
433 status: "forbidden",
434 message: "The Devin API key lacks organization consumption permission.",
435 });
436 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
437 return value;
438 }
439 if (response.status < 200 || response.status >= 300) {
440 const value = accountConsumptionStatus({
441 status: "failed",
442 message:
443 response.status === 404
444 ? "Devin organization consumption is unavailable for this account."
445 : `Devin account consumption returned HTTP ${response.status}.`,
446 });
447 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
448 return value;
449 }
450​
451 const payloadResult = yield* response.json.pipe(Effect.result);
452 if (Result.isFailure(payloadResult)) {
453 const value = accountConsumptionStatus({
454 status: "failed",
455 message: "Devin returned an unreadable account consumption response.",
456 });
457 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
458 return value;
459 }
460 const parsed = selectAccountWindow(
461 parseDevinAccountConsumptionPayload(payloadResult.success),
462 input,
463 );
464 if (parsed === null) {
465 const value = accountConsumptionStatus({
466 status: "failed",
467 message: "Devin returned an invalid account consumption response.",
468 });
469 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
470 return value;
471 }
472​
473 const value = accountConsumptionStatus({
474 status: "available",
475 message: null,
476 fetchedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),
477 totalAcus: parsed.totalAcus,
478 days: parsed.days,
479 });
480 devinAccountCache.set(cacheKey, { fetchedAtMs: now, value });
481 return value;
482 });
483​
484 /**
485 * Claude's config dir is the home itself when overridden, but a default
486 * install nests transcripts under `~/.claude/projects`. Probe both.
487 */
488 const resolveClaudeTranscriptDir = (homePath: string) =>
489 Effect.gen(function* () {
490 const nested = path.join(homePath, ".claude", "projects");
491 const nestedExists = yield* fileSystem
492 .exists(nested)
493 .pipe(Effect.catchCause(() => Effect.succeed(false)));
494 return nestedExists ? nested : path.join(homePath, "projects");
495 });
496​
497 // A settings failure must not silently discard custom rates or transcript homes.
498 const readSettings = settingsService.getSettings.pipe(
499 Effect.catchCause(
500 (cause) =>
501 new UsageReadError({
502 reason: "scanFailed",
503 detail: "Server settings could not be read.",
504 cause: Cause.squash(cause),
505 }),
506 ),
507 );
508​
509 /** Resolves the transcript directory for each provider. */
510 const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* (
511 settings: ServerSettingsValue,
512 ) {
513 const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
514 const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
515 const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
516 // Grok Settings only expose the binary path; home is `$GROK_HOME` or `~/.grok`.
517 // Empty/whitespace GROK_HOME must fall back: coalescing alone would scan cwd.
518 const grokHomeEnv = hostEnvironment["GROK_HOME"]?.trim() ?? "";
519 const grokHome =
520 grokHomeEnv.length > 0
521 ? path.resolve(expandHomePath(grokHomeEnv))
522 : path.join(NodeOS.homedir(), ".grok");
523​
524 return [
525 { provider: "claude" as const, dir: claudeDir },
526 { provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") },
527 {
528 provider: "grok" as const,
529 dir: path.join(grokHome, "sessions"),
530 fileName: "updates.jsonl",
531 },
532 {
533 provider: "devin" as const,
534 dir: config.providerLogsDir,
535 eventLog: true as const,
536 },
537 ];
538 });
539​
540 /**
541 * Loads the persisted scan cache exactly once per process.
542 *
543 * `Effect.cached` makes concurrent first readers await the same load rather
544 * than each seeing a "loaded" flag set before the read finished and cold
545 * scanning against an empty cache.
546 */
547 const ensureScanCacheLoaded = yield* Effect.cached(
548 Effect.gen(function* () {
549 const document = yield* fileSystem.readFileString(scanCachePath).pipe(
550 Effect.flatMap((raw) => decodeScanCacheFile(raw)),
551 Effect.catchCause(() => Effect.succeed(null)),
552 );
553 if (document === null) return;
554 for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);
555 }),
556 );
557​
558 const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
559 if (!cacheDirty) return;
560 // Cleared only after the write lands, so a failed persist is retried on
561 // the next scan instead of leaving disk permanently stale.
562 yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(
563 Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
564 Effect.map(() => {
565 cacheDirty = false;
566 }),
567 // A cache we cannot write is a slower next start, not a failed read.
568 Effect.catchCause(() => Effect.void),
569 );
570 });
571​
572 /**
573 * Parses one transcript, reusing the cached result when it is unchanged.
574 *
575 * A file that only grew re-parses from the cached position, so an actively
576 * written multi-hundred-megabyte rollout costs its appended bytes per scan
577 * rather than a full re-read. The reader verifies the position's guard bytes
578 * and silently restarts from byte 0 when they no longer match.
579 */
580 const readFileRecords = (
581 filePath: string,
582 size: number,
583 mtimeMs: number,
584 provider: UsageProviderKind,
585 ): Effect.Effect<readonly UsageRecord[]> =>
586 Effect.gen(function* () {
587 const cached = fileCache.get(filePath);
588 // Provider is part of the identity: if both providers were ever pointed
589 // at one directory, a hit parsed by the other parser must not be reused.
590 if (
591 cached &&
592 cached.size === size &&
593 cached.mtimeMs === mtimeMs &&
594 cached.provider === provider
595 ) {
596 return cached.tailRecords.length === 0
597 ? cached.records
598 : [...cached.records, ...cached.tailRecords];
599 }
600​
601 // Only a strictly grown file may resume. Same size with a new mtime, or
602 // a shrunken file, means rewritten content; re-parse it whole.
603 const resumeFrom =
604 cached !== undefined && cached.provider === provider && size > cached.size
605 ? cached.position
606 : undefined;
607​
608 const parsed = yield* Effect.promise(() =>
609 readTranscriptRecords(filePath, provider, resumeFrom),
610 );
611 // A read failure is not an empty transcript: caching it under this
612 // (size, mtime) would silently drop the file's usage until it changes.
613 if (parsed === null) return [];
614​
615 // Stored already de-duplicated within the file, which is 99% of all
616 // duplicates. The aggregator still runs the cross-file dedupe pass. One
617 // seen set spans the cached base, the new lines, and the tail so a
618 // resumed parse dedupes exactly like a full one.
619 const base = parsed.resumed && cached !== undefined ? cached.records : [];
620 const seen = new Set<string>();
621 const records = dedupeWithinFile([...base, ...parsed.records], seen);
622 const tailRecords = dedupeWithinFile(parsed.tailRecords, seen);
623​
624 fileCache.set(filePath, {
625 size,
626 mtimeMs,
627 provider,
628 records,
629 tailRecords,
630 position: parsed.position,
631 });
632 cacheDirty = true;
633 return tailRecords.length === 0 ? records : [...records, ...tailRecords];
634 });
635​
636 /** One provider directory's walk and parse, before rates are involved. */
637 interface ScannedDir {
638 readonly provider: UsageProviderKind;
639 readonly dir: string;
640 readonly volumeId: string;
641 /** Parsed records per file, or `null` when the directory does not exist. */
642 readonly files:
643 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
644 | null;
645 }
646​
647 const collectDirs = Effect.fn("UsageService.collectDirs")(function* (
648 windowStartMs: number,
649 settings: ServerSettingsValue,
650 ) {
651 // The home resolvers ask for `Path` themselves; satisfy them from the
652 // instance we already hold so the scan stays context-free.
653 const dirs = yield* resolveTranscriptDirs(settings).pipe(
654 Effect.provideService(Path.Path, path),
655 );
656 const scanned: ScannedDir[] = [];
657 for (const { provider, dir, fileName, eventLog } of dirs) {
658 const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
659 const exists = yield* fileSystem
660 .exists(dir)
661 .pipe(Effect.catchCause(() => Effect.succeed(false)));
662 if (!exists) {
663 scanned.push({ provider, dir, volumeId, files: null });
664 continue;
665 }
666 const files = yield* Effect.promise(() =>
667 eventLog
668 ? listProviderEventLogFiles(dir, "events", windowStartMs)
669 : listTranscriptFiles(
670 dir,
671 windowStartMs,
672 fileName === undefined ? undefined : { fileName },
673 ),
674 );
675 const parsedFiles: { path: string; records: readonly UsageRecord[] }[] = [];
676 for (const file of files) {
677 const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);
678 parsedFiles.push({ path: file.path, records });
679 }
680 scanned.push({ provider, dir, volumeId, files: parsedFiles });
681 }
682 return scanned;
683 });
684​
685 const scanSummary = Effect.fn("UsageService.scanSummary")(function* (
686 input: UsageSummaryInput,
687 settings: ServerSettingsValue,
688 ) {
689 if (input.sinceDay > input.untilDay) {
690 return yield* new UsageReadError({
691 reason: "invalidWindow",
692 detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,
693 });
694 }
695​
696 let hourlyWindow: { readonly sinceTimeMs: number; readonly untilTimeMs: number } | null = null;
697 if (input.resolution === "hour") {
698 const sinceTime =
699 input.sinceTime === undefined ? Option.none() : DateTime.make(input.sinceTime);
700 const untilTime =
701 input.untilTime === undefined ? Option.none() : DateTime.make(input.untilTime);
702 if (Option.isNone(sinceTime) || Option.isNone(untilTime)) {
703 return yield* new UsageReadError({
704 reason: "invalidWindow",
705 detail: "Hourly usage requires valid sinceTime and untilTime instants",
706 });
707 }
708 const sinceTimeMs = DateTime.toEpochMillis(sinceTime.value);
709 const untilTimeMs = DateTime.toEpochMillis(untilTime.value);
710 const durationMs = untilTimeMs - sinceTimeMs;
711 if (durationMs <= 0 || durationMs > MAX_HOURLY_WINDOW_MS) {
712 return yield* new UsageReadError({
713 reason: "invalidWindow",
714 detail: "Hourly usage window must be greater than zero and at most 24 hours",
715 });
716 }
717 hourlyWindow = { sinceTimeMs, untilTimeMs };
718 }
719​
720 const startedAtMs = yield* Clock.currentTimeMillis;
721 yield* ensureScanCacheLoaded;
722​
723 const hostId = NodeOS.hostname();
724 yield* ensureDevinRates();
725 const settingsForAccount = yield* settingsService.getSettings.pipe(
726 Effect.catchCause(() => Effect.succeed(null)),
727 );
728 const accountUsage =
729 settingsForAccount === null
730 ? undefined
731 : yield* readDevinAccountUsage(input, settingsForAccount);
732 const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);
733 if (Option.isNone(windowStart)) {
734 return yield* new UsageReadError({
735 reason: "invalidWindow",
736 detail: `sinceDay '${input.sinceDay}' is not a valid date`,
737 });
738 }
739 const windowStartMs =
740 (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;
741​
742 // Pricing only matters once records are aggregated, so the rate table
743 // loads while transcripts stream instead of gating them: a cold rates
744 // fetch on a slow network no longer delays the scan by its own timeout.
745 const [, scannedDirs] = yield* Effect.all(
746 [ensureRates(false), collectDirs(windowStartMs, settings)],
747 { concurrency: 2 },
748 );
749​
750 const aggregator = new UsageAggregator({
751 timeZone: input.timeZone,
752 sinceDay: input.sinceDay,
753 untilDay: input.untilDay,
754 resolution: input.resolution ?? "day",
755 ...hourlyWindow,
756 rates: liteLlmRates,
757 providerRates: { devin: new Map([...liteLlmRates, ...devinRates]) },
758 priceOverrides: createOverrideRateTable(settings.usagePriceOverrides),
759 });
760​
761 const sources: UsageSource[] = [];
762 const livePaths = new Set<string>();
763 const walkedRoots: string[] = [];
764​
765 for (const { provider, dir, volumeId, files } of scannedDirs) {
766 if (files === null) {
767 sources.push({
768 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
769 status: "missing",
770 scannedFiles: 0,
771 skippedFiles: 0,
772 malformedRecords: 0,
773 distinctSessions: 0,
774 message: "No transcript directory on this environment.",
775 });
776 continue;
777 }
778​
779 walkedRoots.push(dir);
780 let scannedFiles = 0;
781 let skippedFiles = 0;
782 // Distinct per directory. Buckets carry per-cell session counts, but a
783 // session spans days and models, so clients total this figure instead.
784 const sessionIds = new Set<string>();
785​
786 for (const file of files) {
787 livePaths.add(file.path);
788 if (file.records.length === 0) {
789 skippedFiles += 1;
790 continue;
791 }
792 scannedFiles += 1;
793 for (const record of file.records) {
794 // Only sessions that contributed in-window count: the mtime slack
795 // admits boundary files whose records fall outside the range.
796 if (aggregator.add(record) && record.sessionId.length > 0) {
797 sessionIds.add(record.sessionId);
798 }
799 }
800 }
801​
802 sources.push({
803 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },
804 status: "ok",
805 scannedFiles,
806 skippedFiles,
807 malformedRecords: 0,
808 distinctSessions: sessionIds.size,
809 message:
810 provider === "devin"
811 ? "Devin ACP usage is captured from this T3 server's local event logs."
812 : null,
813 });
814 }
815​
816 const pruned = pruneScanCache(fileCache, {
817 livePaths,
818 walkedRoots,
819 windowStartMs,
820 retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,
821 });
822 if (pruned > 0) cacheDirty = true;
823 yield* persistScanCache();
824​
825 const aggregated = aggregator.finish();
826 const readAt = yield* DateTime.now;
827 const finishedAtMs = yield* Clock.currentTimeMillis;
828​
829 return {
830 contractVersion: USAGE_CONTRACT_VERSION,
831 readAt: DateTime.formatIso(readAt),
832 timeZone: input.timeZone,
833 sinceDay: input.sinceDay,
834 untilDay: input.untilDay,
835 buckets: aggregated.buckets,
836 sources,
837 pricing: pricing(),
838 ...(accountUsage === undefined ? {} : { accountUsage }),
839 scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),
840 } satisfies UsageSummary;
841 });
842​
843 /**
844 * In-flight scans by window and custom prices, so concurrent identical requests (the usage
845 * page open on two clients at once) share one scan instead of racing over
846 * the same corpus twice.
847 */
848 const inflightScans = new Map<string, Deferred.Deferred<UsageSummary, UsageReadError>>();
849​
850 const scanKey = (
851 input: UsageSummaryInput,
852 priceOverrides: ServerSettingsValue["usagePriceOverrides"],
853 ): string =>
854 JSON.stringify([
855 input.timeZone,
856 input.sinceDay,
857 input.untilDay,
858 input.resolution ?? "day",
859 input.sinceTime ?? null,
860 input.untilTime ?? null,
861 priceOverrides,
862 ]);
863​
864 const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {
865 const settings = yield* readSettings;
866 const key = scanKey(input, settings.usagePriceOverrides);
867 const deferred = yield* Effect.uninterruptible(
868 Effect.gen(function* () {
869 const existing = inflightScans.get(key);
870 if (existing !== undefined) return existing;
871​
872 // Enrollment and detached-fiber creation must be atomic. Otherwise a
873 // canceled first caller can leave a Deferred with no scan to finish it.
874 const created = Deferred.makeUnsafe<UsageSummary, UsageReadError>();
875 inflightScans.set(key, created);
876 // Detached so one departing client cannot tear the scan out from under
877 // the fibers awaiting it; a finished scan warms the cache either way.
878 yield* scanSummary(input, settings).pipe(
879 Effect.onExit((exit) =>
880 Effect.sync(() => inflightScans.delete(key)).pipe(
881 Effect.andThen(Deferred.done(created, exit)),
882 ),
883 ),
884 Effect.forkDetach,
885 );
886 return created;
887 }),
888 );
889 // Waiting stays interruptible. The detached scan continues for other
890 // callers and still warms the cache if this caller leaves.
891 return yield* Deferred.await(deferred);
892 });
893​
894 return { readSummary, refreshRates } as const;
895});
896​
897export const layer = Layer.effect(UsageService, make);