@@ -4,6 +4,10 @@ import { join } from "node:path";
44
55 let writer: ReturnType<ReturnType<typeof Bun.file>["writer"]> | null = null;
66
7+/** Cap individual log entries to prevent unbounded serialization (e.g. RetryError
8+ * objects that embed the full requestBodyValues / conversation history). */
9+const MAX_ENTRY_BYTES = 8 * 1024;
10+
711 export function initApiLog(): void {
812 if (writer) return;
913
@@ -16,6 +20,41 @@ export function initApiLog(): void {
1620 writer = Bun.file(logPath).writer();
1721 }
1822
23+function isObject(v: unknown): v is Record<string, unknown> {
24+ return typeof v === "object" && v !== null;
25+}
26+
27+/**
28+ * Strip large/opaque fields from error objects before serialization.
29+ * AI SDK errors embed full `requestBodyValues` (the entire conversation) and
30+ * `responseBody` (full HTML error pages) — serializing these can produce
31+ * tens of megabytes per error and block the event loop on flush.
32+ */
33+function sanitizeForLog(data: unknown): unknown {
34+ if (!isObject(data)) return data;
35+
36+ const DROP_KEYS = new Set([
37+ "requestBodyValues",
38+ "responseBody",
39+ "responseHeaders",
40+ "stack",
41+ ]);
42+
43+ const result: Record<string, unknown> = {};
44+ for (const key in data) {
45+ if (DROP_KEYS.has(key)) continue;
46+ const value = data[key];
47+ if (key === "errors" && Array.isArray(value)) {
48+ result[key] = value.map((e) => sanitizeForLog(e));
49+ } else if (key === "lastError" && isObject(value)) {
50+ result[key] = sanitizeForLog(value);
51+ } else {
52+ result[key] = value;
53+ }
54+ }
55+ return result;
56+}
57+
1958 export function logApiEvent(event: string, data?: unknown): void {
2059 if (!writer) return;
2160
@@ -24,7 +63,12 @@ export function logApiEvent(event: string, data?: unknown): void {
2463
2564 if (data !== undefined) {
2665 try {
27- entry += JSON.stringify(data, null, 2)
66+ const safe = sanitizeForLog(data);
67+ let serialized = JSON.stringify(safe, null, 2);
68+ if (Buffer.byteLength(serialized, "utf8") > MAX_ENTRY_BYTES) {
69+ serialized = `${serialized.slice(0, MAX_ENTRY_BYTES)}\n …truncated`;
70+ }
71+ entry += serialized
2872 .split("\n")
2973 .map((line) => ` ${line}`)
3074 .join("\n");