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