From d16f79f49d2415ed4cd6761c6d52805de4e1b528 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Fri, 15 May 2026 08:41:03 +0800 Subject: [PATCH] fix(providers): add safe json response helper --- src/agents/provider-http-errors.test.ts | 12 ++++++++++++ src/agents/provider-http-errors.ts | 8 ++++++++ src/plugin-sdk/provider-http.ts | 1 + 3 files changed, 21 insertions(+) diff --git a/src/agents/provider-http-errors.test.ts b/src/agents/provider-http-errors.test.ts index 925399f695ab..bf97a54e7e37 100644 --- a/src/agents/provider-http-errors.test.ts +++ b/src/agents/provider-http-errors.test.ts @@ -4,6 +4,7 @@ import { assertOkOrThrowHttpError, extractProviderErrorDetail, extractProviderRequestId, + readProviderJsonResponse, } from "./provider-http-errors.js"; describe("provider error utils", () => { @@ -54,4 +55,15 @@ describe("provider error utils", () => { "Legacy provider error (HTTP 400): Bad request [code=invalid_request] [request_id=req_legacy]", ); }); + + it("wraps malformed successful JSON responses with provider labels", async () => { + const response = new Response("{ nope", { + status: 200, + headers: { "content-type": "application/json" }, + }); + + await expect(readProviderJsonResponse(response, "Provider catalog failed")).rejects.toThrow( + "Provider catalog failed: malformed JSON response", + ); + }); }); diff --git a/src/agents/provider-http-errors.ts b/src/agents/provider-http-errors.ts index 9ef6756d1ffd..0c00ec8aa058 100644 --- a/src/agents/provider-http-errors.ts +++ b/src/agents/provider-http-errors.ts @@ -163,3 +163,11 @@ export async function assertOkOrThrowHttpError(response: Response, label: string } throw await createProviderHttpError(response, label, { statusPrefix: "HTTP " }); } + +export async function readProviderJsonResponse(response: Response, label: string): Promise { + try { + return (await response.json()) as T; + } catch (cause) { + throw new Error(`${label}: malformed JSON response`, { cause }); + } +} diff --git a/src/plugin-sdk/provider-http.ts b/src/plugin-sdk/provider-http.ts index ae77ae55e649..67abef98ea98 100644 --- a/src/plugin-sdk/provider-http.ts +++ b/src/plugin-sdk/provider-http.ts @@ -9,6 +9,7 @@ export { extractProviderRequestId, formatProviderErrorPayload, formatProviderHttpErrorMessage, + readProviderJsonResponse, readResponseTextLimited, truncateErrorDetail, } from "../agents/provider-http-errors.js";