diff --git a/CHANGELOG.md b/CHANGELOG.md index b027b6e..26f2ced 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ existing `0.1.0` release; earlier development prereleases are not listed. ### Fixed +- Decode SSE streams over raw byte chunks using WHATWG CR/LF/CRLF line splitting instead of `httpx`'s `iter_lines()`, preventing Unicode line separators (`\u2028`, `\u2029`, `\x85`) inside JSON payloads from splitting frames and failing with `APIResponseValidationError`. - Preserve historical string `configs[].permission_policy` values when leniently parsing Managed Agent, Session and Thread tool snapshots. Tools and configs retain model attribute access instead of becoming Browser models or raw dictionaries; known Browser/media variants keep their concrete types and strict validation still rejects invalid payloads. - Expose Managed MCP toolsets' top-level `permission_policy` in requests and Agent/Session/Thread responses, including `always_deny` without `configs`. Set server-wide defaults here: nested `default_config.permission_policy` is retained unchanged for compatibility but does not set the MCP default; omitting the top-level policy defaults to allow. - Accept `"latest"` and positive integer strings for child Agent `version` in Managed Agent multiagent rosters through the new `MultiagentAgentParams` type, and parse saved `"latest"` versions in Agent responses, including with `_strict_response_validation=True`. `MultiagentAgentUnion.version` is now typed `int | str`; Session and Deployment Agent references keep numeric versions. diff --git a/src/qca/common/_streaming.py b/src/qca/common/_streaming.py index 191fe38..a9bbf76 100644 --- a/src/qca/common/_streaming.py +++ b/src/qca/common/_streaming.py @@ -1,6 +1,8 @@ from __future__ import annotations +import codecs import json +import re import socket import threading from collections.abc import AsyncIterator, Iterator @@ -13,6 +15,8 @@ T = TypeVar("T") +_SSE_NEWLINE_RE = re.compile(r"\r\n|\r|\n") + class SSEDecoder: def __init__(self) -> None: @@ -47,6 +51,50 @@ def __init__(self, response: httpx.Response, cast_to: Any, *, strict: bool = Fal self._strict = strict self._decoder = SSEDecoder() self._last_event_id: str | None = None + self._byte_decoder = codecs.getincrementaldecoder(response.encoding or "utf-8")(errors="replace") + self._line_buffer = "" + self._trailing_cr = False + self._seen_text = False + + def _decode_chunk(self, chunk: bytes) -> list[str]: + if not chunk: + return [] + text = self._byte_decoder.decode(chunk, final=False) + return self._feed_text(text) if text else [] + + def _flush_lines(self) -> list[str]: + text = self._byte_decoder.decode(b"", final=True) + lines = self._feed_text(text) if text else [] + if self._line_buffer: + lines.append(self._line_buffer) + self._line_buffer = "" + self._trailing_cr = False + return lines + + def _feed_text(self, text: str) -> list[str]: + if not self._seen_text: + self._seen_text = True + if text.startswith("\ufeff"): + text = text[1:] + if not text: + return [] + if self._trailing_cr: + self._trailing_cr = False + if text.startswith("\n"): + text = text[1:] + if not text: + return [] + data = self._line_buffer + text + lines: list[str] = [] + start = 0 + length = len(data) + for match in _SSE_NEWLINE_RE.finditer(data): + lines.append(data[start : match.start()]) + start = match.end() + if match.group(0) == "\r" and start == length: + self._trailing_cr = True + self._line_buffer = data[start:] + return lines @property def last_event_id(self) -> str | None: @@ -127,7 +175,17 @@ def __next__(self) -> T: def _iter_events(self) -> Iterator[T]: try: - for line in self.response.iter_lines(): + for chunk in self.response.iter_bytes(): + for line in self._decode_chunk(chunk): + frame = self._decoder.decode(line) + if frame is None: + continue + if frame[0] == "ping": + continue + if frame[1] == "[DONE]": + return + yield self._parse(frame) + for line in self._flush_lines(): frame = self._decoder.decode(line) if frame is None: continue @@ -163,7 +221,17 @@ async def __anext__(self) -> T: async def _iter_events(self) -> AsyncIterator[T]: try: - async for line in self.response.aiter_lines(): + async for chunk in self.response.aiter_bytes(): + for line in self._decode_chunk(chunk): + frame = self._decoder.decode(line) + if frame is None: + continue + if frame[0] == "ping": + continue + if frame[1] == "[DONE]": + return + yield self._parse(frame) + for line in self._flush_lines(): frame = self._decoder.decode(line) if frame is None: continue diff --git a/tests/test_streaming.py b/tests/test_streaming.py index 58c8dfd..c7c1c5b 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -67,6 +67,64 @@ def handle(request): assert chunks.closed +@pytest.mark.parametrize("separator", ["\u2028", "\u2029", "\x85"]) +def test_sse_preserves_unicode_line_separators_inside_json_payloads(separator): + body = ( + "\ufeff" + ": comment\x0bwith\x0ccontrols\r\n" + f'id: sep-1\r\nevent: agent.message\r\ndata: {{"content":[{{"type":"text","text":"before{separator}after"}}]}}\r\n\r\n' + 'id: sep-2\revent: agent.message\rdata: {"content":[{"type":"text","text":"cr-only"}]}\r\r' + ).encode("utf-8") + chunks = Chunks(body) + + with Forward( + pat="test", + http_client=httpx.Client( + transport=httpx.MockTransport( + lambda _: httpx.Response(200, stream=chunks, headers={"content-type": "text/event-stream"}) + ) + ), + ) as client: + with client.sessions.events.stream("session") as stream: + events = list(stream) + assert [event.id for event in events] == ["sep-1", "sep-2"] + assert events[0].content[0]["text"] == f"before{separator}after" + assert events[1].content[0]["text"] == "cr-only" + assert chunks.closed + + +async def test_async_sse_preserves_unicode_line_separators_and_split_crlf(): + class SplitChunks(httpx.AsyncByteStream): + closed = False + + async def __aiter__(self): + payload = 'id: a1\r\nevent: agent.message\r\ndata: {"content":[{"type":"text","text":"line\u2028break"}]}\r\n\r\n'.encode( + "utf-8" + ) + # Deliver one byte at a time so CRLF and multi-byte UTF-8 cross chunk boundaries. + for index in range(len(payload)): + yield payload[index : index + 1] + + async def aclose(self): + self.closed = True + + chunks = SplitChunks() + async with AsyncManaged( + pat="test", + http_client=httpx.AsyncClient( + transport=httpx.MockTransport( + lambda _: httpx.Response(200, stream=chunks, headers={"content-type": "text/event-stream"}) + ) + ), + ) as client: + async with await client.sessions.events.stream("session") as stream: + events = [event async for event in stream] + assert len(events) == 1 + assert events[0].id == "a1" + assert events[0].content[0].text == "line\u2028break" + assert chunks.closed + + @pytest.mark.parametrize( "body,error", [