Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Raw filesystem access for transcript scanning.
4 *
5 * Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
6 * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
7 * across ~1,500 files, and `readline` over a read stream is roughly an order of
8 * magnitude cheaper than materialising each file. The equivalent Effect stream
9 * pipeline is idiomatic but not fast enough to sit behind a page load.
10 *
11 * @module usageTranscriptReader
12 */
13import * as NodeFS from "node:fs";
14import * as NodeFSP from "node:fs/promises";
15import * as NodePath from "node:path";
16import * as NodeReadline from "node:readline";
17
18import type { UsageProviderKind } from "@t3tools/contracts";
19
20import {
21 initialCodexScanState,
22 mightCarryUsage,
23 parseClaudeLine,
24 parseCodexLine,
25 type UsageRecord,
26} from "./usageTranscripts.ts";
27
28export interface TranscriptFile {
29 readonly path: string;
30 readonly size: number;
31 readonly mtimeMs: number;
32}
33
34/**
35 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
36 *
37 * Errors on individual entries are swallowed: session files rotate and get
38 * removed while the walk is in flight, and a partial listing is far better than
39 * failing the page.
40 */
41export async function listTranscriptFiles(
42 root: string,
43 sinceMs: number,
44): Promise<readonly TranscriptFile[]> {
45 const found: TranscriptFile[] = [];
46
47 const walk = async (dir: string): Promise<void> => {
48 let entries;
49 try {
50 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
51 } catch {
52 return;
53 }
54 for (const entry of entries) {
55 const child = NodePath.join(dir, entry.name);
56 if (entry.isDirectory()) {
57 await walk(child);
58 continue;
59 }
60 if (!entry.name.endsWith(".jsonl")) continue;
61 try {
62 const stats = await NodeFSP.stat(child);
63 if (stats.mtimeMs >= sinceMs) {
64 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
65 }
66 } catch {
67 // Vanished between readdir and stat.
68 }
69 }
70 };
71
72 await walk(root);
73 return found;
74}
75
76/**
77 * Filesystem identity of a directory, as `device:inode`.
78 *
79 * Used to tell "two servers reading the same transcript directory" apart from
80 * "two machines whose hostname and home path happen to match". Returns an empty
81 * string when the directory cannot be stat'd.
82 */
83export async function readDirectoryVolumeId(path: string): Promise<string> {
84 try {
85 const stats = await NodeFSP.stat(path);
86 return `${stats.dev}:${stats.ino}`;
87 } catch {
88 return "";
89 }
90}
91
92/**
93 * Streams one transcript and returns the usage records it contains, or `null`
94 * when the file could not be read.
95 *
96 * The distinction matters to the caller's cache: a genuinely empty transcript
97 * is a stable fact worth memoising, while a transient read failure memoised
98 * under the same `(size, mtime)` key would silently drop that file's usage
99 * until the file next changes.
100 *
101 * Codex carries the active model on `turn_context` lines that hold no usage of
102 * their own, so those still have to pass through the reducer to keep model
103 * attribution correct.
104 */
105export async function readTranscriptRecords(
106 filePath: string,
107 provider: UsageProviderKind,
108): Promise<readonly UsageRecord[] | null> {
109 const records: UsageRecord[] = [];
110 const codexState = initialCodexScanState();
111
112 try {
113 const lines = NodeReadline.createInterface({
114 input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
115 crlfDelay: Infinity,
116 });
117
118 for await (const line of lines) {
119 if (provider === "codex") {
120 if (
121 !mightCarryUsage(line, provider) &&
122 !line.includes('"turn_context"') &&
123 !line.includes('"session_meta"')
124 ) {
125 continue;
126 }
127 const record = parseCodexLine(line, codexState);
128 if (record !== null) records.push(record);
129 continue;
130 }
131
132 if (!mightCarryUsage(line, provider)) continue;
133 const record = parseClaudeLine(line);
134 if (record !== null) records.push(record);
135 }
136 } catch {
137 return null;
138 }
139
140 return records;
141}