protocol.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. """Minimal LSP JSON-RPC 2.0 framer over async streams.
  2. Wire format: ``Content-Length: <bytes>\\r\\n\\r\\n<utf-8 JSON body>`` where the
  3. body is a JSON-RPC 2.0 request, response, or notification. Just the framer
  4. plus envelope helpers, so :class:`agent.lsp.client.LSPClient` can focus on
  5. protocol semantics.
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import json
  10. import logging
  11. from typing import Any, Optional, Tuple
  12. logger = logging.getLogger("agent.lsp.protocol")
  13. # LSP error codes we care about (spec 3.17 #errorCodes).
  14. ERROR_CONTENT_MODIFIED = -32801
  15. ERROR_METHOD_NOT_FOUND = -32601
  16. _MAX_HEADER_BYTES = 8192 # a well-behaved server fits in well under 200 bytes
  17. _MAX_BODY_BYTES = 64 * 1024 * 1024
  18. class LSPProtocolError(Exception):
  19. """The framing or envelope itself is broken (vs. :class:`LSPRequestError`, a conformant error response)."""
  20. class LSPRequestError(Exception):
  21. """An LSP request returned a JSON-RPC error response; carries ``code``, ``message``, ``data``."""
  22. def __init__(self, code: int, message: str, data: Any = None) -> None:
  23. super().__init__(f"LSP error {code}: {message}")
  24. self.code, self.message, self.data = code, message, data
  25. def encode_message(obj: dict) -> bytes:
  26. """Encode an envelope as compact UTF-8 JSON with an exact Content-Length header."""
  27. body = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
  28. return f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + body
  29. async def _read_headers(reader: asyncio.StreamReader) -> Optional[dict]:
  30. """Read the header block; ``None`` on clean EOF before any header started."""
  31. headers: dict = {}
  32. header_bytes = 0
  33. while True:
  34. try:
  35. line = await reader.readuntil(b"\r\n")
  36. except asyncio.IncompleteReadError as e:
  37. # EOF before any header started is a clean close; mid-block is bad framing.
  38. if not e.partial and not headers:
  39. return None
  40. raise LSPProtocolError(f"unexpected EOF while reading LSP headers (partial={e.partial!r})") from e
  41. # Cap against a server streaming headers without ever emitting CRLF-CRLF.
  42. header_bytes += len(line)
  43. if header_bytes > _MAX_HEADER_BYTES:
  44. raise LSPProtocolError("LSP header block exceeded 8 KiB without terminator")
  45. line = line[:-2] # strip CRLF
  46. if not line:
  47. return headers # blank line ends header block
  48. try:
  49. key, _, value = line.decode("ascii").partition(":")
  50. except UnicodeDecodeError as e:
  51. raise LSPProtocolError(f"non-ASCII LSP header: {line!r}") from e
  52. if not key:
  53. raise LSPProtocolError(f"malformed LSP header line: {line!r}")
  54. headers[key.strip().lower()] = value.strip()
  55. async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
  56. """Read one framed message.
  57. ``None`` on clean EOF between messages (typical shutdown); :class:`LSPProtocolError` on malformed framing.
  58. """
  59. headers = await _read_headers(reader)
  60. if headers is None:
  61. return None
  62. cl = headers.get("content-length")
  63. if cl is None:
  64. raise LSPProtocolError(f"LSP message missing Content-Length: {headers!r}")
  65. try:
  66. n = int(cl)
  67. except ValueError as e:
  68. raise LSPProtocolError(f"non-integer Content-Length: {cl!r}") from e
  69. if n < 0 or n > _MAX_BODY_BYTES:
  70. raise LSPProtocolError(f"unreasonable Content-Length: {n}")
  71. try:
  72. body = await reader.readexactly(n)
  73. except asyncio.IncompleteReadError as e:
  74. raise LSPProtocolError(f"truncated LSP body: expected {n} bytes, got {len(e.partial)}") from e
  75. try:
  76. return json.loads(body.decode("utf-8"))
  77. except json.JSONDecodeError as e:
  78. raise LSPProtocolError(f"invalid JSON in LSP body: {e}") from e
  79. except UnicodeDecodeError as e:
  80. raise LSPProtocolError(f"non-UTF-8 LSP body: {e}") from e
  81. def make_notification(method: str, params: Any) -> dict:
  82. """Build a JSON-RPC 2.0 notification envelope (no ``id``)."""
  83. return {"jsonrpc": "2.0", "method": method, **({} if params is None else {"params": params})}
  84. def make_request(req_id: int, method: str, params: Any) -> dict:
  85. """Build a JSON-RPC 2.0 request envelope."""
  86. return {"jsonrpc": "2.0", "id": req_id, "method": method, **({} if params is None else {"params": params})}
  87. def make_response(req_id: Any, result: Any) -> dict:
  88. """Build a JSON-RPC 2.0 success response envelope."""
  89. return {"jsonrpc": "2.0", "id": req_id, "result": result}
  90. def make_error_response(req_id: Any, code: int, message: str, data: Any = None) -> dict:
  91. """Build a JSON-RPC 2.0 error response envelope."""
  92. err = {"code": code, "message": message, **({} if data is None else {"data": data})}
  93. return {"jsonrpc": "2.0", "id": req_id, "error": err}
  94. def classify_message(msg: dict) -> tuple[str, Any]:
  95. """Return ``(kind, key)``: kind ∈ request/response/notification/invalid; key is the id (request/response),
  96. the method (notification) or ``None`` (invalid)."""
  97. if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
  98. return "invalid", None
  99. if "id" in msg:
  100. if "method" in msg:
  101. return "request", msg["id"]
  102. return ("response", msg["id"]) if ("result" in msg or "error" in msg) else ("invalid", None)
  103. return ("notification", msg["method"]) if "method" in msg else ("invalid", None)
  104. __all__ = [
  105. "ERROR_CONTENT_MODIFIED",
  106. "ERROR_METHOD_NOT_FOUND",
  107. "LSPProtocolError",
  108. "LSPRequestError",
  109. "classify_message",
  110. "encode_message",
  111. "make_error_response",
  112. "make_notification",
  113. "make_request",
  114. "make_response",
  115. "read_message",
  116. ]