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