import json import re def console_safe(text: str) -> str: """Sanitize LLM-generated text for legacy Windows console rendering. Rich's legacy Windows renderer writes through the active console codepage (often cp1252, not UTF-8), which raises an unhandled UnicodeEncodeError on characters like curly quotes, em/en-dashes, or the non-breaking hyphen (U+2011) that LLM-generated task titles/descriptions routinely contain. Replacing unencodable characters here keeps the display readable instead of crashing the whole process after all real work is already done. """ return text.encode("ascii", "replace").decode("ascii") def extract_json(text: str) -> dict: trimmed = text.strip() fence_pattern = r"```(?:json)?\s*\n?(.*?)\n?```" match = re.search(fence_pattern, trimmed, re.DOTALL) if match: trimmed = match.group(1).strip() if trimmed.startswith("{") or trimmed.startswith("["): pass else: first_brace = trimmed.find("{") first_bracket = trimmed.find("[") candidates = [] if first_brace != -1: candidates.append(first_brace) if first_bracket != -1: candidates.append(first_bracket) if candidates: start = min(candidates) else: start = 0 trimmed = trimmed[start:] last_brace = trimmed.rfind("}") last_bracket = trimmed.rfind("]") if last_brace != -1: trimmed = trimmed[: last_brace + 1] elif last_bracket != -1: trimmed = trimmed[: last_bracket + 1] try: return json.loads(trimmed) except json.JSONDecodeError: pass trimmed = _strip_trailing_commas(trimmed) try: return json.loads(trimmed) except json.JSONDecodeError: pass cleaned = _fix_unescaped_chars(trimmed) try: return json.loads(cleaned) except json.JSONDecodeError as e: raise json.JSONDecodeError( f"{e.msg}\nFirst 500 chars of response: {text[:500]}", e.doc, e.pos, ) from None def _strip_trailing_commas(text: str) -> str: text = re.sub(r",\s*([}\]])", r"\1", text) return text def _fix_unescaped_chars(text: str) -> str: text = text.replace("\t", "\\t") def _escape_newlines_in_strings(m): content = m.group(1) content = content.replace("\n", "\\n") return f'"{content}"' text = re.sub(r'"([^"]*?\n[^"]*?)"', _escape_newlines_in_strings, text) return text