Skip to content

Commit fd36d33

Browse files
committed
fix(ai): prevent crash from circular references in provider error handlers
JSON.stringify(error) throws TypeError when the error object contains circular references (common for network/fetch errors with socket properties), which crashes the catch block and prevents stream.push() and stream.end() from executing, causing unhandled rejections and resource leaks. Introduce safeStringifyError() that falls back to String() when JSON.stringify fails, and apply it to google-shared, openai-completions, and anthropic providers. Fixes #106568 Fixes #106570
1 parent c93e420 commit fd36d33

5 files changed

Lines changed: 59 additions & 3 deletions

File tree

‎packages/ai/src/providers/anthropic.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ import {
8484
} from "./anthropic-usage.js";
8585
import { resolveCacheRetention } from "./cache-retention.js";
8686
import { resolveCloudflareBaseUrl } from "./cloudflare.js";
87+
import { safeStringifyError } from "./error-utils.js";
8788
import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
8889
import { adjustMaxTokensForThinking, buildBaseOptions } from "./simple-options.js";
8990
import {
@@ -936,7 +937,7 @@ export const streamAnthropic: StreamFunction<"anthropic-messages", AnthropicOpti
936937
output.content = [];
937938
}
938939
output.stopReason = requestOptions?.signal?.aborted ? "aborted" : "error";
939-
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
940+
output.errorMessage = safeStringifyError(error);
940941
stream.push({ type: "error", reason: output.stopReason, error: output });
941942
stream.end();
942943
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { describe, expect, it } from "vitest";
2+
import { safeStringifyError } from "./error-utils.js";
3+
4+
describe("safeStringifyError", () => {
5+
it("returns error.message for Error instances", () => {
6+
const error = new Error("something went wrong");
7+
expect(safeStringifyError(error)).toBe("something went wrong");
8+
});
9+
10+
it("returns error.message for subclassed errors", () => {
11+
const error = new TypeError("type mismatch");
12+
expect(safeStringifyError(error)).toBe("type mismatch");
13+
});
14+
15+
it("stringifies plain objects", () => {
16+
expect(safeStringifyError({ code: 42 })).toBe('{"code":42}');
17+
});
18+
19+
it("stringifies primitives", () => {
20+
expect(safeStringifyError("hello")).toBe('"hello"');
21+
expect(safeStringifyError(123)).toBe("123");
22+
expect(safeStringifyError(true)).toBe("true");
23+
expect(safeStringifyError(null)).toBe("null");
24+
});
25+
26+
it("falls back to String() for circular references", () => {
27+
const obj: Record<string, unknown> = { name: "circular" };
28+
obj.self = obj;
29+
const result = safeStringifyError(obj);
30+
expect(result).toBe("[object Object]");
31+
});
32+
33+
it("falls back to String() for objects that throw on stringify", () => {
34+
const obj = {
35+
get toJSON() {
36+
throw new Error("nope");
37+
},
38+
};
39+
const result = safeStringifyError(obj);
40+
expect(typeof result).toBe("string");
41+
expect(result.length).toBeGreaterThan(0);
42+
});
43+
});
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export function safeStringifyError(error: unknown): string {
2+
if (error instanceof Error) {
3+
return error.message;
4+
}
5+
try {
6+
return JSON.stringify(error);
7+
} catch {
8+
return String(error);
9+
}
10+
}

‎packages/ai/src/providers/google-shared.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import type {
3232
import type { AssistantMessageEventStream } from "../utils/event-stream.js";
3333
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
3434
import { stripSystemPromptCacheBoundary } from "../utils/system-prompt-cache-boundary.js";
35+
import { safeStringifyError } from "./error-utils.js";
3536
import { describeToolResultMediaPlaceholder, extractToolResultText } from "./tool-result-text.js";
3637
import { transformMessages } from "./transform-messages.js";
3738

@@ -468,7 +469,7 @@ export async function runGoogleGenerateContentLifecycle<T extends GoogleApiType>
468469
}
469470
}
470471
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
471-
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
472+
output.errorMessage = safeStringifyError(error);
472473
stream.push({ type: "error", reason: output.stopReason, error: output });
473474
stream.end();
474475
}

‎packages/ai/src/providers/openai-completions.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
} from "../utils/system-prompt-cache-boundary.js";
5353
import { resolveCacheRetention } from "./cache-retention.js";
5454
import { isCloudflareProvider, resolveCloudflareBaseUrl } from "./cloudflare.js";
55+
import { safeStringifyError } from "./error-utils.js";
5556
import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
5657
import { clampOpenAIPromptCacheKey } from "./openai-prompt-cache.js";
5758
import { mapOpenAIStopReason } from "./openai-stop-reason.js";
@@ -564,7 +565,7 @@ export const streamOpenAICompletions: StreamFunction<
564565
delete (block as { streamIndex?: number }).streamIndex;
565566
}
566567
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
567-
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
568+
output.errorMessage = safeStringifyError(error);
568569
// Some providers via OpenRouter give additional information in this field.
569570
const rawMetadata = (error as { error?: { metadata?: { raw?: string } } })?.error?.metadata
570571
?.raw;

0 commit comments

Comments
 (0)