Skip to content

Commit f9e7a4c

Browse files
authored
fix(agents): guard null response body in proxy stream reader (#107325)
* fix(agents): guard null response body in proxy stream reader The proxy transport used response.body! (non-null assertion) to enter the SSE read loop without checking whether the body is present. response.ok does not guarantee response.body is non-null — empty 200 responses and prematurely-closed connections leave body=null while ok=true. Sibling transports in the same repository already guard this case: - provider-transport-fetch.ts:148,385,541 - anthropic-transport-stream.ts:847 - openai-completions-transport.ts:272 - mcp-http-fetch.ts:60,76 (added in #98143) Add the same guard before getReader() so the caller receives a business- level diagnostic ("Proxy returned an empty response body") instead of the misleading JS runtime error "Cannot read properties of null (reading 'getReader')". The try-catch in streamProxy already catches the error and pushes it as a stream event, so this does not introduce a new crash — it replaces an internal TypeError with a meaningful error. * test(agents): cover null response body in proxy stream reader
1 parent 9e3a50b commit f9e7a4c

2 files changed

Lines changed: 34 additions & 1 deletion

File tree

‎src/agents/runtime/proxy.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,4 +598,33 @@ describe("streamProxy", () => {
598598
errorMessage: "Proxy stream ended before terminal event",
599599
});
600600
});
601+
602+
it("emits a business-level error when the proxy returns a null response body", async () => {
603+
vi.stubGlobal(
604+
"fetch",
605+
vi.fn(
606+
async () =>
607+
({
608+
ok: true,
609+
status: 200,
610+
body: null,
611+
}) as Response,
612+
),
613+
);
614+
615+
const stream = streamProxy(model, context, {
616+
authToken: "token",
617+
proxyUrl: "https://proxy.example",
618+
});
619+
const events = [];
620+
for await (const event of stream) {
621+
events.push(event);
622+
}
623+
624+
expect(events.at(-1)?.type).toBe("error");
625+
await expect(stream.result()).resolves.toMatchObject({
626+
stopReason: "error",
627+
errorMessage: "Proxy returned an empty response body",
628+
});
629+
});
601630
});

‎src/agents/runtime/proxy.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,11 @@ export function streamProxy(
340340
throw new Error(errorMessage);
341341
}
342342

343-
reader = response.body!.getReader();
343+
if (!response.body) {
344+
throw new Error("Proxy returned an empty response body");
345+
}
346+
347+
reader = response.body.getReader();
344348
const sseReader = createSseByteGuard(reader, {
345349
maxBytes: PROXY_SSE_STREAM_MAX_BYTES,
346350
onOverflow: ({ maxBytes }) => new Error(`Proxy SSE stream exceeded ${maxBytes} bytes`),

0 commit comments

Comments
 (0)