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