reporter.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """Format LSP diagnostics for inclusion in tool output.
  2. The model sees a compact, severity-filtered, line-bounded ``<diagnostics>``
  3. block (1-indexed line/column, capped at ``MAX_PER_FILE``) for diagnostics
  4. introduced by the latest edit.
  5. """
  6. from __future__ import annotations
  7. import html
  8. from typing import Any, Dict, List
  9. from agent.compression_marker import elide
  10. # ERROR only by default — warnings/info/hints would flood the agent.
  11. SEVERITY_NAMES = {1: "ERROR", 2: "WARN", 3: "INFO", 4: "HINT"}
  12. DEFAULT_SEVERITIES = frozenset({1})
  13. MAX_PER_FILE = 20
  14. MAX_TOTAL_CHARS = 4000
  15. # Per-field caps bound any single attacker-controlled identifier that can
  16. # ride into the model's tool output via an LSP diagnostic message.
  17. MAX_MESSAGE_CHARS = 300
  18. MAX_CODE_CHARS = 80
  19. MAX_SOURCE_CHARS = 80
  20. def _sanitize_field(value: Any, *, limit: int) -> str:
  21. """Make a language-server field safe to embed in a tool-result block.
  22. ``message``/``code``/``source`` come from a server that just parsed user-controlled code, so a
  23. hostile repo can smuggle instruction-shaped text through identifier names. We collapse CR/LF,
  24. drop control chars, cap the length, and HTML-escape ``< > &`` so the text can't close
  25. ``<diagnostics>`` early. ``None``/empty → ``""`` so callers can omit the part.
  26. """
  27. if value is None:
  28. return ""
  29. raw = str(value).replace("\r", " ").replace("\n", " ")
  30. raw = "".join(ch for ch in raw if ch == " " or ch.isprintable())
  31. return html.escape(raw.strip()[:limit], quote=False)
  32. def format_diagnostic(d: dict[str, Any]) -> str:
  33. """One-line representation of a single diagnostic (fields sanitized)."""
  34. sev = SEVERITY_NAMES.get(d.get("severity") or 1, "ERROR")
  35. start = (d.get("range") or {}).get("start") or {}
  36. line = int(start.get("line", 0)) + 1
  37. col = int(start.get("character", 0)) + 1
  38. msg = _sanitize_field(d.get("message"), limit=MAX_MESSAGE_CHARS)
  39. code = _sanitize_field(d.get("code"), limit=MAX_CODE_CHARS)
  40. source = _sanitize_field(d.get("source"), limit=MAX_SOURCE_CHARS)
  41. return f"{sev} [{line}:{col}] {msg}{f' [{code}]' if code else ''}{f' ({source})' if source else ''}"
  42. def report_for_file(
  43. file_path: str,
  44. diagnostics: list[dict[str, Any]],
  45. *,
  46. severities: frozenset = DEFAULT_SEVERITIES,
  47. max_per_file: int = MAX_PER_FILE,
  48. ) -> str:
  49. """Build a ``<diagnostics file=...>`` block; ``""`` when nothing passes the severity filter."""
  50. filtered = [d for d in diagnostics or [] if (d.get("severity") or 1) in severities]
  51. if not filtered:
  52. return ""
  53. body = "\n".join(format_diagnostic(d) for d in filtered[:max_per_file])
  54. if len(filtered) > max_per_file:
  55. body += f"\n... and {len(filtered) - max_per_file} more"
  56. # quote=True also escapes ``"`` so a crafted file name can't break out of
  57. # the ``file="..."`` attribute and synthesize new tags.
  58. safe_path = html.escape(file_path, quote=True)
  59. return f"<diagnostics file=\"{safe_path}\">\n{body}\n</diagnostics>"
  60. def truncate(s: str, *, limit: int = MAX_TOTAL_CHARS) -> str:
  61. """Hard-cap a formatted summary string with the non-imitable elision marker."""
  62. return elide(s, limit)
  63. __all__ = ["DEFAULT_SEVERITIES", "MAX_PER_FILE", "SEVERITY_NAMES", "format_diagnostic", "report_for_file", "truncate"]