events.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """Callback factories for bridging AIAgent events to ACP notifications.
  2. Each factory returns a callable with the signature AIAgent expects for its
  3. callbacks. AIAgent runs in a worker thread while the event loop lives on the
  4. main thread, so updates are pushed via ``conn.session_update()`` scheduled
  5. thread-safely onto the loop.
  6. """
  7. import asyncio
  8. import logging
  9. import uuid
  10. from collections import deque
  11. from typing import Any, Callable, Deque, Dict
  12. import acp
  13. from acp.schema import AgentPlanUpdate, PlanEntry
  14. from .tools import (
  15. _json_loads_maybe, build_tool_abandoned, build_tool_complete, build_tool_start, coerce_tool_args,
  16. make_tool_call_id,
  17. )
  18. logger = logging.getLogger(__name__)
  19. # ACP plans only support pending/in_progress/completed. Cancelled tasks are kept
  20. # as terminal entries so the client's full-list replacement doesn't drop them.
  21. _PLAN_STATUS = {"pending": "pending", "in_progress": "in_progress", "completed": "completed", "cancelled": "completed"}
  22. def _build_plan_update_from_todo_result(result: Any) -> AgentPlanUpdate | None:
  23. """Translate Hermes' todo tool result into ACP's native plan update.
  24. Zed renders ``sessionUpdate: plan`` as its first-class task panel, so the
  25. todo state is exposed natively rather than only as a tool-call transcript."""
  26. if not isinstance(result, str) or not result.strip():
  27. return None
  28. data = _json_loads_maybe(result)
  29. if not isinstance(data, dict) or not isinstance(data.get("todos"), list):
  30. return None
  31. entries: list[PlanEntry] = []
  32. for item in data["todos"]:
  33. if not isinstance(item, dict):
  34. continue
  35. content = str(item.get("content") or item.get("id") or "").strip()
  36. if not content:
  37. continue
  38. raw_status = str(item.get("status") or "pending").strip()
  39. if raw_status == "cancelled":
  40. content = f"[cancelled] {content}"
  41. entries.append(PlanEntry(content=content, priority="medium", status=_PLAN_STATUS.get(raw_status, "pending")))
  42. return AgentPlanUpdate(session_update="plan", entries=entries)
  43. def _send_update(conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, update: Any) -> None:
  44. """Fire-and-forget an ACP session update from a worker thread."""
  45. from agent.async_utils import safe_schedule_threadsafe
  46. future = safe_schedule_threadsafe(
  47. conn.session_update(session_id, update), loop, logger=logger, log_message="Failed to send ACP update",
  48. )
  49. if future is None:
  50. return
  51. try:
  52. future.result(timeout=5)
  53. except Exception:
  54. logger.debug("Failed to send ACP update", exc_info=True)
  55. def _upgrade_queue(tool_call_ids: dict[str, deque[str]], name: str) -> deque[str] | None:
  56. """Fetch the per-tool FIFO of pending call IDs, upgrading a legacy bare-string entry in place."""
  57. queue = tool_call_ids.get(name)
  58. if isinstance(queue, str):
  59. queue = tool_call_ids[name] = deque([queue])
  60. return queue
  61. def close_tool_call(
  62. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: dict[str, deque[str]],
  63. tool_call_meta: dict[str, dict[str, Any]], name: str, result: Any = None, is_error: bool = False,
  64. ) -> str | None:
  65. """Close the oldest open ACP tool call for ``name``; returns its id, or None when none is open."""
  66. queue = _upgrade_queue(tool_call_ids, name)
  67. if not queue:
  68. return None
  69. tc_id = queue.popleft()
  70. meta = tool_call_meta.pop(tc_id, {})
  71. _send_update(conn, session_id, loop, build_tool_complete(
  72. tc_id, name, result=str(result) if result is not None else None,
  73. function_args=meta.get("args"), snapshot=meta.get("snapshot"), is_error=is_error,
  74. ))
  75. if not queue:
  76. tool_call_ids.pop(name, None)
  77. return tc_id
  78. def flush_open_tool_calls(
  79. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: dict[str, deque[str]],
  80. tool_call_meta: dict[str, dict[str, Any]],
  81. ) -> int:
  82. """Close every tool call still open at the end of a turn, and report how many there were.
  83. A tool blocked by scope, guardrail or an editor permission prompt never
  84. projects ``tool.completed``, so without this its bubble stays ``in_progress``
  85. forever and clients read the turn as one that never ran a tool."""
  86. open_calls = [(name, list(queue)) for name, queue in list(tool_call_ids.items()) if queue]
  87. flushed = 0
  88. for name, ids in open_calls:
  89. for tc_id in ids:
  90. tool_call_meta.pop(tc_id, None)
  91. _send_update(conn, session_id, loop, build_tool_abandoned(tc_id, name))
  92. flushed += 1
  93. tool_call_ids.pop(name, None)
  94. if flushed:
  95. logger.debug("Flushed %d ACP tool call(s) left open at turn end", flushed)
  96. return flushed
  97. def make_tool_progress_cb(
  98. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: dict[str, deque[str]],
  99. tool_call_meta: dict[str, dict[str, Any]],
  100. edit_approval_policy_getter: Callable[[], tuple[str, str | None]] | None = None,
  101. turn_state: dict[str, Any] | None = None,
  102. ) -> Callable:
  103. """Create a ``tool_progress_callback`` for AIAgent.
  104. Signature: ``tool_progress_callback(event_type, name, preview, args, **kwargs)``.
  105. Emits ``ToolCallStart`` for ``tool.started`` and tracks IDs in a FIFO per tool
  106. name so parallel same-name calls complete against the right ACP tool call.
  107. ``tool.completed`` closes that call with its own result — the step callback
  108. only fires on the *next* step, which leaves a turn's last tools open."""
  109. def _tool_progress(event_type: str, name: str | None = None, preview: str | None = None, args: Any = None, **kwargs) -> None:
  110. if event_type == "tool.completed" and name:
  111. if turn_state is not None:
  112. turn_state["saw_completion"] = True
  113. # The executor's verdict: a cancelled/errored tool may return plain text the heuristic misses.
  114. close_tool_call(
  115. conn, session_id, loop, tool_call_ids, tool_call_meta, name, kwargs.get("result"),
  116. is_error=bool(kwargs.get("is_error")),
  117. )
  118. return
  119. if event_type != "tool.started":
  120. return
  121. args = coerce_tool_args(args)
  122. tc_id = make_tool_call_id()
  123. queue = _upgrade_queue(tool_call_ids, name)
  124. if queue is None:
  125. queue = tool_call_ids[name] = deque()
  126. queue.append(tc_id)
  127. snapshot = None
  128. if name in {"write_file", "patch", "skill_manage"}:
  129. try:
  130. from agent.display import capture_local_edit_snapshot
  131. snapshot = capture_local_edit_snapshot(name, args)
  132. except Exception:
  133. logger.debug("Failed to capture ACP edit snapshot for %s", name, exc_info=True)
  134. tool_call_meta[tc_id] = {"args": args, "snapshot": snapshot}
  135. edit_diff = None
  136. if name in {"write_file", "patch"} and edit_approval_policy_getter is not None:
  137. try:
  138. from acp_adapter.edit_approval import build_edit_proposal, should_auto_approve_edit
  139. proposal = build_edit_proposal(name, args)
  140. if proposal is not None:
  141. policy, cwd = edit_approval_policy_getter()
  142. if should_auto_approve_edit(proposal, policy, cwd):
  143. edit_diff = proposal
  144. except Exception:
  145. logger.debug("Failed to prepare auto-approved ACP edit diff for %s", name, exc_info=True)
  146. _send_update(conn, session_id, loop, build_tool_start(tc_id, name, args, edit_diff=edit_diff))
  147. return _tool_progress
  148. # ------------------------------------------------------------------
  149. # Assistant message identity
  150. # ------------------------------------------------------------------
  151. class AssistantMessageIdAllocator:
  152. """Allocates stable per-message ids for streamed assistant chunks.
  153. ACP clients group streamed ``agent_message_chunk`` / ``agent_thought_chunk``
  154. deltas into one assistant reply by ``messageId`` and use a NEW id to start
  155. the next reply (root-reply replacement semantics). Without ids, a client
  156. that replaces "the current assistant message" on each chunk collapses
  157. separate autonomous turns into one bubble.
  158. One allocator lives per ACP session; a contiguous run of deltas shares
  159. ``current()`` and ``close()`` marks the message finished so the next delta
  160. allocates a fresh id. Ids are UUID4 strings because the ACP schema requires
  161. UUID-format message ids, and a fresh UUID can never collide with an earlier
  162. turn's id.
  163. """
  164. def __init__(self) -> None:
  165. self._active: str | None = None
  166. self._last: str | None = None
  167. def current(self) -> str:
  168. """Return the active message id, allocating one if none is open."""
  169. if self._active is None:
  170. self._active = self._last = str(uuid.uuid4())
  171. return self._active
  172. def last(self) -> str | None:
  173. """Return the most recently allocated id (open or closed)."""
  174. return self._last
  175. def close(self) -> None:
  176. """End the active message; the next chunk starts a new id."""
  177. self._active = None
  178. def _make_text_cb(
  179. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, wrap: Callable[[str], Any],
  180. message_ids: AssistantMessageIdAllocator | None = None,
  181. ) -> Callable:
  182. # ``None`` is the flush sentinel Hermes core sends between assistant messages
  183. # (before tool execution / at end of stream): it closes the active messageId so
  184. # the next delta opens a new bubble instead of merging into the previous one.
  185. def _cb(text: str | None) -> None:
  186. if text:
  187. update = wrap(text)
  188. if message_ids is not None:
  189. update.message_id = message_ids.current()
  190. _send_update(conn, session_id, loop, update)
  191. elif text is None and message_ids is not None:
  192. message_ids.close()
  193. return _cb
  194. def make_thinking_cb(
  195. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop,
  196. message_ids: AssistantMessageIdAllocator | None = None,
  197. ) -> Callable:
  198. """Create a ``thinking_callback`` for AIAgent."""
  199. return _make_text_cb(conn, session_id, loop, acp.update_agent_thought_text, message_ids)
  200. def make_message_cb(
  201. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop,
  202. message_ids: AssistantMessageIdAllocator | None = None,
  203. ) -> Callable:
  204. """Create a callback that streams agent response text to the editor."""
  205. return _make_text_cb(conn, session_id, loop, acp.update_agent_message_text, message_ids)
  206. def make_step_cb(
  207. conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: dict[str, deque[str]],
  208. tool_call_meta: dict[str, dict[str, Any]], turn_state: dict[str, Any] | None = None,
  209. ) -> Callable:
  210. """Create a ``step_callback(api_call_count: int, prev_tools: list)`` for AIAgent."""
  211. def _step(api_call_count: int, prev_tools: Any = None) -> None:
  212. if not isinstance(prev_tools, list):
  213. return
  214. for tool_info in prev_tools:
  215. tool_name = result = function_args = None
  216. if isinstance(tool_info, dict):
  217. tool_name = tool_info.get("name") or tool_info.get("function_name")
  218. # Key presence, not truthiness: "", 0 and False are real results (#10845).
  219. result = tool_info.get("result") if "result" in tool_info else tool_info.get("output")
  220. function_args = tool_info.get("arguments") or tool_info.get("args")
  221. elif isinstance(tool_info, str):
  222. tool_name = tool_info
  223. if not tool_name:
  224. continue
  225. # ``tool.completed`` already closed this call with its own result;
  226. # this callback is the fallback for runtimes that never project one.
  227. if not (turn_state or {}).get("saw_completion"):
  228. queue = _upgrade_queue(tool_call_ids, tool_name)
  229. if not queue:
  230. continue
  231. tc_id = queue.popleft()
  232. meta = tool_call_meta.pop(tc_id, {})
  233. # ``prev_tools`` carries the wire ``arguments`` JSON *string*; the content
  234. # builders index it as a dict, so an uncoerced string raised inside this
  235. # (swallowed) callback and the bubble never closed.
  236. _send_update(conn, session_id, loop, build_tool_complete(
  237. tc_id, tool_name, result=str(result) if result is not None else None,
  238. function_args=coerce_tool_args(function_args) if function_args else meta.get("args"),
  239. snapshot=meta.get("snapshot"),
  240. ))
  241. if not queue:
  242. tool_call_ids.pop(tool_name, None)
  243. if tool_name == "todo" and (plan_update := _build_plan_update_from_todo_result(result)) is not None:
  244. _send_update(conn, session_id, loop, plan_update)
  245. return _step