CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat: JSON repair and partial JSON parsing for streaming (#8)
Chris162166cdc806
diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.pyindex 09f0a3c..5794fd4 100644--- a/cubepi/providers/openai.py+++ b/cubepi/providers/openai.py@@ -5,6 +5,8 @@ import jsonimport timefrom typing import Any+from cubepi.utils.json_parse import parse_streaming_json+from cubepi.providers.base import (AssistantMessage,Message,@@ -176,14 +178,7 @@ class OpenAIProvider:)for idx, tc_data in tool_calls_in_progress.items():- try:- args = (- json.loads(tc_data["arguments"])- if tc_data["arguments"]- else {}- )- except json.JSONDecodeError:- args = {}+ args = parse_streaming_json(tc_data["arguments"])for i, c in enumerate(partial.content):if isinstance(c, ToolCall) and c.id == tc_data["id"]:partial.content[i] = ToolCall(diff --git a/cubepi/utils/__init__.py b/cubepi/utils/__init__.pynew file mode 100644index 0000000..3eb4fd5--- /dev/null+++ b/cubepi/utils/__init__.py@@ -0,0 +1,5 @@+"""cubepi.utils — utility modules."""++from cubepi.utils.json_parse import parse_streaming_json, repair_json++__all__ = ["parse_streaming_json", "repair_json"]diff --git a/cubepi/utils/json_parse.py b/cubepi/utils/json_parse.pynew file mode 100644index 0000000..4005c4f--- /dev/null+++ b/cubepi/utils/json_parse.py@@ -0,0 +1,209 @@+"""JSON repair and partial-parse utilities for streaming tool call arguments.++Provides a 3-tier fallback strategy mirroring pi-agent-core's approach:+ 1. ``json.loads(text)`` — fast path for well-formed JSON.+ 2. ``json.loads(repair_json(text))`` — fix control chars / bad escapes.+ 3. Partial-parse (close open braces/brackets/strings) for truncated JSON.+ 4. Return ``{}`` as the last resort.+"""++from __future__ import annotations++import json+import re++# Escapes that the JSON spec allows after a backslash.+_VALID_ESCAPES = frozenset('"\\bfnrtu/')+++def _is_control_char(ch: str) -> bool:+ """Return True for ASCII control characters (0x00-0x1F)."""+ cp = ord(ch)+ return 0x00 <= cp <= 0x1F+++def _escape_control_char(ch: str) -> str:+ """Convert an ASCII control character to its JSON escape sequence."""+ mapping = {+ "\b": "\\b",+ "\f": "\\f",+ "\n": "\\n",+ "\r": "\\r",+ "\t": "\\t",+ }+ if ch in mapping:+ return mapping[ch]+ return f"\\u{ord(ch):04x}"+++def repair_json(text: str) -> str:+ """Repair malformed JSON string literals.++ Operates character-by-character, tracking whether the cursor is inside a+ JSON string value. Inside strings it:++ * Escapes raw control characters (0x00-0x1F) that are not already+ escaped (``\\t``, ``\\n``, ``\\r`` are kept when already escaped).+ * Doubles a backslash before an invalid escape character+ (e.g. ``\\x`` becomes ``\\\\x``), making the output parseable.+ * Handles truncated backslash at end-of-string.+ """+ repaired: list[str] = []+ in_string = False+ i = 0+ length = len(text)++ while i < length:+ ch = text[i]++ # Outside a string literal — pass through, toggle on opening quote.+ if not in_string:+ repaired.append(ch)+ if ch == '"':+ in_string = True+ i += 1+ continue++ # Inside a string literal.+ if ch == '"':+ repaired.append(ch)+ in_string = False+ i += 1+ continue++ if ch == "\\":+ # Look ahead for the escape character.+ if i + 1 >= length:+ # Trailing backslash — escape it.+ repaired.append("\\\\")+ i += 1+ continue++ next_ch = text[i + 1]++ # Valid \uXXXX?+ if next_ch == "u":+ hex_digits = text[i + 2 : i + 6]+ if len(hex_digits) == 4 and re.fullmatch(r"[0-9a-fA-F]{4}", hex_digits):+ repaired.append(f"\\u{hex_digits}")+ i += 6+ continue+ # Invalid \u sequence — double the backslash and also+ # emit 'u' so we don't re-process it as an escape.+ repaired.append("\\\\u")+ i += 2+ continue++ if next_ch in _VALID_ESCAPES:+ repaired.append(f"\\{next_ch}")+ i += 2+ continue++ # Invalid escape — double the backslash so the original char is+ # preserved as a literal backslash in the output.+ repaired.append("\\\\")+ i += 1+ continue++ # Raw control character inside string — replace with escape.+ if _is_control_char(ch):+ repaired.append(_escape_control_char(ch))+ else:+ repaired.append(ch)+ i += 1++ return "".join(repaired)+++def _close_partial_json(text: str) -> str:+ """Attempt to close truncated JSON by balancing braces, brackets, and strings.++ This is intentionally simple: it scans through *text* tracking nesting+ depth for ``{}``, ``[]``, and string literals, then appends closing+ tokens in reverse order. It does **not** try to be a full parser — just+ good enough for the common streaming case where JSON is cut off mid-value.+ """+ # Stack of open tokens we need to close.+ stack: list[str] = []+ in_string = False+ i = 0+ length = len(text)++ while i < length:+ ch = text[i]++ if in_string:+ if ch == "\\":+ # Skip escaped character.+ i += 2+ continue+ if ch == '"':+ in_string = False+ if stack:+ stack.pop()+ i += 1+ continue++ if ch == '"':+ in_string = True+ stack.append('"')+ elif ch == "{":+ stack.append("}")+ elif ch == "[":+ stack.append("]")+ elif ch == "}":+ # Pop matching '{' closer.+ if stack and stack[-1] == "}":+ stack.pop()+ elif ch == "]":+ if stack and stack[-1] == "]":+ stack.pop()++ i += 1++ # Close everything that's still open, innermost first.+ closing = "".join(reversed(stack))+ return text + closing+++def parse_streaming_json(text: str | None) -> dict:+ """Parse potentially incomplete or malformed JSON from streaming.++ Uses a 3-tier fallback:+ 1. ``json.loads(text)``+ 2. ``json.loads(repair_json(text))``+ 3. Partial-parse: repair + close open braces/brackets/strings+ 4. ``{}`` as last resort++ Always returns a *dict* (or at minimum ``{}``) so callers never need+ to handle parse failures.+ """+ if not text or not text.strip():+ return {}++ # Tier 1: direct parse.+ try:+ result = json.loads(text)+ return result if isinstance(result, dict) else {}+ except (json.JSONDecodeError, ValueError):+ pass++ # Tier 2: repair then parse.+ repaired = repair_json(text)+ if repaired != text:+ try:+ result = json.loads(repaired)+ return result if isinstance(result, dict) else {}+ except (json.JSONDecodeError, ValueError):+ pass++ # Tier 3: partial parse (repair + close).+ try:+ closed = _close_partial_json(repaired)+ result = json.loads(closed)+ return result if isinstance(result, dict) else {}+ except (json.JSONDecodeError, ValueError):+ pass++ # Tier 4: give up.+ return {}diff --git a/tests/utils/__init__.py b/tests/utils/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tests/utils/test_json_parse.py b/tests/utils/test_json_parse.pynew file mode 100644index 0000000..9c72eac--- /dev/null+++ b/tests/utils/test_json_parse.py@@ -0,0 +1,252 @@+"""Tests for cubepi.utils.json_parse — repair_json and parse_streaming_json."""++from __future__ import annotations++import json++import pytest++from cubepi.utils.json_parse import (+ _close_partial_json,+ parse_streaming_json,+ repair_json,+)+++# ---------------------------------------------------------------------------+# repair_json+# ---------------------------------------------------------------------------+++class TestRepairJson:+ """Tests for repair_json()."""++ def test_valid_json_unchanged(self) -> None:+ text = '{"key": "value", "num": 42}'+ assert repair_json(text) == text++ def test_escape_raw_control_chars_in_string(self) -> None:+ # Embed a NUL and BEL inside a JSON string value.+ raw = '{"msg": "hello\x00world\x07"}'+ repaired = repair_json(raw)+ assert "\\u0000" in repaired+ assert "\\u0007" in repaired+ # Repaired text must be valid JSON.+ parsed = json.loads(repaired)+ assert parsed["msg"] == "hello\x00world\x07"++ def test_tab_newline_carriage_return_escaped(self) -> None:+ raw = '{"msg": "a\tb\nc\rd"}'+ repaired = repair_json(raw)+ assert "\\t" in repaired+ assert "\\n" in repaired+ assert "\\r" in repaired+ parsed = json.loads(repaired)+ assert parsed["msg"] == "a\tb\nc\rd"++ def test_invalid_escape_sequence_fixed(self) -> None:+ # \x is not a valid JSON escape — should become \\x+ raw = r'{"path": "C:\xampp\htdocs"}'+ repaired = repair_json(raw)+ parsed = json.loads(repaired)+ assert "xampp" in parsed["path"]+ assert "htdocs" in parsed["path"]++ def test_valid_escape_sequences_preserved(self) -> None:+ raw = r'{"msg": "line1\nline2\ttab\\backslash\"quote"}'+ repaired = repair_json(raw)+ assert repaired == raw++ def test_valid_unicode_escape_preserved(self) -> None:+ raw = r'{"emoji": "AB"}'+ repaired = repair_json(raw)+ parsed = json.loads(repaired)+ assert parsed["emoji"] == "AB"++ def test_trailing_backslash(self) -> None:+ raw = '{"val": "trailing\\'+ repaired = repair_json(raw)+ # Should double the trailing backslash.+ assert repaired.endswith("\\\\")++ def test_control_chars_outside_string_unchanged(self) -> None:+ # Control chars outside strings are passed through unchanged+ # (invalid JSON anyway, but repair_json only touches strings).+ raw = '{\n"key":\t"val"\n}'+ assert repair_json(raw) == raw++ def test_multiple_strings(self) -> None:+ raw = '{"a": "x\x01y", "b": "normal"}'+ repaired = repair_json(raw)+ parsed = json.loads(repaired)+ assert parsed["a"] == "x\x01y"+ assert parsed["b"] == "normal"++ def test_empty_string(self) -> None:+ assert repair_json("") == ""++ def test_no_strings(self) -> None:+ raw = "[1, 2, 3]"+ assert repair_json(raw) == raw++ def test_backspace_and_formfeed(self) -> None:+ raw = '{"msg": "a\x08b\x0c"}'+ repaired = repair_json(raw)+ assert "\\b" in repaired+ assert "\\f" in repaired+ parsed = json.loads(repaired)+ assert parsed["msg"] == "a\x08b\x0c"++ def test_incomplete_unicode_escape(self) -> None:+ # \u followed by fewer than 4 hex digits — backslash should be doubled.+ raw = r'{"val": "\u00G"}'+ repaired = repair_json(raw)+ # Should be parseable — the \u was treated as invalid and backslash doubled.+ parsed = json.loads(repaired)+ assert "u00G" in parsed["val"]+++# ---------------------------------------------------------------------------+# _close_partial_json+# ---------------------------------------------------------------------------+++class TestClosePartialJson:+ """Tests for the internal _close_partial_json helper."""++ def test_complete_json_unchanged(self) -> None:+ text = '{"key": "val"}'+ assert _close_partial_json(text) == text++ def test_truncated_object(self) -> None:+ text = '{"key": "val"'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert parsed == {"key": "val"}++ def test_truncated_nested_object(self) -> None:+ text = '{"a": {"b": 1'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert parsed == {"a": {"b": 1}}++ def test_truncated_array(self) -> None:+ text = '{"items": [1, 2'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert parsed == {"items": [1, 2]}++ def test_truncated_string(self) -> None:+ text = '{"key": "incom'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert parsed["key"] == "incom"++ def test_truncated_deeply_nested(self) -> None:+ text = '{"a": {"b": [{"c": "d'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert parsed["a"]["b"][0]["c"] == "d"++ def test_empty_string(self) -> None:+ assert _close_partial_json("") == ""++ def test_escaped_quote_in_string(self) -> None:+ text = r'{"key": "val\"ue'+ closed = _close_partial_json(text)+ parsed = json.loads(closed)+ assert 'val"ue' in parsed["key"]+++# ---------------------------------------------------------------------------+# parse_streaming_json+# ---------------------------------------------------------------------------+++class TestParseStreamingJson:+ """Tests for parse_streaming_json()."""++ def test_valid_json(self) -> None:+ assert parse_streaming_json('{"a": 1}') == {"a": 1}++ def test_none_input(self) -> None:+ assert parse_streaming_json(None) == {}++ def test_empty_string(self) -> None:+ assert parse_streaming_json("") == {}++ def test_whitespace_only(self) -> None:+ assert parse_streaming_json(" ") == {}++ def test_truncated_json(self) -> None:+ result = parse_streaming_json('{"name": "hello", "count": 42')+ assert result == {"name": "hello", "count": 42}++ def test_truncated_string_value(self) -> None:+ result = parse_streaming_json('{"cmd": "echo hel')+ assert result["cmd"] == "echo hel"++ def test_control_chars_in_value(self) -> None:+ raw = '{"msg": "line\x01end"}'+ result = parse_streaming_json(raw)+ assert result["msg"] == "line\x01end"++ def test_invalid_escape_in_value(self) -> None:+ raw = r'{"path": "C:\windows\system32"}'+ result = parse_streaming_json(raw)+ assert "windows" in result["path"]+ assert "system32" in result["path"]++ def test_completely_broken_returns_empty(self) -> None:+ assert parse_streaming_json("not json at all") == {}++ def test_non_dict_returns_empty(self) -> None:+ # parse_streaming_json should only return dicts.+ assert parse_streaming_json("[1, 2, 3]") == {}+ assert parse_streaming_json('"just a string"') == {}+ assert parse_streaming_json("42") == {}++ def test_complex_nested_truncated(self) -> None:+ text = '{"tool": "bash", "args": {"cmd": "ls -la", "opts": {"verbose": true'+ result = parse_streaming_json(text)+ assert result["tool"] == "bash"+ assert result["args"]["cmd"] == "ls -la"+ assert result["args"]["opts"]["verbose"] is True++ def test_truncated_after_key(self) -> None:+ # Truncated right after a colon — partial parse should still work+ # or return {} gracefully.+ result = parse_streaming_json('{"key":')+ # This is acceptable as either {} or a partial result+ assert isinstance(result, dict)++ def test_repair_then_partial(self) -> None:+ # Control char + truncation — needs both repair and partial parse.+ raw = '{"msg": "bad\x02char", "extra": "trunc'+ result = parse_streaming_json(raw)+ assert result["msg"] == "bad\x02char"+ assert result["extra"] == "trunc"++ def test_multiple_tool_calls_pattern(self) -> None:+ # Simulates a typical streaming tool-call argument pattern.+ text = '{"command": "grep -r TODO .", "timeout": 30}'+ result = parse_streaming_json(text)+ assert result["command"] == "grep -r TODO ."+ assert result["timeout"] == 30++ def test_boolean_and_null_values(self) -> None:+ text = '{"flag": true, "other": null, "num": 3.14}'+ result = parse_streaming_json(text)+ assert result["flag"] is True+ assert result["other"] is None+ assert result["num"] == pytest.approx(3.14)++ def test_truncated_boolean(self) -> None:+ # "tru" is not valid JSON — should fallback gracefully.+ result = parse_streaming_json('{"flag": tru')+ assert isinstance(result, dict)++ def test_unicode_content(self) -> None:+ text = '{"text": "Hello \\u4e16\\u754c"}'+ result = parse_streaming_json(text)+ assert result["text"] == "Hello 世界"