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;
88const CARRIAGE_RETURN = 0x0d;
89
90type SelectedFields = { readonly [key: string]: true | SelectedFields };
91
92// Keep the fields consumed by usageTranscripts, including reducer state and
93// dedupe/cost metadata. A selected subtree (usage) keeps future token fields.
94const USAGE_FIELDS: Record<"claude" | "codex" | "grok", SelectedFields> = {
95 claude: {
96 type: true,
97 timestamp: true,
98 requestId: true,
99 sessionId: true,
100 costUSD: true,
101 message: { id: true, model: true, usage: true },
102 },
103 codex: {
104 type: true,
105 timestamp: true,
106 payload: {
107 type: true,
108 id: true,
109 session_id: true,
110 model: true,
111 forked_from_id: true,
112 source: { subagent: { thread_spawn: { parent_thread_id: true } } },
113 info: { last_token_usage: true },
114 },
115 },
116 grok: {
117 timestamp: true,
118 params: {
119 sessionId: true,
120 _meta: { agentTimestampMs: true },
121 update: { sessionUpdate: true, prompt_id: true, usage: true },
122 },
123 },
124};
125
126function selectUsageFields(provider: UsageProviderKind) {
127 const fields = USAGE_FIELDS[provider === "codex" || provider === "grok" ? provider : "claude"];
128 return (path: ReadonlyArray<string | number | null>): boolean => {
129 let selected: true | SelectedFields = fields;
130 for (const key of path) {
131 if (selected === true) return true;
132 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
133 selected = selected[key]!;
134 }
135 return true;
136 };
137}
138
139function fnv1a(buffer: Buffer): number {
140 let hash = 0x811c9dc5;
141 for (let index = 0; index < buffer.length; index += 1) {
142 hash ^= buffer[index]!;
143 hash = Math.imul(hash, 0x01000193);
144 }
145 return hash >>> 0;
146}
147
148/**
149 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
150 *
151 * Errors on individual entries are swallowed: session files rotate and get
152 * removed while the walk is in flight, and a partial listing is far better than
153 * failing the page.
154 *
155 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
156 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
157 * never carry usage, so the basename filter keeps a cold scan off those files.
158 */
159export async function listTranscriptFiles(
160 root: string,
161 sinceMs: number,
162 options?: { readonly fileName?: string },
163): Promise<readonly TranscriptFile[]> {
164 const found: TranscriptFile[] = [];
165 const fileName = options?.fileName;
166
167 const walk = async (dir: string): Promise<void> => {
168 let entries;
169 try {
170 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
171 } catch {
172 return;
173 }
174 for (const entry of entries) {
175 const child = NodePath.join(dir, entry.name);
176 if (entry.isDirectory()) {
177 await walk(child);
178 continue;
179 }
180 if (fileName !== undefined) {
181 if (entry.name !== fileName) continue;
182 } else if (!entry.name.endsWith(".jsonl")) {
183 continue;
184 }
185 try {
186 const stats = await NodeFSP.stat(child);
187 if (stats.mtimeMs >= sinceMs) {
188 found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });
189 }
190 } catch {
191 // Vanished between readdir and stat.
192 }
193 }
194 };
195
196 await walk(root);
197 return found;
198}
199
200/**
201 * Filesystem identity of a directory, as `device:inode`.
202 *
203 * Used to tell "two servers reading the same transcript directory" apart from
204 * "two machines whose hostname and home path happen to match". Returns an empty
205 * string when the directory cannot be stat'd.
206 */
207export async function readDirectoryVolumeId(path: string): Promise<string> {
208 try {
209 const stats = await NodeFSP.stat(path);
210 return `${stats.dev}:${stats.ino}`;
211 } catch {
212 return "";
213 }
214}
215
216async function guardMatches(
217 handle: NodeFSP.FileHandle,
218 position: TranscriptParsePosition,
219): Promise<boolean> {
220 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
221 try {
222 const window = Buffer.alloc(position.guardLength);
223 const { bytesRead } = await handle.read(
224 window,
225 0,
226 position.guardLength,
227 position.resumeOffset - position.guardLength,
228 );
229 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
230 } catch {
231 return false;
232 }
233}
234
235/**
236 * Streams one transcript and returns the usage records it contains, or `null`
237 * when the file could not be read.
238 *
239 * The distinction matters to the caller's cache: a genuinely empty transcript
240 * is a stable fact worth memoising, while a transient read failure memoised
241 * under the same `(size, mtime)` key would silently drop that file's usage
242 * until the file next changes.
243 *
244 * With `resumeFrom`, parsing continues from that position when its guard bytes
245 * still match, so only appended lines are read; otherwise the whole file is
246 * re-parsed from the start and `resumed` reports `false`.
247 *
248 * Codex carries the active model on `turn_context` lines that hold no usage of
249 * their own, so those still have to pass through the reducer to keep model
250 * attribution correct.
251 */
252export async function readTranscriptRecords(
253 filePath: string,
254 provider: UsageProviderKind,
255 resumeFrom?: TranscriptParsePosition,
256 options?: { readonly streamingThresholdBytes?: number },
257): Promise<TranscriptParseResult | null> {
258 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
259 let handle: NodeFSP.FileHandle;
260 try {
261 handle = await NodeFSP.open(filePath, "r");
262 } catch {
263 return null;
264 }
265
266 try {
267 let codexState = initialCodexScanState();
268 let resumed = false;
269 let start = 0;
270 if (
271 resumeFrom !== undefined &&
272 resumeFrom.resumeOffset > 0 &&
273 (provider !== "codex" || resumeFrom.codexState !== null) &&
274 (await guardMatches(handle, resumeFrom))
275 ) {
276 if (resumeFrom.codexState !== null) codexState = { ...resumeFrom.codexState };
277 start = resumeFrom.resumeOffset;
278 resumed = true;
279 }
280
281 const parseLine = (line: string, state: CodexScanState, out: UsageRecord[]): void => {
282 if (provider === "codex") {
283 if (
284 !mightCarryUsage(line, provider) &&
285 !line.includes('"turn_context"') &&
286 !line.includes('"session_meta"')
287 ) {
288 return;
289 }
290 const record = parseCodexLine(line, state);
291 if (record !== null) out.push(record);
292 return;
293 }
294 if (!mightCarryUsage(line, provider)) return;
295 if (provider === "grok") {
296 for (const grokRecord of parseGrokLine(line)) out.push(grokRecord);
297 return;
298 }
299 const record = parseClaudeLine(line);
300 if (record !== null) out.push(record);
301 };
302
303 const toLineString = (lineBuffer: Buffer): string => {
304 const content =
305 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
306 ? lineBuffer.subarray(0, -1)
307 : lineBuffer;
308 return content.toString("utf8");
309 };
310
311 const records: UsageRecord[] = [];
312 // Byte offsets remain independent of UTF-8 decoding. Only complete lines
313 // commit the resume point; an unfinished tail is replayed on the next scan.
314 let resumeOffset = start;
315 let scanOffset = start;
316 let pendingChunks: Buffer[] = [];
317 let pendingBytes = 0;
318 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
319 let decoder: NodeStringDecoder.StringDecoder | undefined;
320 const selectPath = selectUsageFields(provider);
321
322 const append = (segment: Buffer) => {
323 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
324 if (segment.length > 0) pendingChunks.push(segment);
325 pendingBytes += segment.length;
326 return;
327 }
328 if (!streaming) {
329 // Usage has no import-history budget: retain all selected usage fields,
330 // regardless of the size of the surrounding unselected tool content.
331 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
332 decoder = new NodeStringDecoder.StringDecoder("utf8");
333 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
334 pendingChunks = [];
335 pendingBytes = 0;
336 }
337 streaming.write(decoder!.write(segment));
338 };
339 const finish = (state: CodexScanState, out: UsageRecord[]) => {
340 if (streaming) {
341 streaming.write(decoder!.end());
342 const projected = streaming.finish();
343 if (provider === "grok") {
344 out.push(...parseGrokRecord(projected));
345 } else {
346 const record =
347 provider === "codex"
348 ? parseCodexRecord(projected, state)
349 : parseClaudeRecord(projected);
350 if (record !== null) out.push(record);
351 }
352 } else if (pendingBytes > 0) {
353 const line =
354 pendingChunks.length === 1
355 ? pendingChunks[0]!
356 : Buffer.concat(pendingChunks, pendingBytes);
357 parseLine(toLineString(line), state, out);
358 }
359 pendingChunks = [];
360 pendingBytes = 0;
361 streaming = undefined;
362 decoder = undefined;
363 };
364 const stream = handle.createReadStream({
365 start,
366 autoClose: false,
367 highWaterMark: 256 * 1024,
368 }) as AsyncIterable<Buffer>;
369 for await (const chunk of stream) {
370 let lineStart = 0;
371 while (lineStart < chunk.length) {
372 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
373 if (newlineIndex === -1) {
374 append(chunk.subarray(lineStart));
375 break;
376 }
377 // Most lines fit in the current chunk. Avoid buffering/streaming
378 // machinery on this hot path.
379 if (!streaming && pendingBytes === 0) {
380 parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), codexState, records);
381 } else {
382 append(chunk.subarray(lineStart, newlineIndex));
383 finish(codexState, records);
384 }
385 lineStart = newlineIndex + 1;
386 resumeOffset = scanOffset + lineStart;
387 }
388 scanOffset += chunk.length;
389 }
390
391 const tailRecords: UsageRecord[] = [];
392 finish({ ...codexState }, tailRecords);
393
394 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
395 let guardHash = 0;
396 if (guardLength > 0) {
397 const window = Buffer.alloc(guardLength);
398 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
399 guardHash = fnv1a(window);
400 }
401
402 return {
403 records,
404 tailRecords,
405 position: {
406 resumeOffset,
407 guardLength,
408 guardHash,
409 codexState: provider === "codex" ? codexState : null,
410 },
411 resumed,
412 };
413 } catch {
414 return null;
415 } finally {
416 await handle.close().catch(() => undefined);
417 }
418}