inline_tool_executors.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """Agent-level ("inline") tool executors shared by the sequential and concurrent tool paths.
  2. These tools need live ``AIAgent`` state (stores, callbacks, session DB) and therefore
  3. bypass the tool registry. Each executor is ``fn(agent, args, ctx) -> result``; the
  4. table replaces two hand-maintained if/elif chains (``invoke_tool`` and
  5. ``execute_tool_calls_sequential``) that had drifted apart. Tool modules are imported
  6. lazily at call time so ``patch("tools.x.y")`` in tests keeps working.
  7. """
  8. from __future__ import annotations
  9. import json
  10. from dataclasses import dataclass
  11. from importlib import import_module
  12. from typing import Any, Callable, Dict, Optional, Tuple
  13. from tools.arg_coercion import coerce_tool_args
  14. def tool_hook_ids(agent, effective_task_id: str, tool_call_id: Optional[str]) -> dict[str, str]:
  15. """Identity kwargs every tool hook/middleware call carries (all coerced to ``""``)."""
  16. return {
  17. "task_id": effective_task_id or "",
  18. "session_id": getattr(agent, "session_id", "") or "",
  19. "tool_call_id": tool_call_id or "",
  20. "turn_id": getattr(agent, "_current_turn_id", "") or "",
  21. "api_request_id": getattr(agent, "_current_api_request_id", "") or "",
  22. }
  23. def emit_terminal_post_tool_call(
  24. agent,
  25. *,
  26. function_name: str,
  27. function_args: dict,
  28. result: Any,
  29. effective_task_id: str,
  30. tool_call_id: Optional[str],
  31. duration_ms: int = 0,
  32. status: Optional[str] = None,
  33. error_type: Optional[str] = None,
  34. error_message: Optional[str] = None,
  35. middleware_trace: Optional[list] = None,
  36. ) -> None:
  37. """Emit the one terminal ``post_tool_call`` hook for a tool_call_id (best-effort)."""
  38. try:
  39. from model_tools import _emit_post_tool_call_hook
  40. _emit_post_tool_call_hook(
  41. function_name=function_name,
  42. function_args=function_args,
  43. result=result,
  44. **tool_hook_ids(agent, effective_task_id, tool_call_id),
  45. duration_ms=duration_ms,
  46. status=status,
  47. error_type=error_type,
  48. error_message=error_message,
  49. middleware_trace=list(middleware_trace or []),
  50. )
  51. except Exception:
  52. pass
  53. def apply_transform_tool_result(
  54. agent,
  55. *,
  56. function_name: str,
  57. function_args: dict,
  58. result: Any,
  59. effective_task_id: str,
  60. tool_call_id: Optional[str],
  61. duration_ms: int = 0,
  62. ) -> Any:
  63. """Apply ``transform_tool_result`` to an inline-dispatched tool's result.
  64. Registry tools get this inside ``handle_function_call``; inline executors never
  65. reach it, so the agent paths call the same helper (after the terminal
  66. ``post_tool_call``) to keep the hook's "every tool" contract. Fail-open."""
  67. try:
  68. from model_tools import _CallIds, _apply_transform_tool_result_hook
  69. return _apply_transform_tool_result_hook(
  70. function_name, function_args, result, duration_ms,
  71. _CallIds(**tool_hook_ids(agent, effective_task_id, tool_call_id)),
  72. )
  73. except Exception:
  74. return result
  75. @dataclass
  76. class InlineToolContext:
  77. """Per-call state an inline executor may need beyond its arguments."""
  78. effective_task_id: str
  79. tool_call_id: Optional[str] = None
  80. messages: Optional[list] = None
  81. InlineToolExecutor = Callable[[Any, dict, InlineToolContext], Any]
  82. # ``(kwarg, args_key)`` → ``args.get(key)``; ``(kwarg, args_key, default)`` → ``args.get(key, default)``.
  83. _ArgSpec = tuple[Any, ...]
  84. def _call_tool(module: str, func: str, args: dict, arg_specs: tuple[_ArgSpec, ...], **fixed: Any) -> Any:
  85. """Import ``module.func`` lazily and call it with args mapped per ``arg_specs`` plus ``fixed``."""
  86. fn = getattr(import_module(module), func)
  87. return fn(**{spec[0]: args.get(*spec[1:]) for spec in arg_specs}, **fixed)
  88. def _tool(
  89. module: str, func: str, *arg_specs: _ArgSpec, **fixed: Callable[[Any, InlineToolContext], Any],
  90. ) -> InlineToolExecutor:
  91. """Executor calling ``module.func`` with mapped args plus ``fixed`` kwargs computed from ``(agent, ctx)``."""
  92. def _exec(agent, args: dict, ctx: InlineToolContext) -> Any:
  93. return _call_tool(module, func, args, arg_specs, **{k: f(agent, ctx) for k, f in fixed.items()})
  94. return _exec
  95. def _callback_tool(module: str, func: str, callback_attr: str, *arg_specs: _ArgSpec) -> InlineToolExecutor:
  96. """Executor for a GUI-callback tool: mapped args plus ``callback=getattr(agent, callback_attr, None)``."""
  97. return _tool(module, func, *arg_specs, callback=lambda agent, ctx: getattr(agent, callback_attr, None))
  98. def _session_search(agent, args: dict, ctx: InlineToolContext) -> Any:
  99. session_db = agent._get_session_db_for_recall()
  100. if not session_db:
  101. from hermes_state import format_session_db_unavailable
  102. return json.dumps({"success": False, "error": format_session_db_unavailable()})
  103. return _call_tool(
  104. "tools.session_search_tool", "session_search", args,
  105. (
  106. ("query", "query", ""), ("role_filter", "role_filter"), ("limit", "limit"),
  107. ("session_id", "session_id"), ("around_message_id", "around_message_id"),
  108. ("window", "window", 5), ("sort", "sort"), ("profile", "profile"),
  109. ("detail", "detail", "adaptive"), ("after", "after"), ("before", "before"),
  110. ("exclude_session_ids", "exclude_session_ids"),
  111. ),
  112. db=session_db, current_session_id=agent.session_id,
  113. )
  114. def _memory(agent, args: dict, ctx: InlineToolContext) -> Any:
  115. from agent.runtime_context import current
  116. if current() is not None:
  117. # Retired: Yaovi workspace memory is the only store and is reached via workspace_memory_* tools.
  118. return json.dumps({"success": False, "error": "tool 'memory' is retired in Yaoyao; use workspace_memory_search / workspace_memory_write / workspace_memory_forget"}, ensure_ascii=False)
  119. result = _call_tool(
  120. "tools.memory_tool", "memory_tool", args,
  121. (
  122. ("action", "action"), ("target", "target"), ("content", "content"),
  123. ("old_text", "old_text"), ("new_text", "new_text"), ("operations", "operations"),
  124. ),
  125. store=agent._memory_store,
  126. )
  127. # Mirror built-in memory writes to external providers; gating lives in
  128. # MemoryManager.notify_memory_tool_write.
  129. if agent._memory_manager:
  130. agent._memory_manager.notify_memory_tool_write(
  131. result,
  132. args,
  133. build_metadata=lambda: agent._build_memory_write_metadata(
  134. task_id=ctx.effective_task_id,
  135. tool_call_id=ctx.tool_call_id,
  136. ),
  137. )
  138. return result
  139. _read_preview = _callback_tool(
  140. "tools.read_preview_tool", "read_preview_tool", "read_preview_callback",
  141. ("start", "start"), ("count", "count"),
  142. )
  143. def _desktop_preview(agent, args: dict, ctx: InlineToolContext) -> Any:
  144. # action=read needs the GUI callback (agent-level); open/close go through the
  145. # registry handler like any other tool.
  146. if (args.get("action") or "").strip() == "read":
  147. return _read_preview(agent, args, ctx)
  148. from tools.preview_tool import _handle_preview
  149. return _handle_preview(args)
  150. def _manage_connections(agent, args: dict, ctx: InlineToolContext) -> Any:
  151. # Embedded runs use the application's shared connection home and approval
  152. # lifecycle, including this inline path used before registry dispatch.
  153. from agent.runtime_context import current as embedded_context, dispatch as embedded_dispatch
  154. embedded = embedded_context()
  155. if embedded is not None:
  156. if "manage_connections" not in {entry.get("name") for entry in embedded.get("tools", [])}:
  157. return json.dumps({"error": "本轮未授权应用连接管理工具。"}, ensure_ascii=False)
  158. return embedded_dispatch("manage_connections", args, **tool_hook_ids(agent, ctx.effective_task_id, ctx.tool_call_id))
  159. # The GUI callback lives on the agent; registry dispatch never forwards it.
  160. from tools.connectors import manage_connections
  161. from tools.connectors.gateway import config as gateway_config
  162. result = manage_connections(
  163. args, session_id=getattr(agent, "session_id", None), tool_call_id=ctx.tool_call_id,
  164. turn_id=getattr(agent, "_current_turn_id", None) or None,
  165. connection_callback=getattr(agent, "connection_callback", None),
  166. connectors_available=gateway_config.connectors_available,
  167. card_surface=getattr(agent, "platform", None) == "desktop",
  168. )
  169. _scope_in_connected_mcp_servers(agent, result)
  170. return result
  171. def _scope_in_connected_mcp_servers(agent, result: Any) -> None:
  172. """Add the MCP servers this call connected to the agent's toolset selection.
  173. ``tool_describe``/``tool_call`` resolve names inside that selection, and it was fixed when the
  174. agent was built, so a server registered a moment ago is otherwise "not found" for the rest of
  175. the turn the result calls it available in. Only the selection changes; ``agent.tools`` does
  176. not, so the sent tool schema bytes stay the same."""
  177. enabled = getattr(agent, "enabled_toolsets", None)
  178. if enabled is None or "no_mcp" in enabled: # None already means every toolset
  179. return
  180. try:
  181. targets = json.loads(result).get("targets") or []
  182. except (AttributeError, TypeError, ValueError):
  183. return
  184. connected = [str(t.get("name")) for t in targets if isinstance(t, dict)
  185. and t.get("kind") == "mcp" and t.get("state") == "connected" and t.get("tools")]
  186. added = [name for name in connected if name not in enabled]
  187. if added:
  188. agent.enabled_toolsets = [*enabled, *added]
  189. def _manage_catalog(agent, args: dict, ctx: InlineToolContext) -> Any:
  190. # The card callback lives on the agent; only a desktop chat draws catalog rows.
  191. from tools.connectors.catalog_tool import manage_catalog
  192. return manage_catalog(
  193. args, session_id=getattr(agent, "session_id", None), tool_call_id=ctx.tool_call_id,
  194. connection_callback=getattr(agent, "connection_callback", None),
  195. card_surface=getattr(agent, "platform", None) == "desktop",
  196. )
  197. def _setup_beat(agent, args: dict, ctx: InlineToolContext) -> Any:
  198. # The run record lives on the session row and the card callback on the agent. A card the user wrote
  199. # past ends the turn as a new message does: setup_beat runs inline (never parallel), so its result is
  200. # kept and the loop stops before the next model call.
  201. from agent.interrupt_control import _REASON_NEW_MESSAGE
  202. from tools.setup_beat_tool import setup_beat_tool
  203. return setup_beat_tool(
  204. args, db=getattr(agent, "_session_db", None), session_id=getattr(agent, "session_id", None) or "",
  205. tool_call_id=ctx.tool_call_id or "", callback=getattr(agent, "setup_beat_callback", None),
  206. end_turn=lambda: agent.interrupt(tool_reason=_REASON_NEW_MESSAGE),
  207. )
  208. def _setup_mcp_shim(agent, args: dict, ctx: InlineToolContext) -> Any:
  209. # Replay shim for conversations whose cached prompt still names setup_mcp.
  210. # Not in _LEGACY_TOOL_ALIASES: inline tools bypass handle_function_call.
  211. return _manage_connections(agent, {
  212. "action": args.get("action", "install"),
  213. "connectors": [{"name": args.get("server", ""), "mcp": True}],
  214. }, ctx)
  215. # Order is the historical if/elif order of ``execute_tool_calls_sequential``.
  216. _RAW_INLINE_TOOL_EXECUTORS: dict[str, InlineToolExecutor] = {
  217. "todo_list": _tool(
  218. "tools.todo_tool", "todo_tool", ("todos", "todos"), ("merge", "merge", False),
  219. store=lambda agent, ctx: agent._todo_store,
  220. ),
  221. # Bot Mode teammate DM is injected, not registered: only a canonical Bot
  222. # Chat session carries the schema, and the tool re-gates on the title.
  223. "message_agent": _tool(
  224. "tools.bot_mode_dm", "message_agent_tool", ("target", "target", ""), ("message", "message", ""),
  225. ("expects_reply", "expects_reply", True), ("cancel", "cancel", ""),
  226. ("constraints", "constraints", ""), ("expecting", "expecting", ""),
  227. task_id=lambda agent, ctx: ctx.effective_task_id, agent=lambda agent, ctx: agent,
  228. ),
  229. "session_search": _session_search,
  230. "memory": _memory,
  231. "clarify": _tool(
  232. "tools.clarify_tool", "clarify_tool", ("questions", "questions"),
  233. callback=lambda agent, ctx: agent.clarify_callback,
  234. ),
  235. "read_terminal": _callback_tool(
  236. "tools.read_terminal_tool", "read_terminal_tool", "read_terminal_callback",
  237. ("start_line", "start_line"), ("count", "count"),
  238. ),
  239. "desktop_preview": _desktop_preview,
  240. "drive_preview": _callback_tool(
  241. "tools.drive_preview_tool", "drive_preview_tool", "drive_preview_callback",
  242. ("action", "action", ""), ("ref", "ref"), ("selector", "selector"), ("text", "text"),
  243. ("key", "key"), ("submit", "submit"), ("amount", "amount"), ("to", "to"), ("limit", "max"),
  244. ),
  245. "annotate_preview": _callback_tool(
  246. "tools.annotate_preview_tool", "annotate_preview_tool", "drive_preview_callback",
  247. ("action", "action", "add"), ("ref", "ref"), ("selector", "selector"), ("label", "label"),
  248. ),
  249. "read_window_below": _callback_tool(
  250. "tools.read_window_tool", "read_window_below_tool", "read_window_below_callback",
  251. ),
  252. "gui_tour": _callback_tool(
  253. "tools.tour_tool", "tour_tool", "tour_callback",
  254. ("action", "action", ""), ("surface", "surface"), ("selector", "selector"), ("title", "title"),
  255. ("text", "text"), ("side", "side"), ("steps", "steps"), ("step_index", "step_index"),
  256. ("preset", "preset"),
  257. ),
  258. "set_theme": _callback_tool(
  259. "tools.set_theme_tool", "set_theme_tool", "theme_callback",
  260. ("accent", "accent"), ("mode", "mode"), ("layout", "layout"), ("picker", "picker"),
  261. ),
  262. "setup_beat": _setup_beat,
  263. "manage_connections": _manage_connections,
  264. "manage_catalog": _manage_catalog,
  265. "setup_mcp": _setup_mcp_shim,
  266. "delegate_task": lambda agent, args, ctx: agent._dispatch_delegate_task(args),
  267. }
  268. def _coerced(name: str, executor: InlineToolExecutor) -> InlineToolExecutor:
  269. def _exec(agent, args: dict, ctx: InlineToolContext) -> Any:
  270. return executor(agent, coerce_tool_args(name, args), ctx)
  271. return _exec
  272. INLINE_TOOL_EXECUTORS: dict[str, InlineToolExecutor] = {
  273. name: _coerced(name, executor) for name, executor in _RAW_INLINE_TOOL_EXECUTORS.items()
  274. }
  275. # ``invoke_tool`` (concurrent path) consults the memory manager right after these three
  276. # names and before the remaining inline tools; ``message_agent`` falls through to the
  277. # registry there (Bot Mode DM is only injected into the sequential path's schema).
  278. INVOKE_TOOL_PRE_MEMORY_MANAGER_NAMES = frozenset({"todo_list", "session_search", "memory"})
  279. def resolve_invoke_tool_executor(agent, function_name: str) -> Optional[InlineToolExecutor]:
  280. """Inline executor for ``invoke_tool`` (concurrent path), or None for registry dispatch.
  281. Precedence: todo_list/session_search/memory, then memory-manager tools, then the
  282. remaining inline tools (``message_agent`` excluded).
  283. """
  284. if function_name in INVOKE_TOOL_PRE_MEMORY_MANAGER_NAMES:
  285. return INLINE_TOOL_EXECUTORS[function_name]
  286. memory_manager = agent._memory_manager
  287. if memory_manager and memory_manager.has_tool(function_name):
  288. return lambda agent, args, ctx: agent._memory_manager.handle_tool_call(
  289. function_name, args,
  290. caller_gsk=(getattr(agent, "_gateway_session_key", "") or ""),
  291. )
  292. if function_name == "message_agent":
  293. return None
  294. return INLINE_TOOL_EXECUTORS.get(function_name)