"""Shared JSON helpers (fenced markdown, brace extraction).""" from __future__ import annotations import re _MARKDOWN_JSON_FENCE_RE = re.compile( r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.IGNORECASE | re.DOTALL, ) def extract_json_payload(raw_response: str | None) -> str: """Strip optional ```json fences and return the outermost `{...}` object substring.""" cleaned = (raw_response or "").strip() fenced_match = _MARKDOWN_JSON_FENCE_RE.match(cleaned) if fenced_match: cleaned = fenced_match.group(1).strip() if cleaned.startswith("{") and cleaned.endswith("}"): return cleaned start = cleaned.find("{") if start == -1: return cleaned depth = 0 for i, ch in enumerate(cleaned[start:], start): if ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: return cleaned[start : i + 1].strip() return cleaned