gateway_reply.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """How a gateway turn's reply reaches the editor: ``messageId`` grouping, exactly-once final text, tool and
  2. permission bubbles closed as the in-process agent closed them. Mixed into ``GatewayACPAgent``, whose state
  3. (``_conn``, ``_streamed``, ``_segments``, ``_tool_args``, ``_message_ids``, ``_cut``) it reads and updates."""
  4. from __future__ import annotations
  5. import logging
  6. import acp
  7. logger = logging.getLogger(__name__)
  8. def _text(payload):
  9. """Reply text of a message frame; ``text`` may be present and null (a suppressed delivery)."""
  10. text = payload.get("text")
  11. return text if isinstance(text, str) else ""
  12. class GatewayReplyMixin:
  13. async def _project_tool(self, kind, sid, editor_id, aid, payload):
  14. """``tool.start`` / ``tool.complete`` as the in-process callbacks projected them (#134889 ACP-15)."""
  15. from acp_adapter.tools import build_tool_complete, build_tool_start, coerce_tool_args
  16. # In-process turns publish ``tool_name``; managed workers publish ``name``.
  17. tool_name = payload.get("tool_name") or payload.get("name") or "tool"
  18. call_id = payload["tool_call_id"]
  19. if kind == "tool.start":
  20. # Deltas before a tool call are commentary the final reply does not repeat: close
  21. # that segment so ``message.complete`` measures only the final's own stream, and end
  22. # that assistant message so the text after the tool opens a new one (a new ``messageId``).
  23. self._close_segment(aid)
  24. self._end_message(sid)
  25. args = coerce_tool_args(payload.get("args"))
  26. self._tool_args[(sid, call_id)] = (tool_name, args, aid)
  27. if self._conn:
  28. await self._conn.session_update(session_id=editor_id, update=build_tool_start(call_id, tool_name, args))
  29. return
  30. name, args, _ = self._tool_args.pop((sid, call_id), (tool_name, {}, aid))
  31. result = payload.get("result")
  32. if self._conn:
  33. # ``is_error`` is the executor's verdict: a cancelled or failed tool may return plain text the
  34. # result heuristic reads as success.
  35. await self._conn.session_update(session_id=editor_id, update=build_tool_complete(
  36. call_id, name, result=result if isinstance(result, str) else None, function_args=args,
  37. is_error=payload.get("is_error") is True))
  38. async def _finish_reply(self, sid, editor_id, aid, payload):
  39. """Show the settled reply's unseen remainder, then end the turn: its reply's id closes, and a tool
  40. call it left open (blocked by a guard, an approval denied) ends ``failed``, as the in-process agent
  41. flushed them at turn end. Shared by ``message.complete`` and a retry's terminal receipt."""
  42. remainder = self._final_remainder(aid, payload)
  43. if remainder and self._conn:
  44. await self._conn.session_update(session_id=editor_id, update=self._chunk(sid, remainder))
  45. self._end_message(sid)
  46. await self._flush_open_tools(sid, editor_id, aid)
  47. async def _flush_open_tools(self, sid, editor_id, aid):
  48. """Close every call admission *aid* started and never completed (``failed``: it produced no result)."""
  49. from acp_adapter.tools import build_tool_abandoned
  50. for key in [key for key, held in self._tool_args.items() if key[0] == sid and held[2] == aid]:
  51. name, _, _ = self._tool_args.pop(key)
  52. if self._conn:
  53. await self._conn.session_update(session_id=editor_id, update=build_tool_abandoned(key[1], name))
  54. def _chunk(self, sid, text, *, thought=False):
  55. """An assistant (or thought) chunk carrying the session's current ``messageId``: ACP clients group
  56. chunks into one reply by it and start a new bubble when it changes."""
  57. from acp_adapter.events import AssistantMessageIdAllocator
  58. update = (acp.update_agent_thought_text if thought else acp.update_agent_message_text)(text)
  59. update.message_id = self._message_ids.setdefault(sid, AssistantMessageIdAllocator()).current()
  60. return update
  61. def _end_message(self, sid):
  62. if (ids := self._message_ids.get(sid)) is not None:
  63. ids.close()
  64. async def _project_side_update(self, kind, sid, editor_id, payload):
  65. """Turn events outside the reply text, as the in-process server projected them.
  66. ``reasoning.delta``: the model's reasoning as thought chunks. It never enters the reply's segments,
  67. so ``message.complete``'s final remainder is unchanged.
  68. ``todo.updated``: the owner's full todo snapshot (published for a LOCAL session's turn, which an ACP
  69. session is) as the native ``plan`` update Zed renders as its task panel (#134889 ACP-5)."""
  70. if kind == "reasoning.delta":
  71. text = _text(payload)
  72. update = self._chunk(sid, text, thought=True) if text else None
  73. else:
  74. import json
  75. from acp_adapter.events import _build_plan_update_from_todo_result
  76. todos = payload.get("todos")
  77. update = _build_plan_update_from_todo_result(json.dumps({"todos": todos})) \
  78. if isinstance(todos, list) else None
  79. if update is not None and self._conn:
  80. await self._conn.session_update(session_id=editor_id, update=update)
  81. def _close_segment(self, aid):
  82. streamed = self._streamed.pop(aid, "")
  83. if streamed.strip():
  84. self._segments.setdefault(aid, []).append(streamed)
  85. def _final_remainder(self, aid, payload):
  86. """The part of the settled reply the editor has not been shown yet (exactly-once text)."""
  87. from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX
  88. text = _text(payload)
  89. streamed = self._streamed.pop(aid, "")
  90. shown = self._segments.pop(aid, [])
  91. cut = self._cut.pop(aid, None)
  92. # Local interrupt status is metadata; ACP carries it in stop_reason.
  93. if not text or (payload.get("outcome") == "cancelled"
  94. and text.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)):
  95. return ""
  96. segments = {s.strip() for s in shown}
  97. if payload.get("response_reused") is True and (
  98. text.strip() in segments | {streamed.strip()} if cut is not None or payload.get("receipt")
  99. else (streamed or shown)):
  100. # The owner names the final as a reply already painted (never inferred from text); after a
  101. # replay gap or from a receipt, only when this editor showed all of it.
  102. return ""
  103. if cut is not None: # a replay gap stopped its live text: the rest once, or marked in full
  104. from hermes_cli.gateway_replay_gap import owed_reply
  105. # An interim after the gap closed the cut segment and may already have shown the whole reply.
  106. return "" if not cut and text.strip() in segments else owed_reply(cut, text)
  107. if text.startswith(streamed):
  108. remainder = text[len(streamed):]
  109. # An unstreamed final the owner already published as an interim segment.
  110. return "" if not streamed and text.strip() in {s.strip() for s in shown} else remainder
  111. if text.strip() == streamed.strip():
  112. return ""
  113. return "\n\n" + text
  114. async def _close_card(self, editor_id, tool_call, options, response):
  115. """The editor shows a permission request's ``tool_call`` as a pending bubble; once it is answered,
  116. close it as the in-process agent did (``permissions.await_permission``): ``completed`` for an allow,
  117. ``failed`` for a reject or a dismissal (#134889 ACP-15)."""
  118. outcome = getattr(response, "outcome", None)
  119. allowed = getattr(outcome, "outcome", None) == "selected" and any(
  120. option.option_id == getattr(outcome, "option_id", None) and option.kind.startswith("allow")
  121. for option in options)
  122. try:
  123. await self._conn.session_update(session_id=editor_id, update=acp.update_tool_call(
  124. tool_call.tool_call_id, status="completed" if allowed else "failed"))
  125. except Exception:
  126. # Boundary: display only; a failed close must never cost the user's answer its delivery.
  127. logger.debug("ACP permission card %s not closed", tool_call.tool_call_id, exc_info=True)