Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/** Native and canonical views share write state to avoid races on the same thread file. */
3import * as NodeCrypto from "node:crypto";
4import * as NodeFS from "node:fs";
5import * as NodePath from "node:path";
6
7import type { ThreadId } from "@t3tools/contracts";
8import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
9import { makeAsyncRotatingFileSink, rotationSidecarBase } from "@t3tools/shared/logging";
10import { errorTag } from "@t3tools/shared/observability";
11import * as Clock from "effect/Clock";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Path from "effect/Path";
16import * as Result from "effect/Result";
17import * as Exit from "effect/Exit";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as SynchronizedRef from "effect/SynchronizedRef";
21
22import {
23 ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS,
24 toSafeThreadAttachmentSegment,
25} from "../attachmentStore.ts";
26import type * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
27
28const MEBIBYTE = 1024 * 1024;
29const DAY_MS = 24 * 60 * 60 * 1_000;
30const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
31const DEFAULT_MAX_FILES = 10;
32const DEFAULT_BATCH_WINDOW_MS = 1_000;
33const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
34const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
35const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
36const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
37const DEFAULT_MAX_BUFFERED_RECORDS = 512;
38const MAX_RECORD_CHARACTERS = 64 * 1024;
39const MAX_RECORD_FIELDS = 1_024;
40const MAX_RECORD_DEPTH = 16;
41const GLOBAL_THREAD_SEGMENT = "_global";
42const LOG_SCOPE = "provider-observability";
43const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
44
45const transientCanonicalEventTypes = new Set([
46 "content.delta",
47 "hook.progress",
48 "item.updated",
49 "task.progress",
50 "thread.realtime.audio.delta",
51 "tool.progress",
52 "turn.proposed.delta",
53]);
54const transientNativeMethods = new Set([
55 "item/agentMessage/delta",
56 "item/commandExecution/outputDelta",
57 "item/fileChange/outputDelta",
58 "item/plan/delta",
59 "item/reasoning/summaryTextDelta",
60 "item/reasoning/textDelta",
61 "thread/realtime/outputAudio/delta",
62 "thread/realtime/transcript/delta",
63 "turn/diff/updated",
64]);
65const transientAcpUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
66const transientCursorUpdates = new Set([
67 "text-delta",
68 "thinking-delta",
69 "token-delta",
70 "shell-output-delta",
71 "partial-tool-call",
72]);
73
74export type EventNdjsonStream = "native" | "canonical" | "orchestration";
75
76export interface EventNdjsonLogStore {
77 readonly filePath: string;
78 readonly logger: (stream: EventNdjsonStream) => ProviderEventLoggers.EventNdjsonLogger;
79 readonly close: () => Effect.Effect<void>;
80}
81
82export interface EventNdjsonLogStoreOptions {
83 readonly maxBytes?: number;
84 readonly maxFiles?: number;
85 readonly batchWindowMs?: number;
86 readonly attribution?: ResourceAttribution.ResourceAttribution["Service"];
87}
88
89export class EventNdjsonLogDirectoryError extends Schema.TaggedError<EventNdjsonLogDirectoryError>()(
90 "EventNdjsonLogDirectoryError",
91 {
92 directory: Schema.String,
93 cause: Schema.Defect(),
94 },
95) {
96 override get message(): string {
97 return `Failed to create provider event log directory '${this.directory}'`;
98 }
99}
100
101export type EventNdjsonLogStoreError = EventNdjsonLogDirectoryError;
102
103interface ResolvedOptions {
104 readonly maxBytes: number;
105 readonly maxFiles: number;
106 readonly batchWindowMs: number;
107 readonly maxTotalBytes: number;
108 readonly maxAgeMs: number;
109 readonly retentionCheckIntervalMs: number;
110 readonly maxBufferedBytes: number;
111 readonly maxBufferedRecords: number;
112 readonly attribution: ResourceAttribution.ResourceAttribution["Service"] | undefined;
113}
114
115export interface PendingRecord {
116 readonly stream: EventNdjsonStream;
117 readonly threadSegment: string;
118 readonly line: string;
119 readonly bytes: number;
120}
121
122type AsyncFileSink = Effect.Success<ReturnType<typeof makeAsyncRotatingFileSink>>;
123
124interface StoreState {
125 readonly pending: Array<PendingRecord>;
126 readonly pendingBytes: number;
127 readonly sinks: ReadonlyMap<string, AsyncFileSink>;
128 readonly writtenSinceRetention: ReadonlySet<string>;
129 readonly flushScheduled: boolean;
130 readonly closed: boolean;
131 readonly lastRetentionAt: number;
132}
133
134interface AttributionSummary {
135 readonly stream: EventNdjsonStream;
136 readonly count: number;
137 readonly logicalWriteBytes: number;
138}
139
140interface FileOperationFailure {
141 readonly filePath: string;
142 readonly cause: unknown;
143}
144
145interface RetentionResult {
146 readonly failures: ReadonlyArray<FileOperationFailure>;
147}
148
149interface DrainResult {
150 readonly attributions: ReadonlyArray<AttributionSummary>;
151 readonly failures: ReadonlyArray<FileOperationFailure>;
152}
153
154function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
155 return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
156}
157
158function resolveThreadSegment(raw: string | null | undefined): string {
159 if (typeof raw !== "string") return GLOBAL_THREAD_SEGMENT;
160 const normalized = toSafeThreadAttachmentSegment(raw);
161 if (normalized === null) return GLOBAL_THREAD_SEGMENT;
162 // Delegated thread ids share a prefix longer than the segment, so ids that may be cut get a hash.
163 if (raw.length <= ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS) return normalized;
164 const hash = NodeCrypto.createHash("sha256").update(raw).digest("hex").slice(0, 16);
165 return `${normalized}-${hash}`;
166}
167
168function resolveStreamLabel(stream: EventNdjsonStream): string {
169 return stream === "native" ? "NTIVE" : stream === "orchestration" ? "ORCH" : "CANON";
170}
171
172function providerLogPrefix(filePath: string): string {
173 const basename = NodePath.basename(filePath);
174 const extension = NodePath.extname(basename);
175 return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;
176}
177
178function providerLogPath(directory: string, prefix: string, threadSegment: string): string {
179 return NodePath.join(directory, `${prefix}${threadSegment}.log`);
180}
181
182export function providerThreadLogPath(providerEventLogPath: string, threadId: string): string {
183 return providerLogPath(
184 NodePath.dirname(providerEventLogPath),
185 providerLogPrefix(providerEventLogPath),
186 resolveThreadSegment(threadId),
187 );
188}
189
190export function shouldPersistProviderEvent(stream: EventNdjsonStream, event: unknown): boolean {
191 if (stream === "orchestration" || typeof event !== "object" || event === null) {
192 return true;
193 }
194 try {
195 const type = Reflect.get(event, "type");
196 if (typeof type === "string" && transientCanonicalEventTypes.has(type)) {
197 return false;
198 }
199 if (stream !== "native") return true;
200
201 const nested = Reflect.get(event, "event");
202 const envelope = typeof nested === "object" && nested !== null ? nested : event;
203 // Decoded frames preserve raw-frame information without duplicating every token delta.
204 if (Reflect.get(envelope, "stage") === "raw") return false;
205 const decodedPayload = Reflect.get(envelope, "payload");
206 const nativeEvent =
207 Reflect.get(envelope, "stage") === "decoded" &&
208 typeof decodedPayload === "object" &&
209 decodedPayload !== null
210 ? decodedPayload
211 : envelope;
212 const method = Reflect.get(nativeEvent, "method");
213 if (
214 typeof method === "string" &&
215 (transientNativeMethods.has(method) ||
216 method.startsWith("claude/stream_event/content_block_delta/"))
217 ) {
218 return false;
219 }
220
221 const nativeType = Reflect.get(nativeEvent, "type");
222 if (nativeType === "system" && Reflect.get(nativeEvent, "subtype") === "thinking_tokens") {
223 return false;
224 }
225 if (nativeType === "message.part.delta") return false;
226 if (nativeType === "stream_event") {
227 const streamEvent = Reflect.get(nativeEvent, "event");
228 if (
229 typeof streamEvent === "object" &&
230 streamEvent !== null &&
231 Reflect.get(streamEvent, "type") === "content_block_delta"
232 ) {
233 return false;
234 }
235 }
236
237 if (nativeType === "interaction.update") {
238 let update = Reflect.get(nativeEvent, "update");
239 if (typeof update !== "object" || update === null) return true;
240 // Subagent updates arrive wrapped; keep the wrapper when it carries a lifecycle record.
241 if (Reflect.get(update, "type") === "tool-call-delta") {
242 update = Reflect.get(update, "taskUpdate");
243 if (typeof update !== "object" || update === null) return true;
244 }
245 const updateType = Reflect.get(update, "type");
246 return typeof updateType !== "string" || !transientCursorUpdates.has(updateType);
247 }
248
249 const payload = Reflect.get(nativeEvent, "payload");
250 if (typeof payload !== "object" || payload === null) return true;
251
252 if (method === "session/update") {
253 const update = Reflect.get(payload, "update");
254 if (typeof update !== "object" || update === null) return true;
255 const updateType = Reflect.get(update, "sessionUpdate");
256 return typeof updateType !== "string" || !transientAcpUpdates.has(updateType);
257 }
258
259 if (nativeType === "message.part.updated") {
260 const properties = Reflect.get(payload, "properties");
261 if (typeof properties !== "object" || properties === null) return true;
262 const part = Reflect.get(properties, "part");
263 if (typeof part !== "object" || part === null) return true;
264 const partType = Reflect.get(part, "type");
265 if (partType === "text" || partType === "reasoning") return false;
266 if (partType === "tool") {
267 // Running snapshots repeat growing output.
268 const state = Reflect.get(part, "state");
269 if (typeof state === "object" && state !== null) {
270 return Reflect.get(state, "status") !== "running";
271 }
272 }
273 return true;
274 }
275
276 return true;
277 } catch {
278 return true;
279 }
280}
281
282const summaryFields = [
283 "provider",
284 "protocol",
285 "kind",
286 "providerSessionId",
287 "direction",
288 "stage",
289 "type",
290 "subtype",
291 "method",
292 "id",
293 "threadId",
294 "turnId",
295 "requestId",
296 "session_id",
297 "status",
298 "is_error",
299 "api_error_status",
300 "terminal_reason",
301 "stop_reason",
302 "operation",
303 "code",
304 "willRetry",
305 "message",
306 "event",
307 "payload",
308 "params",
309 "result",
310 "thread",
311 "turn",
312 "error",
313 "turns",
314 "items",
315 "content",
316] as const;
317
318function summarizeProviderEvent(event: unknown): unknown {
319 let remainingFields = 128;
320 let remainingCharacters = 8 * 1024;
321 const summarize = (value: unknown, depth: number): unknown => {
322 if (typeof value === "string") {
323 if (value.length > Math.min(1_024, remainingCharacters)) {
324 return { omittedCharacters: value.length };
325 }
326 remainingCharacters -= value.length;
327 return value;
328 }
329 if (value === null || typeof value === "number" || typeof value === "boolean") return value;
330 if (typeof value !== "object") return undefined;
331 if (Array.isArray(value)) return { itemCount: value.length };
332 const summary: Record<string, unknown> = { truncated: true };
333 if (depth >= 6) return summary;
334 for (const key of summaryFields) {
335 if (remainingFields <= 0) break;
336 const nested = Reflect.get(value, key);
337 if (nested === undefined) continue;
338 remainingFields -= 1;
339 summary[key] = summarize(nested, depth + 1);
340 }
341 return summary;
342 };
343 try {
344 return summarize(event, 0);
345 } catch {
346 return { truncated: true };
347 }
348}
349
350export function boundProviderEventForLogging(event: unknown): unknown {
351 let remainingCharacters = MAX_RECORD_CHARACTERS;
352 let remainingFields = MAX_RECORD_FIELDS;
353 const ancestors = new WeakSet<object>();
354 const fits = (value: unknown, depth: number): boolean => {
355 if (typeof value === "string") {
356 remainingCharacters -= value.length;
357 return remainingCharacters >= 0;
358 }
359 if (typeof value !== "object" || value === null) return true;
360 if (depth > MAX_RECORD_DEPTH || ancestors.has(value)) return false;
361 if (Array.isArray(value) && value.length > remainingFields) return false;
362 ancestors.add(value);
363 for (const key in value) {
364 if (!Object.hasOwn(value, key)) continue;
365 remainingFields -= 1;
366 remainingCharacters -= key.length;
367 if (
368 remainingFields < 0 ||
369 remainingCharacters < 0 ||
370 !fits(Reflect.get(value, key), depth + 1)
371 )
372 return false;
373 }
374 ancestors.delete(value);
375 return true;
376 };
377 try {
378 if (fits(event, 0)) return event;
379 } catch {}
380 return summarizeProviderEvent(event);
381}
382
383export const writeBatchedMessages = Effect.fnUntraced(function* (
384 sink: AsyncFileSink,
385 records: ReadonlyArray<PendingRecord>,
386 maxBytes: number,
387 onWritten: (records: ReadonlyArray<PendingRecord>) => void,
388) {
389 let pendingRecords: Array<PendingRecord> = [];
390 let pendingBytes = 0;
391
392 const flush = Effect.gen(function* () {
393 if (pendingRecords.length === 0) return;
394 const writtenRecords = pendingRecords;
395 yield* sink.write(writtenRecords.map((record) => record.line).join(""));
396 onWritten(writtenRecords);
397 pendingRecords = [];
398 pendingBytes = 0;
399 });
400
401 for (const record of records) {
402 if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
403 yield* flush;
404 }
405 pendingRecords.push(record);
406 pendingBytes += record.bytes;
407 if (pendingBytes >= maxBytes) {
408 yield* flush;
409 }
410 }
411 yield* flush;
412});
413
414async function isProviderLogFile(
415 filePath: string,
416 fileName: string,
417 filePrefix: string,
418): Promise<boolean> {
419 if (!/\.log(?:\.\d+)?$/u.test(fileName)) return false;
420 if (fileName.startsWith(filePrefix)) return true;
421
422 const descriptor = await NodeFS.promises.open(filePath, "r");
423 try {
424 const header = Buffer.alloc(256);
425 const { bytesRead } = await descriptor.read(header, 0, header.byteLength, 0);
426 return /^\[[^\]\r\n]+\] (?:NTIVE|CANON|ORCH): /u.test(header.toString("utf8", 0, bytesRead));
427 } finally {
428 await descriptor.close();
429 }
430}
431
432async function enforceRetention(input: {
433 readonly directory: string;
434 readonly maxTotalBytes: number;
435 readonly maxAgeMs: number;
436 readonly activeFilePaths: ReadonlySet<string>;
437 readonly filePrefix: string;
438 readonly now: number;
439}): Promise<RetentionResult> {
440 const failures: Array<FileOperationFailure> = [];
441 interface RetentionEntry {
442 readonly name: string;
443 readonly members: Array<{ path: string; size: number }>;
444 mtimeMs: number;
445 }
446 const files = new Map<string, RetentionEntry>();
447 let totalBytes = 0;
448 const unreadable = new Set<string>();
449
450 let entries: ReadonlyArray<NodeFS.Dirent>;
451 try {
452 entries = await NodeFS.promises.readdir(input.directory, { withFileTypes: true });
453 } catch (cause) {
454 return { failures: [{ filePath: input.directory, cause }] };
455 }
456
457 const pending = new Set<string>();
458 for (const entry of entries) {
459 if (!entry.isFile()) continue;
460 const base = rotationSidecarBase(entry.name);
461 if (base?.startsWith(input.filePrefix) && base.endsWith(".log")) pending.add(base);
462 }
463
464 for (const entry of entries) {
465 if (!entry.isFile()) continue;
466 const filePath = NodePath.join(input.directory, entry.name);
467 const sidecar = rotationSidecarBase(entry.name);
468 const base = sidecar ?? entry.name.replace(/\.\d+$/u, "");
469 const group = pending.has(base) ? base : entry.name;
470 try {
471 if (
472 !(sidecar && pending.has(sidecar)) &&
473 !(await isProviderLogFile(filePath, entry.name, input.filePrefix))
474 )
475 continue;
476 const stat = await NodeFS.promises.stat(filePath);
477 const file = files.get(group) ?? { name: group, members: [], mtimeMs: stat.mtimeMs };
478 file.members.push({ path: filePath, size: stat.size });
479 file.mtimeMs = Math.max(file.mtimeMs, stat.mtimeMs);
480 totalBytes += stat.size;
481 files.set(group, file);
482 } catch (cause) {
483 unreadable.add(group);
484 failures.push({ filePath, cause });
485 }
486 }
487
488 const removalOrder = (path: string) =>
489 path.endsWith(".rotating.json") ? 2 : path.endsWith(".rotating") ? 1 : 0;
490 const remove = async (file: RetentionEntry) => {
491 if (
492 unreadable.has(file.name) ||
493 input.activeFilePaths.has(NodePath.join(input.directory, file.name))
494 ) {
495 return false;
496 }
497 // Keep the staged file and journal until the other payload files have been removed.
498 file.members.sort((left, right) => removalOrder(left.path) - removalOrder(right.path));
499 while (file.members.length > 0) {
500 const { path: filePath, size } = file.members[0]!;
501 try {
502 await NodeFS.promises.rm(filePath, { force: true });
503 } catch (cause) {
504 failures.push({ filePath, cause });
505 return false;
506 }
507 file.members.shift();
508 totalBytes -= size;
509 }
510 return true;
511 };
512
513 const retained: RetentionEntry[] = [];
514 for (const file of files.values()) {
515 if (input.now - file.mtimeMs <= input.maxAgeMs || !(await remove(file))) retained.push(file);
516 }
517
518 for (const file of retained.toSorted(
519 (left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name),
520 )) {
521 if (totalBytes <= input.maxTotalBytes) break;
522 await remove(file);
523 }
524
525 return { failures };
526}
527
528function resolveOptions(options: EventNdjsonLogStoreOptions): Effect.Effect<ResolvedOptions> {
529 const resolved = {
530 maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
531 maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
532 batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
533 maxTotalBytes: DEFAULT_MAX_TOTAL_BYTES,
534 maxAgeMs: DEFAULT_MAX_AGE_MS,
535 retentionCheckIntervalMs: DEFAULT_RETENTION_CHECK_INTERVAL_MS,
536 maxBufferedBytes: DEFAULT_MAX_BUFFERED_BYTES,
537 maxBufferedRecords: DEFAULT_MAX_BUFFERED_RECORDS,
538 attribution: options.attribution,
539 } satisfies ResolvedOptions;
540
541 return Effect.succeed(resolved);
542}
543
544const drainPending = Effect.fnUntraced(function* (input: {
545 readonly directory: string;
546 readonly options: ResolvedOptions;
547 readonly state: StoreState;
548 readonly filePrefix: string;
549 readonly now: number;
550 readonly timerFired: boolean;
551 readonly close: boolean;
552 readonly makeSink: (
553 filePath: string,
554 ) => Effect.Effect<AsyncFileSink, Effect.Error<ReturnType<typeof makeAsyncRotatingFileSink>>>;
555}): Effect.fn.Return<readonly [DrainResult, StoreState]> {
556 if (input.state.closed) {
557 return [{ attributions: [], failures: [] }, input.state];
558 }
559
560 const sinks = new Map(input.state.sinks);
561 const writtenSegments = new Set(input.state.writtenSinceRetention);
562 const failures: Array<FileOperationFailure> = [];
563 const attributionByStream = new Map<
564 EventNdjsonStream,
565 { count: number; logicalWriteBytes: number }
566 >();
567 const recordsBySegment = new Map<string, Array<PendingRecord>>();
568
569 for (const record of input.state.pending) {
570 const records = recordsBySegment.get(record.threadSegment) ?? [];
571 records.push(record);
572 recordsBySegment.set(record.threadSegment, records);
573 }
574
575 for (const [threadSegment, records] of recordsBySegment) {
576 const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);
577 writtenSegments.add(threadSegment);
578 let sink = sinks.get(threadSegment);
579 if (!sink) {
580 const created = yield* input.makeSink(filePath).pipe(Effect.result);
581 if (Result.isFailure(created)) {
582 failures.push({ filePath, cause: created.failure });
583 continue;
584 }
585 sink = created.success;
586 sinks.set(threadSegment, sink);
587 }
588
589 const written = yield* writeBatchedMessages(
590 sink,
591 records,
592 input.options.maxBytes,
593 (writtenRecords) => {
594 for (const record of writtenRecords) {
595 const current = attributionByStream.get(record.stream) ?? {
596 count: 0,
597 logicalWriteBytes: 0,
598 };
599 attributionByStream.set(record.stream, {
600 count: current.count + 1,
601 logicalWriteBytes: current.logicalWriteBytes + record.bytes,
602 });
603 }
604 },
605 ).pipe(Effect.result);
606 if (Result.isFailure(written)) {
607 sinks.delete(threadSegment);
608 failures.push({ filePath, cause: written.failure });
609 }
610 }
611
612 const retentionDue =
613 input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
614 if (retentionDue) {
615 // A sink idle for a whole retention interval reopens from disk on its next
616 // write, so retention may remove its files without leaving a stale size.
617 for (const threadSegment of sinks.keys()) {
618 if (!writtenSegments.has(threadSegment)) sinks.delete(threadSegment);
619 }
620 }
621 const retention = retentionDue
622 ? yield* Effect.promise(() =>
623 enforceRetention({
624 directory: input.directory,
625 maxTotalBytes: input.options.maxTotalBytes,
626 maxAgeMs: input.options.maxAgeMs,
627 activeFilePaths: new Set(
628 Array.from(writtenSegments, (threadSegment) =>
629 providerLogPath(input.directory, input.filePrefix, threadSegment),
630 ),
631 ),
632 filePrefix: input.filePrefix,
633 now: input.now,
634 }),
635 )
636 : { failures: [] };
637
638 return [
639 {
640 attributions: Array.from(attributionByStream, ([stream, value]) => ({
641 stream,
642 ...value,
643 })),
644 failures: [...failures, ...retention.failures],
645 },
646 {
647 pending: [],
648 pendingBytes: 0,
649 sinks,
650 writtenSinceRetention: retentionDue ? new Set() : writtenSegments,
651 flushScheduled: input.timerFired ? false : input.state.flushScheduled,
652 closed: input.close,
653 lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
654 },
655 ];
656});
657
658const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
659 return yield* encodeUnknownJsonString(event).pipe(
660 Effect.catch((error) =>
661 logWarning("failed to serialize provider event log record", {
662 errorTag: errorTag(error),
663 }).pipe(Effect.as(undefined)),
664 ),
665 );
666});
667
668export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
669 filePath: string,
670 options: EventNdjsonLogStoreOptions = {},
671): Effect.fn.Return<
672 EventNdjsonLogStore,
673 EventNdjsonLogStoreError,
674 FileSystem.FileSystem | Path.Path
675> {
676 const fs = yield* FileSystem.FileSystem;
677 const path = yield* Path.Path;
678 const resolved = yield* resolveOptions(options);
679 const directory = NodePath.dirname(filePath);
680 const filePrefix = providerLogPrefix(filePath);
681
682 yield* fs
683 .makeDirectory(directory, { recursive: true })
684 .pipe(Effect.mapError((cause) => new EventNdjsonLogDirectoryError({ directory, cause })));
685 const makeSink = (filePath: string) =>
686 makeAsyncRotatingFileSink({
687 filePath,
688 maxBytes: resolved.maxBytes,
689 maxFiles: resolved.maxFiles,
690 }).pipe(
691 Effect.provideService(FileSystem.FileSystem, fs),
692 Effect.provideService(Path.Path, path),
693 );
694
695 const initializedAt = yield* Clock.currentTimeMillis;
696 const initialRetention = yield* Effect.promise(() =>
697 enforceRetention({
698 directory,
699 maxTotalBytes: resolved.maxTotalBytes,
700 maxAgeMs: resolved.maxAgeMs,
701 activeFilePaths: new Set(),
702 filePrefix,
703 now: initializedAt,
704 }),
705 );
706 for (const failure of initialRetention.failures) {
707 yield* logWarning("provider event log retention failed", {
708 filePath: failure.filePath,
709 errorTag: errorTag(failure.cause),
710 });
711 }
712
713 const stateRef = yield* SynchronizedRef.make<StoreState>({
714 pending: [],
715 pendingBytes: 0,
716 sinks: new Map(),
717 writtenSinceRetention: new Set(),
718 flushScheduled: false,
719 closed: false,
720 lastRetentionAt: initializedAt,
721 });
722 const timerScope = yield* Scope.make();
723
724 const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
725 const startedAt = yield* Clock.currentTimeMillis;
726 const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
727 drainPending({
728 directory,
729 options: resolved,
730 state,
731 filePrefix,
732 now: startedAt,
733 timerFired,
734 close,
735 makeSink,
736 }),
737 );
738
739 for (const failure of result.failures) {
740 yield* logWarning("provider event log write or retention failed", {
741 filePath: failure.filePath,
742 errorTag: errorTag(failure.cause),
743 });
744 }
745
746 if (resolved.attribution && result.attributions.length > 0) {
747 const completedAt = yield* Clock.currentTimeMillis;
748 const durationMs = Math.max(0, completedAt - startedAt);
749 const totalBytes = result.attributions.reduce(
750 (total, entry) => total + entry.logicalWriteBytes,
751 0,
752 );
753 yield* Effect.forEach(
754 result.attributions,
755 (entry) =>
756 resolved.attribution?.record({
757 component: "provider-event-log",
758 operation: `${entry.stream}.append`,
759 logicalWriteBytes: entry.logicalWriteBytes,
760 count: entry.count,
761 durationMs:
762 totalBytes === 0
763 ? 0
764 : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
765 }) ?? Effect.void,
766 { discard: true },
767 );
768 }
769 }, Effect.uninterruptible);
770
771 const scheduleFlush = Effect.fnUntraced(function* () {
772 yield* Effect.forkIn(
773 Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
774 timerScope,
775 { startImmediately: true },
776 );
777 });
778
779 const close = Effect.fnUntraced(function* () {
780 yield* flush(false, true);
781 yield* Scope.close(timerScope, Exit.void);
782 });
783
784 const loggerViews = new Map<EventNdjsonStream, ProviderEventLoggers.EventNdjsonLogger>();
785 const logger = (stream: EventNdjsonStream): ProviderEventLoggers.EventNdjsonLogger => {
786 const existing = loggerViews.get(stream);
787 if (existing) return existing;
788
789 const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
790 if (!shouldPersistProviderEvent(stream, event)) return;
791 let payload = yield* serializeEvent(boundProviderEventForLogging(event));
792 if (payload === undefined) return;
793 // Escaping can expand strings beyond their input size.
794 if (Buffer.byteLength(payload) > MAX_RECORD_CHARACTERS) {
795 payload = yield* serializeEvent(summarizeProviderEvent(event));
796 if (payload === undefined) return;
797 }
798
799 const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
800 const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
801 const bytes = Buffer.byteLength(line);
802 const threadSegment = resolveThreadSegment(threadId);
803 const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
804 if (state.closed) {
805 return Effect.succeed([{ flush: false }, state] as const);
806 }
807 const pending = state.pending;
808 pending.push({ stream, threadSegment, line, bytes });
809 const pendingBytes = state.pendingBytes + bytes;
810 const flush =
811 resolved.batchWindowMs === 0 ||
812 pending.length >= resolved.maxBufferedRecords ||
813 pendingBytes >= resolved.maxBufferedBytes;
814 const schedule = !flush && !state.flushScheduled;
815 const nextState = {
816 ...state,
817 pending,
818 pendingBytes,
819 flushScheduled: state.flushScheduled || schedule,
820 };
821 return (schedule ? scheduleFlush() : Effect.void).pipe(
822 Effect.as([{ flush }, nextState] as const),
823 );
824 }).pipe(Effect.uninterruptible);
825
826 if (action.flush) {
827 yield* flush(false, false);
828 }
829 });
830
831 const view = {
832 filePath,
833 write,
834 close: () => Effect.void,
835 } satisfies ProviderEventLoggers.EventNdjsonLogger;
836 loggerViews.set(stream, view);
837 return view;
838 };
839
840 return { filePath, logger, close } satisfies EventNdjsonLogStore;
841});