Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
4 * across ~1,500 files, and buffer-level streaming is roughly an order of
5 * magnitude cheaper than materialising each file.
6 */
7import * as NodeFSP from "node:fs/promises";
8import * as NodePath from "node:path";
9import * as NodeStringDecoder from "node:string_decoder";
10
11import type {
12 SelectedFields,
13 TranscriptUsageFormat,
14 UsageRecord,
15} from "@t3tools/provider-core/server/usage";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18
19import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
20
21export interface TranscriptFile {
22 readonly path: string;
23 readonly size: number;
24 readonly mtimeMs: number;
25}
26
27/**
28 * The guard hash fingerprints the bytes immediately before `resumeOffset`. A
29 * resume only proceeds when those bytes still match: transcripts are
30 * append-only by design, but a rotated or rewritten file silently mis-parsed
31 * from the middle would corrupt usage totals.
32 */
33export interface TranscriptParsePosition {
34 readonly resumeOffset: number;
35 readonly guardLength: number;
36 readonly guardHash: number;
37 readonly state: unknown;
38}
39
40export interface TranscriptParseResult {
41 readonly records: readonly UsageRecord[];
42 /**
43 * Records from a trailing segment the writer has not newline-terminated yet.
44 * Kept out of `records` because `position` deliberately excludes that
45 * segment: the next scan re-reads it once the writer finishes the line.
46 */
47 readonly tailRecords: readonly UsageRecord[];
48 readonly position: TranscriptParsePosition;
49 readonly resumed: boolean;
50}
51
52export const GUARD_LENGTH = 64;
53const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
54const NEWLINE = 0x0a;
55const STAT_CONCURRENCY = 32;
56const CARRIAGE_RETURN = 0x0d;
57
58function selectUsageFields(fields: SelectedFields) {
59 return (path: ReadonlyArray<string | number | null>): boolean => {
60 let selected: true | SelectedFields = fields;
61 for (const key of path) {
62 if (selected === true) return true;
63 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
64 selected = selected[key]!;
65 }
66 return true;
67 };
68}
69
70function fnv1a(buffer: Buffer): number {
71 let hash = 0x811c9dc5;
72 for (let index = 0; index < buffer.length; index += 1) {
73 hash ^= buffer[index]!;
74 hash = Math.imul(hash, 0x01000193);
75 }
76 return hash >>> 0;
77}
78
79/**
80 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
81 * never carry usage, so the basename filter keeps a cold scan off those files.
82 * Results keep `readdir` order, which the aggregator's first-seen dedupe relies
83 * on.
84 */
85export async function listTranscriptFiles(
86 root: string,
87 sinceMs: number,
88 options?: { readonly fileName?: string },
89): Promise<{ readonly files: readonly TranscriptFile[]; readonly failedPaths: number }> {
90 const fileName = options?.fileName;
91 const candidates: string[] = [];
92 let failedPaths = 0;
93 const walk = async (dir: string): Promise<void> => {
94 let entries;
95 try {
96 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
97 } catch {
98 failedPaths += 1;
99 return;
100 }
101 for (const entry of entries) {
102 const child = NodePath.join(dir, entry.name);
103 if (entry.isDirectory()) await walk(child);
104 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
105 candidates.push(child);
106 }
107 }
108 };
109 await walk(root);
110
111 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
112 const queue = candidates.entries();
113 const statQueued = async (): Promise<void> => {
114 for (const [index, path] of queue) {
115 try {
116 const stats = await NodeFSP.stat(path);
117 if (stats.mtimeMs >= sinceMs) {
118 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
119 }
120 } catch (error) {
121 if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
122 failedPaths += 1;
123 }
124 }
125 }
126 };
127 await Promise.all(
128 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
129 );
130 return { files: found.filter((file) => file !== undefined), failedPaths };
131}
132
133export async function readDirectoryVolumeId(path: string): Promise<string> {
134 try {
135 const stats = await NodeFSP.stat(path);
136 return `${stats.dev}:${stats.ino}`;
137 } catch {
138 return "";
139 }
140}
141
142async function guardMatches(
143 handle: NodeFSP.FileHandle,
144 position: TranscriptParsePosition,
145): Promise<boolean> {
146 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
147 try {
148 const window = Buffer.alloc(position.guardLength);
149 const { bytesRead } = await handle.read(
150 window,
151 0,
152 position.guardLength,
153 position.resumeOffset - position.guardLength,
154 );
155 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
156 } catch {
157 return false;
158 }
159}
160
161/**
162 * Several would be one pass over the line each, so they are matched together as
163 * one alternation over the line's latin1 view instead: latin1 maps every byte
164 * to one character without validating it, so an ASCII marker matches exactly
165 * where its bytes do.
166 */
167export function transcriptLineGate(markers: readonly [string, ...string[]]) {
168 if (markers.length === 1) {
169 const marker = Buffer.from(markers[0]);
170 return (line: Buffer) => line.includes(marker);
171 }
172 const pattern = new RegExp(
173 markers.map((marker) => marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"),
174 );
175 return (line: Buffer) => pattern.test(line.toString("latin1"));
176}
177
178/**
179 * Streams one transcript and returns the usage records it contains, or `null`
180 * when the file could not be read.
181 *
182 * The distinction matters to the caller's cache: a genuinely empty transcript
183 * is a stable fact worth memoising, while a transient read failure memoised
184 * under the same `(size, mtime)` key would silently drop that file's usage
185 * until the file next changes.
186 */
187export async function readTranscriptRecords<State>(
188 filePath: string,
189 format: TranscriptUsageFormat<State>,
190 resumeFrom?: TranscriptParsePosition,
191 options?: { readonly streamingThresholdBytes?: number },
192): Promise<TranscriptParseResult | null> {
193 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
194 let handle: NodeFSP.FileHandle;
195 try {
196 handle = await NodeFSP.open(filePath, "r");
197 } catch {
198 return null;
199 }
200
201 try {
202 const codec = format.state;
203 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
204 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
205 let state = codec === undefined ? (undefined as State) : codec.initial();
206 let resumed = false;
207 let start = 0;
208 const savedState =
209 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
210 ? Option.none()
211 : decodeState(resumeFrom.state);
212 if (
213 resumeFrom !== undefined &&
214 resumeFrom.resumeOffset > 0 &&
215 (codec === undefined || Option.isSome(savedState)) &&
216 (await guardMatches(handle, resumeFrom))
217 ) {
218 if (Option.isSome(savedState)) state = savedState.value;
219 start = resumeFrom.resumeOffset;
220 resumed = true;
221 }
222
223 const toLineString = (lineBuffer: Buffer): string => {
224 const content =
225 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
226 ? lineBuffer.subarray(0, -1)
227 : lineBuffer;
228 return content.toString("utf8");
229 };
230
231 const mightCarryUsage = transcriptLineGate(format.usageMarkers);
232 const parseLine = (lineBuffer: Buffer, lineState: State, out: UsageRecord[]): void => {
233 if (!mightCarryUsage(lineBuffer)) return;
234 for (const record of format.parseLine(toLineString(lineBuffer), lineState)) out.push(record);
235 };
236
237 const records: UsageRecord[] = [];
238 let resumeOffset = start;
239 let scanOffset = start;
240 let pendingChunks: Buffer[] = [];
241 let pendingBytes = 0;
242 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
243 let decoder: NodeStringDecoder.StringDecoder | undefined;
244 const selectPath = selectUsageFields(format.selectFields);
245
246 const append = (segment: Buffer) => {
247 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
248 if (segment.length > 0) pendingChunks.push(segment);
249 pendingBytes += segment.length;
250 return;
251 }
252 if (!streaming) {
253 // Usage has no import-history budget: retain all selected usage fields,
254 // regardless of the size of the surrounding unselected tool content.
255 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
256 decoder = new NodeStringDecoder.StringDecoder("utf8");
257 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
258 pendingChunks = [];
259 pendingBytes = 0;
260 }
261 streaming.write(decoder!.write(segment));
262 };
263 const finish = (lineState: State, out: UsageRecord[]) => {
264 if (streaming) {
265 streaming.write(decoder!.end());
266 const projected = streaming.finish();
267 for (const record of format.parseProjected(projected, lineState)) out.push(record);
268 } else if (pendingBytes > 0) {
269 const line =
270 pendingChunks.length === 1
271 ? pendingChunks[0]!
272 : Buffer.concat(pendingChunks, pendingBytes);
273 parseLine(line, lineState, out);
274 }
275 pendingChunks = [];
276 pendingBytes = 0;
277 streaming = undefined;
278 decoder = undefined;
279 };
280 const stream = handle.createReadStream({
281 start,
282 autoClose: false,
283 highWaterMark: 256 * 1024,
284 }) as AsyncIterable<Buffer>;
285 for await (const chunk of stream) {
286 let lineStart = 0;
287 while (lineStart < chunk.length) {
288 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
289 if (newlineIndex === -1) {
290 append(chunk.subarray(lineStart));
291 break;
292 }
293 if (!streaming && pendingBytes === 0) {
294 parseLine(chunk.subarray(lineStart, newlineIndex), state, records);
295 } else {
296 append(chunk.subarray(lineStart, newlineIndex));
297 finish(state, records);
298 }
299 lineStart = newlineIndex + 1;
300 resumeOffset = scanOffset + lineStart;
301 }
302 scanOffset += chunk.length;
303 }
304
305 // The unfinished tail parses against a copy, so the saved state stays at
306 // `resumeOffset` and the next scan replays the tail from it.
307 const encodedState = encodeState === undefined ? null : encodeState(state);
308 const tailRecords: UsageRecord[] = [];
309 finish(
310 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
311 tailRecords,
312 );
313
314 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
315 let guardHash = 0;
316 if (guardLength > 0) {
317 const window = Buffer.alloc(guardLength);
318 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
319 guardHash = fnv1a(window);
320 }
321
322 return {
323 records,
324 tailRecords,
325 position: {
326 resumeOffset,
327 guardLength,
328 guardHash,
329 state: encodedState,
330 },
331 resumed,
332 };
333 } catch {
334 return null;
335 } finally {
336 await handle.close().catch(() => undefined);
337 }
338}