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