local_viewer_events.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. """Turn events a local viewer (the classic CLI, TUI, Desktop) reads from the canonical stream.
  2. The classic CLI rendered every agent callback in process: the tool-generating line, the
  3. kawaii thinking text, reasoning, MoA references, hearts, and every status line the agent printed
  4. through ``_print_fn``. On the session authority the agent runs in the gateway, so each of those
  5. callbacks is projected as an execution event (generation-fenced through
  6. ``TurnRunner._publish_execution``) and only for a local viewer's turn: a messaging route never
  7. installs them, so its agent behaves exactly as before.
  8. The cached agent is shared across turns. ``wire`` installs the sinks for one turn and returns the
  9. previous values; ``restore`` puts them back when the turn's ``run_conversation`` returns.
  10. """
  11. from __future__ import annotations
  12. import logging
  13. import time
  14. from gateway import local_desktop_ui
  15. logger = logging.getLogger(__name__)
  16. # Attributes ``wire`` may overwrite on the cached agent for one local-viewer turn.
  17. _TURN_ATTRS = ("tool_gen_callback", "_print_fn", "thinking_callback", "reaction_callback", "reasoning_callback",
  18. *local_desktop_ui.CALLBACK_ATTRS)
  19. # Private key in ``wire``'s return value: the desktop window bridge registration ``restore`` releases.
  20. _DESKTOP_UI_TOKEN = "__desktop_ui_token__"
  21. # MoA facade progress (agent/moa_loop._RELAY_EVENTS) -> the payload tui_gateway/tool_progress emits.
  22. _MOA_KEYS = {"moa.reference": {"moa_index": "index", "moa_count": "count"},
  23. "moa.progress": {"moa_refs_done": "refs_done", "moa_refs_total": "refs_total"},
  24. "moa.phase": {"moa_phase": "phase", "moa_refs_done": "refs_done", "moa_refs_total": "refs_total"},
  25. "moa.aggregating": {}}
  26. def wire(turn, agent) -> dict:
  27. """Install this turn's local-viewer sinks on ``agent``; returns what ``restore`` needs."""
  28. previous = {name: getattr(agent, name, None) for name in _TURN_ATTRS}
  29. publish = turn._publish_execution
  30. agent.tool_gen_callback = lambda name: publish("tool.generating", {"name": str(name or "")})
  31. def print_fn(*args, **kwargs):
  32. publish("agent.print", {"text": str(kwargs.get("sep", " ")).join(str(a) for a in args)})
  33. agent._print_fn = print_fn
  34. # Kawaii spinner text ("" clears it) and hearts; neither changes what the provider is sent.
  35. agent.thinking_callback = lambda text: publish("thinking.delta", {"text": str(text or "")})
  36. agent.reaction_callback = lambda kind: publish("reaction", {"kind": str(kind or "")})
  37. owner = getattr(turn, "_approval_owner", None)
  38. if owner is not None:
  39. from gateway.session_usage import seed_compression_count
  40. seed_compression_count(owner[0].sessions.get(owner[1]), agent)
  41. if show_reasoning(turn) or _config_default_launch():
  42. # A reasoning sink makes the agent ask the provider for reasoning; each delta re-checks the
  43. # session's display so /reasoning show|hide applies mid-turn.
  44. agent.reasoning_callback = lambda text: (
  45. publish("reasoning.delta", {"text": str(text or "")}) if show_reasoning(turn) else None)
  46. # The desktop window bridges (preview/terminal/window reads, preview actions, desktop_ui events).
  47. previous[_DESKTOP_UI_TOKEN] = local_desktop_ui.wire(turn, agent)
  48. return previous
  49. # Launch sources whose viewer never sets the session flag; main's TUI gateway defaulted it from config.
  50. _CONFIG_DEFAULT_SOURCES = frozenset({"tui", "gui"})
  51. def show_reasoning(turn) -> bool:
  52. """The session's ``show_reasoning`` display flag (``config.set``, ``/reasoning show|hide``); unset on an
  53. Ink or Desktop launch, its ``display.show_reasoning`` (default on), as main's TUI gateway resolved it."""
  54. owner = getattr(turn, "_approval_owner", None)
  55. live = owner[0].sessions.get(owner[1]) if owner is not None else None
  56. flag = getattr(live, "show_reasoning", None)
  57. if flag is not None or live is None:
  58. return flag is True
  59. from gateway.session_policy import active_policy
  60. return launch_shows_reasoning(active_policy(), owner[0])
  61. def _config_default_launch() -> bool:
  62. from gateway.session_policy import active_policy
  63. return getattr(active_policy(), "source", None) in _CONFIG_DEFAULT_SOURCES
  64. def launch_shows_reasoning(policy, authority) -> bool:
  65. """An unset session flag: ``display.show_reasoning`` for an Ink or Desktop launch, else off."""
  66. if getattr(policy, "source", None) not in _CONFIG_DEFAULT_SOURCES:
  67. return False
  68. from gateway.display_config import local_display_config
  69. display = local_display_config(policy.config(authority, secrets=False).get("display"))
  70. return bool(display.get("show_reasoning", True))
  71. def _is_active_session_subagent(turn, payload: dict, event_type: str = "") -> bool:
  72. subagent_id = payload.get("subagent_id")
  73. if not isinstance(subagent_id, str) or not subagent_id:
  74. return False
  75. import sys
  76. registry = sys.modules.get("tools.delegate_tool_registry")
  77. holder = getattr(getattr(turn, "_ctx", None), "agent_holder", None)
  78. turn_agent = holder[0] if isinstance(holder, list) and holder else None
  79. if registry is None or turn_agent is None:
  80. return False
  81. parent_id = payload.get("parent_id")
  82. with registry._active_subagents_lock:
  83. record = registry._active_subagents.get(subagent_id)
  84. if record is None and event_type == "subagent.spawn_requested" and isinstance(parent_id, str):
  85. # A queued grandchild is announced before it registers; its spawning parent must be a registered descendant.
  86. record = registry._active_subagents.get(parent_id)
  87. return record is not None and registry._is_descendant_of(record.get("agent"), turn_agent)
  88. def _publish_subagent(turn, event_type, payload) -> None:
  89. owner = getattr(turn, "_approval_owner", None)
  90. executing = getattr(owner[0], "executing", None) if owner is not None else None
  91. if owner is None or not isinstance(executing, dict):
  92. turn._publish_execution(event_type, payload)
  93. return
  94. authority, session_id, generation = owner
  95. stream = getattr(authority.sessions.get(session_id), "event_stream", None)
  96. lock = getattr(stream, "lock", None)
  97. import contextlib
  98. # The claim is stamped and cleared under this lock, so the in-turn/out-of-turn choice cannot race the turn's end.
  99. with lock if lock is not None else contextlib.nullcontext():
  100. if executing.get(session_id) == generation:
  101. turn._publish_execution(event_type, payload)
  102. return
  103. if stream is not None and _is_active_session_subagent(turn, payload, event_type):
  104. # A background delegate_task outlives the spawning turn's running claim; publish without borrowing a later turn's execution identity.
  105. stream.publish(session_id, payload, event_type=event_type, execution={})
  106. def publish_progress(turn, event_type, name, preview, kwargs) -> None:
  107. """``subagent.*``, ``reasoning.available`` and the MoA facade events from the agent's progress callback; a classic CLI renders MoA references whatever its reasoning display (main's ``_on_tool_progress``), while other viewers get them only with reasoning shown."""
  108. if isinstance(event_type, str) and event_type.startswith("subagent."):
  109. if event_type == "subagent.text":
  110. return
  111. from tui_gateway.tool_progress import _subagent_payload
  112. _publish_subagent(turn, event_type, _subagent_payload(
  113. event_type, name, preview, kwargs, show_reasoning=show_reasoning(turn)))
  114. return
  115. if event_type == "tool.progress":
  116. from agent.tool_progress_relay import tool_progress_payload
  117. turn._publish_execution(event_type, tool_progress_payload(name, preview, kwargs))
  118. return
  119. if event_type != "reasoning.available" and event_type not in _MOA_KEYS:
  120. return
  121. from gateway.session_cli_turn import classic_cli_turn
  122. if not (show_reasoning(turn) or (event_type != "reasoning.available" and classic_cli_turn(turn))):
  123. return
  124. if event_type == "reasoning.available":
  125. payload = {"text": str(preview or "")}
  126. elif event_type == "moa.reference":
  127. payload = {"label": str(name or ""), "text": str(preview or "")}
  128. elif event_type in ("moa.aggregating", "moa.phase"):
  129. payload = {"aggregator": str(name or "")} if name or event_type == "moa.aggregating" else {}
  130. else:
  131. payload = {"label": str(name or "")}
  132. payload.update({out: kwargs[key] for key, out in _MOA_KEYS.get(event_type, {}).items()
  133. if kwargs.get(key) is not None})
  134. if event_type == "moa.progress" and not {"refs_done", "refs_total"} <= set(payload):
  135. return
  136. if event_type == "moa.phase" and not payload.get("phase"):
  137. return
  138. turn._publish_execution(event_type, payload)
  139. def restore(agent, previous: dict | None) -> None:
  140. if not previous:
  141. return
  142. token = previous.pop(_DESKTOP_UI_TOKEN, None)
  143. if token is not None:
  144. local_desktop_ui.release(token)
  145. for name, value in previous.items():
  146. setattr(agent, name, value)
  147. def publish_control_if_changed(turn) -> None:
  148. """Agent thread, after each tool: a tool (a plugin adding goal criteria, parking the goal) can move
  149. automation state mid-turn, so viewers' cards repaint now instead of at turn end. Scheduled on the
  150. gateway loop, which takes the publish ticket in order with the slash commands' publishes; the snapshot
  151. (three state.db meta reads on the shared connection lock) is read in a worker thread, because one read
  152. per tool across every running session saturated the loop. Revision-gated: other tools publish nothing."""
  153. from gateway.session_control_actions import publish_async
  154. authority, canonical_id, _generation = turn._approval_owner
  155. async def republish():
  156. await publish_async(authority, canonical_id, only_if_changed=True)
  157. turn._schedule(republish(), "session.control.update after a tool")
  158. def note_tool_start(turn, call_id, tool_name=None, args=None) -> None:
  159. """Monotonic start time of one call (``tool.complete.duration_s``) and, for a write-capable
  160. tool, the before-state of its local files: the agent fires the start callback BEFORE the tool
  161. writes, so the gateway owns the snapshot the classic CLI used to take in process."""
  162. key = str(call_id or "")
  163. turn.__dict__.setdefault("_local_tool_starts", {})[key] = time.monotonic()
  164. if tool_name is None:
  165. return
  166. try:
  167. from agent.display import capture_local_edit_snapshot
  168. snapshot = capture_local_edit_snapshot(tool_name, args if isinstance(args, dict) else {},
  169. task_id=turn._ctx.session_id)
  170. except Exception: # health: allow BLE001 -- display-only preview; a failed snapshot only drops the diff
  171. logger.debug("Edit snapshot capture failed for %s", tool_name, exc_info=True)
  172. snapshot = None
  173. if snapshot is not None:
  174. turn.__dict__.setdefault("_local_edit_snapshots", {})[key] = snapshot
  175. def complete_fields(turn, call_id, tool_name=None, args=None, result=None, *, is_error=False) -> dict:
  176. """``duration_s``, ``inline_diff`` (the rendered edit diff main's CLI printed after a write,
  177. ``None`` when there is none), ``image_path`` (the local image the call produced or looked at,
  178. which main's CLI draws inline; ``None`` when there is none or the call failed) and, for the todo tool, the full
  179. ``todos`` snapshot."""
  180. key = str(call_id or "")
  181. started = turn.__dict__.setdefault("_local_tool_starts", {}).pop(key, None)
  182. fields = {"duration_s": (time.monotonic() - started) if started is not None else None}
  183. if tool_name is None:
  184. return fields
  185. snapshot = turn.__dict__.setdefault("_local_edit_snapshots", {}).pop(key, None)
  186. rendered: list[str] = []
  187. try:
  188. from agent.display import render_edit_diff_with_delta
  189. render_edit_diff_with_delta(tool_name, result, function_args=args if isinstance(args, dict) else {},
  190. snapshot=snapshot, print_fn=rendered.append)
  191. except Exception: # health: allow BLE001 -- display-only preview, as main's CLI _on_tool_complete
  192. logger.debug("Edit diff preview failed for %s", tool_name, exc_info=True)
  193. rendered = []
  194. fields["inline_diff"] = "\n".join(rendered) if rendered else None
  195. from agent.terminal_image import tool_image_path
  196. fields["image_path"] = tool_image_path(tool_name, args, result, is_error=is_error)
  197. todo = todo_state(tool_name, result)
  198. if todo is not None:
  199. fields.update(todo)
  200. return fields
  201. def todo_state(tool_name, result) -> dict | None:
  202. """The client-safe ``{todos, revision}`` snapshot a todo tool's result carries, else None."""
  203. from tools.todo_tool import is_todo_tool_name
  204. if not is_todo_tool_name(tool_name):
  205. return None
  206. import json
  207. from tui_gateway.tool_progress import _normalize_todo_state
  208. try:
  209. return _normalize_todo_state(json.loads(result) if isinstance(result, str) else result)
  210. except (TypeError, ValueError):
  211. return None
  212. def prompt_timeout_s(turn, kind) -> int | None:
  213. """``timeout_s`` of a local viewer's approval / clarify prompt: the window the gateway's own wait
  214. enforces (``approvals.timeout`` / the clarify timeout), so the classic CLI's modal shows the
  215. same countdown and gives up when the gateway does. ``None`` on a messaging turn (frame
  216. unchanged) and for an unlimited clarify wait."""
  217. from gateway.run_turn_progress import local_viewer_turn
  218. if not local_viewer_turn(turn):
  219. return None
  220. # Both readers fall back to their defaults themselves; they never raise.
  221. if kind == "approval":
  222. from tools.approval_context import _get_approval_timeout
  223. seconds = int(_get_approval_timeout())
  224. else:
  225. from tools.clarify_gateway import get_clarify_timeout
  226. seconds = int(get_clarify_timeout())
  227. return seconds if seconds > 0 else None