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

usageTranscriptReader.ts

238 lines7.3 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";
17import * as NodeSqlite from "node:sqlite";
18​
19import type { UsageProviderKind } from "@t3tools/contracts";
20​
21import {
22 initialCodexScanState,
23 mightCarryUsage,
24 parseClaudeLine,
25 parseCodexLine,
26 parseOpenCodeMessage,
27 type UsageRecord,
28} from "./usageTranscripts.ts";
29​
30export interface TranscriptFile {
31 readonly path: string;
32 readonly size: number;
33 readonly mtimeMs: number;
35​
36/**
37 * Identity of an OpenCode WAL sidecar file. OpenCode runs its session store in
38 * WAL mode, so fresh writes live in `opencode.db-wal` until a checkpoint folds
39 * them into the main file; both must be part of any cache identity or a live
40 * session is served stale.
41 */
42export interface OpenCodeWalIdentity {
43 readonly size: number;
44 readonly mtimeMs: number;
46​
47/** OpenCode's store is a single SQLite file; the WAL is its live tail. */
48export interface OpenCodeStoreFile extends TranscriptFile {
49 readonly wal: OpenCodeWalIdentity | null;
51​
52/**
53 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
54 *
55 * Errors on individual entries are swallowed: session files rotate and get
56 * removed while the walk is in flight, and a partial listing is far better than
57 * failing the page.
58 */
59export async function listTranscriptFiles(
60 root: string,
61 sinceMs: number,
62): Promise<readonly TranscriptFile[]> {
63 const found: TranscriptFile[] = [];
64​
65 const walk = async (dir: string): Promise<void> => {
66 let entries;
67 try {
68 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
69 } catch {
70 return;
71 }
72 for (const entry of entries) {
73 const child = NodePath.join(dir, entry.name);
74 if (entry.isDirectory()) {
75 await walk(child);
76 continue;
77 }
78 if (!entry.name.endsWith(".jsonl")) continue;
79 try {
80 const stats = await NodeFSP.stat(child);
81 if (stats.mtimeMs >= sinceMs) {
82 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
83 }
84 } catch {
85 // Vanished between readdir and stat.
86 }
87 }
88 };
89​
90 await walk(root);
91 return found;
93​
94/**
95 * Lists OpenCode's SQLite session store under `root`, if present.
96 *
97 * A single `opencode.db` file replaces the transcript directory the other
98 * providers use. Its mtime alone does not reflect a live session: WAL-mode
99 * writes land in `opencode.db-wal` first, so the file is admitted when either
100 * the main file or its WAL was touched inside the window. The WAL identity
101 * rides along so the caller can cache on the store's true state.
102 */
103export async function listOpenCodeDatabaseFiles(
104 root: string,
105 sinceMs: number,
106): Promise<readonly OpenCodeStoreFile[]> {
107 const dbPath = NodePath.join(root, "opencode.db");
108 let dbStats;
109 try {
110 dbStats = await NodeFSP.stat(dbPath);
111 } catch {
112 return [];
113 }
114​
115 let wal: OpenCodeWalIdentity | null = null;
116 try {
117 const walStats = await NodeFSP.stat(`${dbPath}-wal`);
118 wal = { size: walStats.size, mtimeMs: walStats.mtimeMs };
119 } catch {
120 // No sidecar (yet); a checkpointed store is complete without one.
121 }
122​
123 const mtimeMs = Math.max(dbStats.mtimeMs, wal?.mtimeMs ?? 0);
124 if (mtimeMs < sinceMs) return [];
125 return [{ path: dbPath, size: dbStats.size, mtimeMs, wal }];
127​
128/**
129 * Filesystem identity of a directory, as `device:inode`.
130 *
131 * Used to tell "two servers reading the same transcript directory" apart from
132 * "two machines whose hostname and home path happen to match". Returns an empty
133 * string when the directory cannot be stat'd.
134 */
135export async function readDirectoryVolumeId(path: string): Promise<string> {
136 try {
137 const stats = await NodeFSP.stat(path);
138 return `${stats.dev}:${stats.ino}`;
139 } catch {
140 return "";
141 }
143​
144/**
145 * Streams one transcript and returns the usage records it contains, or `null`
146 * when the file could not be read.
147 *
148 * The distinction matters to the caller's cache: a genuinely empty transcript
149 * is a stable fact worth memoising, while a transient read failure memoised
150 * under the same `(size, mtime)` key would silently drop that file's usage
151 * until the file next changes.
152 *
153 * Codex carries the active model on `turn_context` lines that hold no usage of
154 * their own, so those still have to pass through the reducer to keep model
155 * attribution correct.
156 */
157export async function readTranscriptRecords(
158 filePath: string,
159 provider: UsageProviderKind,
160): Promise<readonly UsageRecord[] | null> {
161 if (provider === "opencode") return readOpenCodeRecords(filePath);
162​
163 const records: UsageRecord[] = [];
164 const codexState = initialCodexScanState();
165​
166 try {
167 const lines = NodeReadline.createInterface({
168 input: NodeFS.createReadStream(filePath, { encoding: "utf8" }),
169 crlfDelay: Infinity,
170 });
171​
172 for await (const line of lines) {
173 if (provider === "codex") {
174 if (
175 !mightCarryUsage(line, provider) &&
176 !line.includes('"turn_context"') &&
177 !line.includes('"session_meta"')
178 ) {
179 continue;
180 }
181 const record = parseCodexLine(line, codexState);
182 if (record !== null) records.push(record);
183 continue;
184 }
185​
186 if (!mightCarryUsage(line, provider)) continue;
187 const record = parseClaudeLine(line);
188 if (record !== null) records.push(record);
189 }
190 } catch {
191 return null;
192 }
193​
194 return records;
196​
197/**
198 * Reads every assistant usage record from OpenCode's SQLite session store.
199 *
200 * `node:sqlite` is used read-only so the CLI can hold the store open in WAL
201 * mode; committed writes in the WAL are visible to a reader. A failure to open
202 * or query (missing file, busy, corrupt) returns `null` so the caller's cache
203 * stays untouched and the source reports empty rather than crashing the page.
204 */
205export async function readOpenCodeRecords(dbPath: string): Promise<readonly UsageRecord[] | null> {
206 let database: NodeSqlite.DatabaseSync;
207 try {
208 database = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });
209 } catch {
210 return null;
211 }
212​
213 try {
214 const rows = database.prepare("SELECT id, session_id, time_created, data FROM message").all();
215 const records: UsageRecord[] = [];
216 for (const row of rows as Array<Record<string, unknown>>) {
217 const id = row["id"];
218 const data = row["data"];
219 if (typeof id !== "string" || typeof data !== "string") continue;
220 const record = parseOpenCodeMessage({
221 id,
222 sessionId: typeof row["session_id"] === "string" ? row["session_id"] : "",
223 timeCreatedMs: typeof row["time_created"] === "number" ? row["time_created"] : 0,
224 data,
225 });
226 if (record !== null) records.push(record);
227 }
228 return records;
229 } catch {
230 return null;
231 } finally {
232 try {
233 database.close();
234 } catch {
235 // Already closed.
236 }
237 }