Tolerate malformed stringified writer rewrites

This commit is contained in:
Your Name
2026-08-03 23:14:24 +05:00
parent 6426148a57
commit ad66f2ed73
+34
View File
@@ -107,10 +107,44 @@ def decode_jsonish(value: Any) -> Any:
try:
value = json.loads(raw)
except json.JSONDecodeError:
salvaged = loads_json_prefix(raw)
if salvaged is not None:
value = salvaged
continue
return value
return value
def loads_json_prefix(raw: str) -> Any | None:
if not raw or raw[0] not in "[{":
return None
pairs = {"[": "]", "{": "}"}
stack: list[str] = []
in_string = False
escaped = False
for idx, char in enumerate(raw):
if in_string:
if escaped:
escaped = False
elif char == "\\":
escaped = True
elif char == '"':
in_string = False
continue
if char == '"':
in_string = True
elif char in pairs:
stack.append(pairs[char])
elif stack and char == stack[-1]:
stack.pop()
if not stack:
try:
return json.loads(raw[: idx + 1])
except json.JSONDecodeError:
return None
return None
def response_usage(response: Any) -> dict[str, Any]:
usage = getattr(response, "usage", None)
if usage is None and isinstance(response, dict):