Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2// Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files.
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5import * as NodeStringDecoder from "node:string_decoder";
6
7import type {
8 SelectedFields,
9 TranscriptUsageFormat,
10 UsageRecord,
11} from "@t3tools/provider-core/server/usage";
12import * as Option from "effect/Option";
13import * as Schema from "effect/Schema";
14
15import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
16
17export interface TranscriptFile {
18 readonly path: string;
19 readonly size: number;
20 readonly mtimeMs: number;
21}
22
23/** Resume only if bytes before resumeOffset match the guard hash; rewritten files would corrupt totals. */
24export interface TranscriptParsePosition {
25 readonly resumeOffset: number;
26 readonly guardLength: number;
27 readonly guardHash: number;
28 readonly state: unknown;
29}
30
31export interface TranscriptParseResult {
32 readonly records: readonly UsageRecord[];
33 /** Unterminated tail records stay outside records/position so the next scan rereads them. */
34 readonly tailRecords: readonly UsageRecord[];
35 /** Includes tentative tail diagnostics; position.state only includes committed lines. */
36 readonly malformedRecords: number;
37 readonly position: TranscriptParsePosition;
38 readonly resumed: boolean;
39}
40
41export const GUARD_LENGTH = 64;
42const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
43const NEWLINE = 0x0a;
44const STAT_CONCURRENCY = 32;
45const CARRIAGE_RETURN = 0x0d;
46
47function selectUsageFields(fields: SelectedFields) {
48 return (path: ReadonlyArray<string | number | null>): boolean => {
49 let selected: true | SelectedFields = fields;
50 for (const key of path) {
51 if (selected === true) return true;
52 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
53 selected = selected[key]!;
54 }
55 return true;
56 };
57}
58
59function fnv1a(buffer: Buffer): number {
60 let hash = 0x811c9dc5;
61 for (let index = 0; index < buffer.length; index += 1) {
62 hash ^= buffer[index]!;
63 hash = Math.imul(hash, 0x01000193);
64 }
65 return hash >>> 0;
66}
67
68/** Skips Grok logs without usage; preserves readdir order for first-seen deduplication. */
69export async function listTranscriptFiles(
70 root: string,
71 sinceMs: number,
72 options?: { readonly fileName?: string },
73): Promise<{ readonly files: readonly TranscriptFile[]; readonly failedPaths: number }> {
74 const fileName = options?.fileName;
75 const candidates: string[] = [];
76 let failedPaths = 0;
77 const walk = async (dir: string): Promise<void> => {
78 let entries;
79 try {
80 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
81 } catch {
82 failedPaths += 1;
83 return;
84 }
85 for (const entry of entries) {
86 const child = NodePath.join(dir, entry.name);
87 if (entry.isDirectory()) await walk(child);
88 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
89 candidates.push(child);
90 }
91 }
92 };
93 await walk(root);
94
95 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
96 const queue = candidates.entries();
97 const statQueued = async (): Promise<void> => {
98 for (const [index, path] of queue) {
99 try {
100 const stats = await NodeFSP.stat(path);
101 if (stats.mtimeMs >= sinceMs) {
102 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
103 }
104 } catch (error) {
105 if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
106 failedPaths += 1;
107 }
108 }
109 }
110 };
111 await Promise.all(
112 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
113 );
114 return { files: found.filter((file) => file !== undefined), failedPaths };
115}
116
117export async function readDirectoryVolumeId(path: string): Promise<string> {
118 try {
119 const stats = await NodeFSP.stat(path);
120 return `${stats.dev}:${stats.ino}`;
121 } catch {
122 return "";
123 }
124}
125
126async function guardMatches(
127 handle: NodeFSP.FileHandle,
128 position: TranscriptParsePosition,
129): Promise<boolean> {
130 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
131 try {
132 const window = Buffer.alloc(position.guardLength);
133 const { bytesRead } = await handle.read(
134 window,
135 0,
136 position.guardLength,
137 position.resumeOffset - position.guardLength,
138 );
139 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
140 } catch {
141 return false;
142 }
143}
144
145// Match markers in one latin1 alternation; one character per byte preserves exact ASCII offsets.
146export function transcriptLineGate(markers: readonly [string, ...string[]]) {
147 if (markers.length === 1) {
148 const marker = Buffer.from(markers[0]);
149 return (line: Buffer) => line.includes(marker);
150 }
151 const pattern = new RegExp(
152 markers.map((marker) => marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"),
153 );
154 return (line: Buffer) => pattern.test(line.toString("latin1"));
155}
156
157/** Returns null on read failure; caching it as empty would hide usage until size/mtime changes. */
158export async function readTranscriptRecords<State>(
159 filePath: string,
160 format: TranscriptUsageFormat<State>,
161 resumeFrom?: TranscriptParsePosition,
162 options?: { readonly streamingThresholdBytes?: number },
163): Promise<TranscriptParseResult | null> {
164 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
165 let handle: NodeFSP.FileHandle;
166 try {
167 handle = await NodeFSP.open(filePath, "r");
168 } catch {
169 return null;
170 }
171
172 try {
173 const codec = format.state;
174 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
175 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
176 let state = codec === undefined ? (undefined as State) : codec.initial();
177 let resumed = false;
178 let start = 0;
179 const savedState =
180 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
181 ? Option.none()
182 : decodeState(resumeFrom.state);
183 if (
184 resumeFrom !== undefined &&
185 resumeFrom.resumeOffset > 0 &&
186 (codec === undefined || Option.isSome(savedState)) &&
187 (await guardMatches(handle, resumeFrom))
188 ) {
189 if (Option.isSome(savedState)) state = savedState.value;
190 start = resumeFrom.resumeOffset;
191 resumed = true;
192 }
193
194 const toLineString = (lineBuffer: Buffer): string => {
195 const content =
196 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
197 ? lineBuffer.subarray(0, -1)
198 : lineBuffer;
199 return content.toString("utf8");
200 };
201
202 const mightCarryUsage = transcriptLineGate(format.usageMarkers);
203 const parseLine = (lineBuffer: Buffer, lineState: State, out: UsageRecord[]): void => {
204 if (!mightCarryUsage(lineBuffer)) return;
205 for (const record of format.parseLine(toLineString(lineBuffer), lineState)) out.push(record);
206 };
207
208 const records: UsageRecord[] = [];
209 let resumeOffset = start;
210 let scanOffset = start;
211 let pendingChunks: Buffer[] = [];
212 let pendingBytes = 0;
213 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
214 let decoder: NodeStringDecoder.StringDecoder | undefined;
215 const selectPath = selectUsageFields(format.selectFields);
216
217 const append = (segment: Buffer) => {
218 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
219 if (segment.length > 0) pendingChunks.push(segment);
220 pendingBytes += segment.length;
221 return;
222 }
223 if (!streaming) {
224 // Usage has no import-history budget; retain selected fields regardless of surrounding tool payload size.
225 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
226 decoder = new NodeStringDecoder.StringDecoder("utf8");
227 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
228 pendingChunks = [];
229 pendingBytes = 0;
230 }
231 streaming.write(decoder!.write(segment));
232 };
233 const finish = (lineState: State, out: UsageRecord[]) => {
234 if (streaming) {
235 streaming.write(decoder!.end());
236 const projected = streaming.finish();
237 for (const record of format.parseProjected(projected, lineState)) out.push(record);
238 } else if (pendingBytes > 0) {
239 const line =
240 pendingChunks.length === 1
241 ? pendingChunks[0]!
242 : Buffer.concat(pendingChunks, pendingBytes);
243 parseLine(line, lineState, out);
244 }
245 pendingChunks = [];
246 pendingBytes = 0;
247 streaming = undefined;
248 decoder = undefined;
249 };
250 const stream = handle.createReadStream({
251 start,
252 autoClose: false,
253 highWaterMark: 256 * 1024,
254 }) as AsyncIterable<Buffer>;
255 for await (const chunk of stream) {
256 let lineStart = 0;
257 while (lineStart < chunk.length) {
258 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
259 if (newlineIndex === -1) {
260 append(chunk.subarray(lineStart));
261 break;
262 }
263 if (!streaming && pendingBytes === 0) {
264 parseLine(chunk.subarray(lineStart, newlineIndex), state, records);
265 } else {
266 append(chunk.subarray(lineStart, newlineIndex));
267 finish(state, records);
268 }
269 lineStart = newlineIndex + 1;
270 resumeOffset = scanOffset + lineStart;
271 }
272 scanOffset += chunk.length;
273 }
274
275 // Parse unfinished tails against copied state so the next scan can replay from resumeOffset.
276 const encodedState = encodeState === undefined ? null : encodeState(state);
277 const tailRecords: UsageRecord[] = [];
278 const tailState =
279 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState));
280 finish(tailState, tailRecords);
281
282 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
283 let guardHash = 0;
284 if (guardLength > 0) {
285 const window = Buffer.alloc(guardLength);
286 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
287 guardHash = fnv1a(window);
288 }
289
290 return {
291 records,
292 tailRecords,
293 malformedRecords: format.readMalformedRecords?.(tailState) ?? 0,
294 position: {
295 resumeOffset,
296 guardLength,
297 guardHash,
298 state: encodedState,
299 },
300 resumed,
301 };
302 } catch {
303 return null;
304 } finally {
305 await handle.close().catch(() => undefined);
306 }
307}