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