diff --git a/src/agents/transport-stream-shared.test.ts b/src/agents/transport-stream-shared.test.ts index bd7ed3cb76d..b11270a63a2 100644 --- a/src/agents/transport-stream-shared.test.ts +++ b/src/agents/transport-stream-shared.test.ts @@ -2,6 +2,7 @@ // final/error stream termination helpers used by provider transports. import { describe, expect, it, vi } from "vitest"; import { + assignTransportErrorDetails, failTransportStream, finalizeTransportStream, mergeTransportHeaders, @@ -100,4 +101,17 @@ describe("transport stream shared helpers", () => { }); expect(end).toHaveBeenCalledTimes(1); }); + + it("does not throw while recording non-JSON transport rejections", () => { + const circular: Record = {}; + circular.self = circular; + + for (const error of [1n, circular]) { + const output: { stopReason: string; errorMessage?: string } = { stopReason: "stop" }; + + expect(() => assignTransportErrorDetails(output, error)).not.toThrow(); + expect(output.stopReason).toBe("error"); + expect(output.errorMessage).toBeTruthy(); + } + }); }); diff --git a/src/agents/transport-stream-shared.ts b/src/agents/transport-stream-shared.ts index 965b9bfbbca..097fc5d0861 100644 --- a/src/agents/transport-stream-shared.ts +++ b/src/agents/transport-stream-shared.ts @@ -178,6 +178,21 @@ function stringifyErrorBody(value: unknown): string | undefined { } } +function stringifyTransportErrorMessage(value: unknown): string | undefined { + if (value instanceof Error) { + return value.message; + } + const encoded = stringifyErrorBody(value); + if (encoded !== undefined) { + return encoded; + } + try { + return String(value); + } catch { + return undefined; + } +} + function normalizeTransportErrorBody(value: unknown): string | undefined { const text = stringifyErrorBody(value); if (!text?.trim()) { @@ -216,7 +231,7 @@ export function assignTransportErrorDetails( signal?: AbortSignal, ): void { output.stopReason = signal?.aborted ? "aborted" : "error"; - output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + output.errorMessage = stringifyTransportErrorMessage(error); Object.assign(output, extractTransportErrorDetails(error)); }