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

usageTranscriptReader.ts

154 lines4.6 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 type UsageRecord,
26} from "./usageTranscripts.ts";
27​
28export interface TranscriptFile {
29 readonly path: string;
30 readonly size: number;
31 readonly mtimeMs: number;
33​
34export interface TranscriptFileListing {
35 readonly files: readonly TranscriptFile[];
36 readonly rootStatus: "ok" | "missing" | "failed";
37 readonly failedPaths: number;
39​
40/**
41 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
42 *
43 * A missing root is distinct from a root that exists but cannot be read.
44 * Nested directory and entry failures are counted so callers can keep the
45 * files that were found without claiming complete coverage.
46 */
47export async function listTranscriptFiles(
48 root: string,
49 sinceMs: number,
50): Promise<TranscriptFileListing> {
51 const found: TranscriptFile[] = [];
52 let failedPaths = 0;
53 let rootStatus: TranscriptFileListing["rootStatus"] = "ok";
54​
55 const walk = async (dir: string): Promise<void> => {
56 let entries;
57 try {
58 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
59 } catch (error) {
60 if (dir === root) {
61 rootStatus = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "failed";
62 } else {
63 failedPaths += 1;
64 }
65 return;
66 }
67 for (const entry of entries) {
68 const child = NodePath.join(dir, entry.name);
69 if (entry.isDirectory()) {
70 await walk(child);
71 continue;
72 }
73 if (!entry.name.endsWith(".jsonl")) continue;
74 try {
75 const stats = await NodeFSP.stat(child);
76 if (stats.mtimeMs >= sinceMs) {
77 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
78 }
79 } catch {
80 failedPaths += 1;
81 }
82 }
83 };
84​
85 await walk(root);
86 return { files: found, rootStatus, failedPaths };
88​
89/**
90 * Filesystem identity of a directory, as `device:inode`.
91 *
92 * Used to tell "two servers reading the same transcript directory" apart from
93 * "two machines whose hostname and home path happen to match". Returns an empty
94 * string when the directory cannot be stat'd.
95 */
96export async function readDirectoryVolumeId(path: string): Promise<string> {
97 try {
98 const stats = await NodeFSP.stat(path);
99 return `${stats.dev}:${stats.ino}`;
100 } catch {
101 return "";
102 }
104​
105/**
106 * Streams one transcript and returns the usage records it contains, or `null`
107 * when the file could not be read.
108 *
109 * The distinction matters to the caller's cache: a genuinely empty transcript
110 * is a stable fact worth memoising, while a transient read failure memoised
111 * under the same `(size, mtime)` key would silently drop that file's usage
112 * until the file next changes.
113 *
114 * Codex carries the active model on `turn_context` lines that hold no usage of
115 * their own, so those still have to pass through the reducer to keep model
116 * attribution correct.
117 */
118export async function readTranscriptRecords(
119 filePath: string,
120 provider: UsageProviderKind,
121): Promise<readonly UsageRecord[] | null> {
122 const records: UsageRecord[] = [];
123 const codexState = initialCodexScanState();
124​
125 try {
126 const lines = NodeReadline.createInterface({
127 input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
128 crlfDelay: Infinity,
129 });
130​
131 for await (const line of lines) {
132 if (provider === "codex") {
133 if (
134 !mightCarryUsage(line, provider) &&
135 !line.includes('"turn_context"') &&
136 !line.includes('"session_meta"')
137 ) {
138 continue;
139 }
140 const record = parseCodexLine(line, codexState);
141 if (record !== null) records.push(record);
142 continue;
143 }
144​
145 if (!mightCarryUsage(line, provider)) continue;
146 const record = parseClaudeLine(line);
147 if (record !== null) records.push(record);
148 }
149 } catch {
150 return null;
151 }
152​
153 return records;