deferred.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """LSP diagnostics for a write, delivered after the write's tool result instead of inside it.
  2. ``write_file`` / ``patch`` return as soon as the bytes are on disk and verified; the language server
  3. check runs on the LSP loop (``agent.lsp.edit_check``). Its verdict is queued here under the session
  4. that made the edit (bound by ``tools.file_tools`` around the write) and handed to that session's agent
  5. at its next tool result, or its next user turn when no tool runs again
  6. (``agent.plugin_live_notes``: a new row not yet flushed, so no cached byte moves).
  7. A later edit of the same file takes over an undelivered verdict: the newer check diffs against the
  8. older baseline, so an error the first edit introduced is still reported unless the second fixed it.
  9. A verdict must not be lost when the edit was the turn's last tool call (a one-shot ``-q`` run has no
  10. next turn): checks still running are tracked per session (:func:`track_pending`), and before the turn's
  11. final answer is accepted :func:`settle_for_agent` waits for them (bounded) and returns every verdict
  12. still undelivered, which ``agent.turn_stop_gates`` hands to the model as a new message.
  13. """
  14. from __future__ import annotations
  15. import contextlib
  16. import threading
  17. from collections import OrderedDict
  18. from contextvars import ContextVar
  19. from dataclasses import dataclass
  20. from typing import Any, Iterator, Optional
  21. _OWNER: ContextVar[Optional[str]] = ContextVar("hermes_lsp_deferred_owner", default=None)
  22. _MAX_OWNERS = 64 # sessions that never drain (a one-shot caller) must not grow this forever
  23. _MAX_PER_OWNER = 32
  24. _LOCK = threading.Lock()
  25. _SETTLED = threading.Condition(_LOCK)
  26. # A turn-end wait longer than this hands the verdict to the next user turn instead.
  27. TURN_END_WAIT = 5.0
  28. @dataclass(frozen=True)
  29. class _Note:
  30. text: str
  31. baseline_text: Optional[str] # pre-edit content the verdict was diffed against
  32. # owner -> {abs path -> note}, oldest owner first
  33. _QUEUED: OrderedDict[str, OrderedDict[str, _Note]] = OrderedDict()
  34. # owner -> tokens of its checks still running (their verdict lands in _QUEUED or nowhere)
  35. _PENDING: dict[str, set[object]] = {}
  36. @contextlib.contextmanager
  37. def bind_owner(owner: Optional[str]) -> Iterator[None]:
  38. """Attribute writes in this block to ``owner`` (the session id, else the task id)."""
  39. token = _OWNER.set(owner or None)
  40. try:
  41. yield
  42. finally:
  43. _OWNER.reset(token)
  44. def current_owner() -> Optional[str]:
  45. return _OWNER.get()
  46. def post(owner: str, path: str, text: str, baseline_text: Optional[str]) -> None:
  47. """Queue ``text`` (a formatted diagnostics block) for ``owner``. A note still queued for ``path``
  48. (an older check finished while a newer one was starting) is kept in front, with its baseline."""
  49. with _LOCK:
  50. notes = _QUEUED.pop(owner, None) or OrderedDict()
  51. older = notes.pop(path, None)
  52. if older is not None and older.text != text:
  53. text, baseline_text = f"{older.text}\n\n{text}", older.baseline_text
  54. notes[path] = _Note(text, baseline_text)
  55. while len(notes) > _MAX_PER_OWNER:
  56. notes.popitem(last=False)
  57. _QUEUED[owner] = notes
  58. while len(_QUEUED) > _MAX_OWNERS:
  59. _QUEUED.popitem(last=False)
  60. def take(owner: Optional[str], path: str) -> Optional[_Note]:
  61. """Withdraw ``owner``'s undelivered note for ``path``: a newer edit of the file supersedes it and
  62. diffs against its ``baseline_text``. The newer check carries it and hands it back to
  63. :func:`restore` only if it ends with no verdict, so the older errors are not lost."""
  64. if not owner:
  65. return None
  66. with _LOCK:
  67. notes = _QUEUED.get(owner)
  68. return notes.pop(path, None) if notes else None
  69. def restore(owner: Optional[str], path: str, notes) -> None:
  70. """Queue ``notes`` (oldest first) withdrawn by :func:`take` again."""
  71. if owner:
  72. for note in notes:
  73. post(owner, path, note.text, note.baseline_text)
  74. def pop_notes(*owners: Optional[str]) -> list[tuple[str, str]]:
  75. """Every queued ``(path, text)`` for ``owners``, oldest first, and clear them."""
  76. out: list[tuple[str, str]] = []
  77. with _LOCK:
  78. for owner in dict.fromkeys(o for o in owners if o):
  79. notes = _QUEUED.pop(owner, None)
  80. if notes:
  81. out.extend((path, note.text) for path, note in notes.items())
  82. return out
  83. def track_pending(owner: str) -> object:
  84. """Record a check of ``owner``'s still running; pass the token to :func:`settled` once its verdict
  85. has been posted (or dropped)."""
  86. token = object()
  87. with _LOCK:
  88. _PENDING.setdefault(owner, set()).add(token)
  89. return token
  90. def settled(owner: str, token: object) -> None:
  91. with _SETTLED:
  92. tokens = _PENDING.get(owner)
  93. if tokens is not None:
  94. tokens.discard(token)
  95. if not tokens:
  96. del _PENDING[owner]
  97. _SETTLED.notify_all()
  98. def _owners(agent: Any) -> tuple[Optional[str], ...]:
  99. owners = (getattr(agent, "session_id", None), getattr(agent, "_current_task_id", None))
  100. return tuple(o if isinstance(o, str) else None for o in owners)
  101. def settle_for_agent(agent: Any, timeout: float = TURN_END_WAIT) -> list[tuple[str, str]]:
  102. """Turn end: wait up to ``timeout`` for ``agent``'s running checks, then pop every undelivered
  103. ``(path, text)`` verdict. Returns at once when nothing is running."""
  104. owners = [o for o in dict.fromkeys(_owners(agent)) if o]
  105. if not owners:
  106. return []
  107. with _SETTLED:
  108. _SETTLED.wait_for(lambda: not any(_PENDING.get(o) for o in owners), timeout=timeout)
  109. return pop_notes(*owners)
  110. def forward_to_agent(agent: Any) -> None:
  111. """Move ``agent``'s finished verdicts onto its live-notes queue, which rides the next tool result
  112. (or the next user turn). Called right before that tool result is built."""
  113. notes = pop_notes(*_owners(agent))
  114. if not notes:
  115. return
  116. from agent.plugin_live_notes import queue_plugin_notice
  117. for path, text in notes:
  118. queue_plugin_notice(agent, f"lsp:{path}", text)
  119. __all__ = ["TURN_END_WAIT", "bind_owner", "current_owner", "forward_to_agent", "pop_notes", "post", "restore",
  120. "settle_for_agent", "settled", "take", "track_pending"]