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

usageTranscriptReader.ts

158 lines4.7 KB

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 parseGrokLine,
26 type UsageRecord,
27} from "./usageTranscripts.ts";
28​
29export interface TranscriptFile {
30 readonly path: string;
31 readonly size: number;
32 readonly mtimeMs: number;
34​
35/**
36 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
37 *
38 * Errors on individual entries are swallowed: session files rotate and get
39 * removed while the walk is in flight, and a partial listing is far better than
40 * failing the page.
41 *
42 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
43 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
44 * never carry usage, so the basename filter keeps a cold scan off those files.
45 */
46export async function listTranscriptFiles(
47 root: string,
48 sinceMs: number,
49 options?: { readonly fileName?: string },
50): Promise<readonly TranscriptFile[]> {
51 const found: TranscriptFile[] = [];
52 const fileName = options?.fileName;
53​
54 const walk = async (dir: string): Promise<void> => {
55 let entries;
56 try {
57 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
58 } catch {
59 return;
60 }
61 for (const entry of entries) {
62 const child = NodePath.join(dir, entry.name);
63 if (entry.isDirectory()) {
64 await walk(child);
65 continue;
66 }
67 if (fileName !== undefined) {
68 if (entry.name !== fileName) continue;
69 } else if (!entry.name.endsWith(".jsonl")) {
70 continue;
71 }
72 try {
73 const stats = await NodeFSP.stat(child);
74 if (stats.mtimeMs >= sinceMs) {
75 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
76 }
77 } catch {
78 // Vanished between readdir and stat.
79 }
80 }
81 };
82​
83 await walk(root);
84 return found;
86​
87/**
88 * Filesystem identity of a directory, as `device:inode`.
89 *
90 * Used to tell "two servers reading the same transcript directory" apart from
91 * "two machines whose hostname and home path happen to match". Returns an empty
92 * string when the directory cannot be stat'd.
93 */
94export async function readDirectoryVolumeId(path: string): Promise<string> {
95 try {
96 const stats = await NodeFSP.stat(path);
97 return `${stats.dev}:${stats.ino}`;
98 } catch {
99 return "";
100 }
102​
103/**
104 * Streams one transcript and returns the usage records it contains, or `null`
105 * when the file could not be read.
106 *
107 * The distinction matters to the caller's cache: a genuinely empty transcript
108 * is a stable fact worth memoising, while a transient read failure memoised
109 * under the same `(size, mtime)` key would silently drop that file's usage
110 * until the file next changes.
111 *
112 * Codex carries the active model on `turn_context` lines that hold no usage of
113 * their own, so those still have to pass through the reducer to keep model
114 * attribution correct.
115 */
116export async function readTranscriptRecords(
117 filePath: string,
118 provider: UsageProviderKind,
119): Promise<readonly UsageRecord[] | null> {
120 const records: UsageRecord[] = [];
121 const codexState = initialCodexScanState();
122​
123 try {
124 const lines = NodeReadline.createInterface({
125 input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
126 crlfDelay: Infinity,
127 });
128​
129 for await (const line of lines) {
130 if (provider === "codex") {
131 if (
132 !mightCarryUsage(line, provider) &&
133 !line.includes('"turn_context"') &&
134 !line.includes('"session_meta"')
135 ) {
136 continue;
137 }
138 const record = parseCodexLine(line, codexState);
139 if (record !== null) records.push(record);
140 continue;
141 }
142​
143 if (provider === "grok") {
144 if (!mightCarryUsage(line, provider)) continue;
145 for (const grokRecord of parseGrokLine(line)) records.push(grokRecord);
146 continue;
147 }
148​
149 if (!mightCarryUsage(line, provider)) continue;
150 const record = parseClaudeLine(line);
151 if (record !== null) records.push(record);
152 }
153 } catch {
154 return null;
155 }
156​
157 return records;