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 buffer-level streaming 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 * Transcripts are append-only, so a parse also reports the byte position it
12 * stopped at. A later scan of the same file resumes from that position and
13 * parses only the appended bytes, which is what keeps a warm scan cheap while a
14 * session is actively writing a multi-hundred-megabyte rollout.
15 *
16 * @module usageTranscriptReader
17 */
18import * as NodeFSP from "node:fs/promises";
19import * as NodePath from "node:path";
20import * as NodeStringDecoder from "node:string_decoder";
21
22import type { UsageProviderKind } from "@t3tools/contracts";
23
24import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
25
26import {
27 initialCodexScanState,
28 mightCarryUsage,
29 parseClaudeLine,
30 parseClaudeRecord,
31 parseCodexLine,
32 parseCodexRecord,
33 parseGrokLine,
34 parseGrokRecord,
35 type CodexScanState,
36 type UsageRecord,
37} from "./usageTranscripts.ts";
38
39export interface TranscriptFile {
40 readonly path: string;
41 readonly size: number;
42 readonly mtimeMs: number;
43}
44
45/**
46 * Where a parse stopped, with enough state to continue from there.
47 *
48 * The guard hash fingerprints the bytes immediately before `resumeOffset`. A
49 * resume only proceeds when those bytes still match: transcripts are
50 * append-only by design, but a rotated or rewritten file silently mis-parsed
51 * from the middle would corrupt usage totals. The window is a cheap tripwire
52 * for those realistic failure shapes, all of which disturb the file's tail at
53 * that exact offset; it deliberately does not hash the whole prefix, which
54 * would cost the full re-read the resume exists to avoid.
55 */
56export interface TranscriptParsePosition {
57 /** Byte offset just past the last newline-terminated line consumed. */
58 readonly resumeOffset: number;
59 /** Length of the fingerprinted window ending at `resumeOffset`. */
60 readonly guardLength: number;
61 /** FNV-1a hash of that window. */
62 readonly guardHash: number;
63 /** Codex reducer state as of `resumeOffset`; `null` for stateless providers. */
64 readonly codexState: CodexScanState | null;
65}
66
67export interface TranscriptParseResult {
68 /** Records from newline-terminated lines at or after the parse start. */
69 readonly records: readonly UsageRecord[];
70 /**
71 * Records from a trailing segment the writer has not newline-terminated yet.
72 * Kept out of `records` because `position` deliberately excludes that
73 * segment: the next scan re-reads it once the writer finishes the line.
74 */
75 readonly tailRecords: readonly UsageRecord[];
76 readonly position: TranscriptParsePosition;
77 /** Whether the parse continued from `resumeFrom` rather than byte 0. */
78 readonly resumed: boolean;
79}
80
81/** 64 bytes of JSONL tail is ample to distinguish a replaced file. */
82export const GUARD_LENGTH = 64;
83// Native parsing is faster for common 1–4 MiB context/tool records. Above
84// 8 MiB, project usage without allocating the whole record. This switches
85// readers; it never discards a record because of its size.
86const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
87const NEWLINE = 0x0a;
88/** `stat` calls one transcript walk keeps in flight. The libuv pool has 4 threads. */
89const STAT_CONCURRENCY = 32;
90const CARRIAGE_RETURN = 0x0d;
91
92type SelectedFields = { readonly [key: string]: true | SelectedFields };
93
94// Keep the fields consumed by usageTranscripts, including reducer state and
95// dedupe/cost metadata. A selected subtree (usage) keeps future token fields.
96const USAGE_FIELDS: Record<"claude" | "codex" | "grok", SelectedFields> = {
97 claude: {
98 type: true,
99 timestamp: true,
100 requestId: true,
101 sessionId: true,
102 costUSD: true,
103 message: { id: true, model: true, usage: true },
104 },
105 codex: {
106 type: true,
107 timestamp: true,
108 payload: {
109 type: true,
110 id: true,
111 session_id: true,
112 model: true,
113 thread_settings: { service_tier: true },
114 forked_from_id: true,
115 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
116 info: { last_token_usage: true },
117 },
118 },
119 grok: {
120 timestamp: true,
121 params: {
122 sessionId: true,
123 _meta: { agentTimestampMs: true },
124 update: { sessionUpdate: true, prompt_id: true, usage: true },
125 },
126 },
127};
128
129function selectUsageFields(provider: UsageProviderKind) {
130 const fields = USAGE_FIELDS[provider === "codex" || provider === "grok" ? provider : "claude"];
131 return (path: ReadonlyArray<string | number | null>): boolean => {
132 let selected: true | SelectedFields = fields;
133 for (const key of path) {
134 if (selected === true) return true;
135 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
136 selected = selected[key]!;
137 }
138 return true;
139 };
140}
141
142function fnv1a(buffer: Buffer): number {
143 let hash = 0x811c9dc5;
144 for (let index = 0; index < buffer.length; index += 1) {
145 hash ^= buffer[index]!;
146 hash = Math.imul(hash, 0x01000193);
147 }
148 return hash >>> 0;
149}
150
151/**
152 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
153 *
154 * Errors on individual entries are swallowed: session files rotate and get
155 * removed while the walk is in flight, and a partial listing is far better than
156 * failing the page.
157 *
158 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
159 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
160 * never carry usage, so the basename filter keeps a cold scan off those files.
161 *
162 * Directories are listed depth-first, one at a time, then the candidates are
163 * stat'd by a fixed pool of workers: a warm scan stats thousands of files, and
164 * one at a time each waits its own trip through the thread pool. Results keep
165 * `readdir` order, which the aggregator's first-seen dedupe relies on.
166 */
167export async function listTranscriptFiles(
168 root: string,
169 sinceMs: number,
170 options?: { readonly fileName?: string },
171): Promise<readonly TranscriptFile[]> {
172 const fileName = options?.fileName;
173 const candidates: string[] = [];
174 const walk = async (dir: string): Promise<void> => {
175 let entries;
176 try {
177 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
178 } catch {
179 return;
180 }
181 for (const entry of entries) {
182 const child = NodePath.join(dir, entry.name);
183 if (entry.isDirectory()) await walk(child);
184 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
185 candidates.push(child);
186 }
187 }
188 };
189 await walk(root);
190
191 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
192 // Each worker pulls the next candidate from one shared iterator.
193 const queue = candidates.entries();
194 const statQueued = async (): Promise<void> => {
195 for (const [index, path] of queue) {
196 try {
197 const stats = await NodeFSP.stat(path);
198 if (stats.mtimeMs >= sinceMs) {
199 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
200 }
201 } catch {
202 // Vanished between readdir and stat.
203 }
204 }
205 };
206 await Promise.all(
207 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
208 );
209 return found.filter((file) => file !== undefined);
210}
211
212/**
213 * Filesystem identity of a directory, as `device:inode`.
214 *
215 * Used to tell "two servers reading the same transcript directory" apart from
216 * "two machines whose hostname and home path happen to match". Returns an empty
217 * string when the directory cannot be stat'd.
218 */
219export async function readDirectoryVolumeId(path: string): Promise<string> {
220 try {
221 const stats = await NodeFSP.stat(path);
222 return `${stats.dev}:${stats.ino}`;
223 } catch {
224 return "";
225 }
226}
227
228async function guardMatches(
229 handle: NodeFSP.FileHandle,
230 position: TranscriptParsePosition,
231): Promise<boolean> {
232 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
233 try {
234 const window = Buffer.alloc(position.guardLength);
235 const { bytesRead } = await handle.read(
236 window,
237 0,
238 position.guardLength,
239 position.resumeOffset - position.guardLength,
240 );
241 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
242 } catch {
243 return false;
244 }
245}
246
247/**
248 * Streams one transcript and returns the usage records it contains, or `null`
249 * when the file could not be read.
250 *
251 * The distinction matters to the caller's cache: a genuinely empty transcript
252 * is a stable fact worth memoising, while a transient read failure memoised
253 * under the same `(size, mtime)` key would silently drop that file's usage
254 * until the file next changes.
255 *
256 * With `resumeFrom`, parsing continues from that position when its guard bytes
257 * still match, so only appended lines are read; otherwise the whole file is
258 * re-parsed from the start and `resumed` reports `false`.
259 *
260 * Codex carries the active model on `turn_context` lines and the service tier
261 * on `thread_settings_applied` lines. Neither holds usage of its own, but both
262 * still have to pass through the reducer to keep attribution and pricing
263 * correct.
264 */
265export async function readTranscriptRecords(
266 filePath: string,
267 provider: UsageProviderKind,
268 resumeFrom?: TranscriptParsePosition,
269 options?: { readonly streamingThresholdBytes?: number },
270): Promise<TranscriptParseResult | null> {
271 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
272 let handle: NodeFSP.FileHandle;
273 try {
274 handle = await NodeFSP.open(filePath, "r");
275 } catch {
276 return null;
277 }
278
279 try {
280 let codexState = initialCodexScanState();
281 let resumed = false;
282 let start = 0;
283 if (
284 resumeFrom !== undefined &&
285 resumeFrom.resumeOffset > 0 &&
286 (provider !== "codex" || resumeFrom.codexState !== null) &&
287 (await guardMatches(handle, resumeFrom))
288 ) {
289 if (resumeFrom.codexState !== null) codexState = { ...resumeFrom.codexState };
290 start = resumeFrom.resumeOffset;
291 resumed = true;
292 }
293
294 const parseLine = (line: string, state: CodexScanState, out: UsageRecord[]): void => {
295 if (provider === "codex") {
296 if (
297 !mightCarryUsage(line, provider) &&
298 !line.includes('"turn_context"') &&
299 !line.includes('"thread_settings_applied"') &&
300 !line.includes('"session_meta"')
301 ) {
302 return;
303 }
304 const record = parseCodexLine(line, state);
305 if (record !== null) out.push(record);
306 return;
307 }
308 if (!mightCarryUsage(line, provider)) return;
309 if (provider === "grok") {
310 for (const grokRecord of parseGrokLine(line)) out.push(grokRecord);
311 return;
312 }
313 const record = parseClaudeLine(line);
314 if (record !== null) out.push(record);
315 };
316
317 const toLineString = (lineBuffer: Buffer): string => {
318 const content =
319 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
320 ? lineBuffer.subarray(0, -1)
321 : lineBuffer;
322 return content.toString("utf8");
323 };
324
325 const records: UsageRecord[] = [];
326 // Byte offsets remain independent of UTF-8 decoding. Only complete lines
327 // commit the resume point; an unfinished tail is replayed on the next scan.
328 let resumeOffset = start;
329 let scanOffset = start;
330 let pendingChunks: Buffer[] = [];
331 let pendingBytes = 0;
332 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
333 let decoder: NodeStringDecoder.StringDecoder | undefined;
334 const selectPath = selectUsageFields(provider);
335
336 const append = (segment: Buffer) => {
337 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
338 if (segment.length > 0) pendingChunks.push(segment);
339 pendingBytes += segment.length;
340 return;
341 }
342 if (!streaming) {
343 // Usage has no import-history budget: retain all selected usage fields,
344 // regardless of the size of the surrounding unselected tool content.
345 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
346 decoder = new NodeStringDecoder.StringDecoder("utf8");
347 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
348 pendingChunks = [];
349 pendingBytes = 0;
350 }
351 streaming.write(decoder!.write(segment));
352 };
353 const finish = (state: CodexScanState, out: UsageRecord[]) => {
354 if (streaming) {
355 streaming.write(decoder!.end());
356 const projected = streaming.finish();
357 if (provider === "grok") {
358 out.push(...parseGrokRecord(projected));
359 } else {
360 const record =
361 provider === "codex"
362 ? parseCodexRecord(projected, state)
363 : parseClaudeRecord(projected);
364 if (record !== null) out.push(record);
365 }
366 } else if (pendingBytes > 0) {
367 const line =
368 pendingChunks.length === 1
369 ? pendingChunks[0]!
370 : Buffer.concat(pendingChunks, pendingBytes);
371 parseLine(toLineString(line), state, out);
372 }
373 pendingChunks = [];
374 pendingBytes = 0;
375 streaming = undefined;
376 decoder = undefined;
377 };
378 const stream = handle.createReadStream({
379 start,
380 autoClose: false,
381 highWaterMark: 256 * 1024,
382 }) as AsyncIterable<Buffer>;
383 for await (const chunk of stream) {
384 let lineStart = 0;
385 while (lineStart < chunk.length) {
386 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
387 if (newlineIndex === -1) {
388 append(chunk.subarray(lineStart));
389 break;
390 }
391 // Most lines fit in the current chunk. Avoid buffering/streaming
392 // machinery on this hot path.
393 if (!streaming && pendingBytes === 0) {
394 parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), codexState, records);
395 } else {
396 append(chunk.subarray(lineStart, newlineIndex));
397 finish(codexState, records);
398 }
399 lineStart = newlineIndex + 1;
400 resumeOffset = scanOffset + lineStart;
401 }
402 scanOffset += chunk.length;
403 }
404
405 const tailRecords: UsageRecord[] = [];
406 finish({ ...codexState }, tailRecords);
407
408 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
409 let guardHash = 0;
410 if (guardLength > 0) {
411 const window = Buffer.alloc(guardLength);
412 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
413 guardHash = fnv1a(window);
414 }
415
416 return {
417 records,
418 tailRecords,
419 position: {
420 resumeOffset,
421 guardLength,
422 guardHash,
423 codexState: provider === "codex" ? codexState : null,
424 },
425 resumed,
426 };
427 } catch {
428 return null;
429 } finally {
430 await handle.close().catch(() => undefined);
431 }
432}