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