tools.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. """ACP tool-call helpers for mapping hermes tools to ACP ToolKind and building content."""
  2. from __future__ import annotations
  3. import json
  4. import logging
  5. import uuid
  6. from typing import Any, Callable, Dict, List, Optional
  7. import acp
  8. from acp.schema import ToolCallLocation, ToolCallProgress, ToolCallStart, ToolKind
  9. from agent.display import build_tool_preview
  10. logger = logging.getLogger(__name__)
  11. # Hermes tool name -> ACP ToolKind (anything unlisted is "other").
  12. TOOL_KIND_MAP: dict[str, ToolKind] = {
  13. name: kind
  14. for kind, names in {
  15. "read": ("read_file", "skill_view", "skills_list", "browser_snapshot", "browser_vision",
  16. "browser_get_images", "vision_analyze"),
  17. "edit": ("write_file", "patch", "skill_manage"),
  18. "search": ("search_files",),
  19. "execute": ("terminal", "process", "execute_code", "browser_click", "browser_type", "browser_scroll",
  20. "browser_press", "browser_back", "delegate_task", "image_generate", "text_to_speech"),
  21. "fetch": ("web_search", "web_extract", "browser_navigate"),
  22. "other": ("todo",),
  23. "think": ("_thinking",),
  24. }.items()
  25. for name in names
  26. }
  27. # Tools whose results render through the curated formatters below (raw JSON is
  28. # suppressed for these); unknown/plugin tools stay conservative.
  29. _POLISHED_TOOLS = {
  30. # Core operator loop
  31. "todo", "memory", "session_search", "delegate_task",
  32. # Files / execution
  33. "read_file", "write_file", "patch", "search_files", "terminal", "process", "execute_code",
  34. # Skills / web / browser / media
  35. "skill_view", "skills_list", "skill_manage", "web_search", "web_extract",
  36. "browser_navigate", "browser_click", "browser_type", "browser_press", "browser_scroll",
  37. "browser_back", "browser_snapshot", "browser_console", "browser_get_images", "browser_vision",
  38. "vision_analyze", "image_generate", "text_to_speech",
  39. # Schedulers / platform integrations
  40. "cronjob", "send_message", "clarify", "discord", "discord_admin",
  41. "feishu_doc_read", "feishu_drive_list_comments", "feishu_drive_list_comment_replies",
  42. "feishu_drive_reply_comment", "feishu_drive_add_comment",
  43. "kanban_create", "kanban_show", "kanban_comment", "kanban_complete",
  44. "kanban_block", "kanban_request_review", "kanban_request_changes",
  45. "kanban_link", "kanban_heartbeat",
  46. "yb_query_group_info", "yb_query_group_members", "yb_search_sticker",
  47. "yb_send_dm", "yb_send_sticker",
  48. }
  49. _EMPTYISH = (None, "", [], {})
  50. Args = dict[str, Any]
  51. _Formatter = Callable[[str, Optional[str], Optional[Args]], Optional[str]]
  52. def get_tool_kind(tool_name: str) -> ToolKind:
  53. """Return the ACP ToolKind for a hermes tool, defaulting to 'other'."""
  54. return TOOL_KIND_MAP.get(tool_name, "other")
  55. def make_tool_call_id() -> str:
  56. return f"tc-{uuid.uuid4().hex[:12]}"
  57. # --- small shared helpers ---------------------------------------------------
  58. def _text(content: str) -> Any:
  59. return acp.tool_content(acp.text_block(content))
  60. def _arg(args: Optional[Args], *keys: str, default: str = "") -> str:
  61. """First truthy ``args[key]`` as a stripped string, else ``default``."""
  62. return str(_first(args or {}, *keys, default=default)).strip() or default
  63. def _first(data: Args, *keys: str, default: Any = "") -> Any:
  64. """First truthy ``data[key]`` in ``keys`` order, else ``default``."""
  65. return next((data[k] for k in keys if data.get(k)), default)
  66. def _fmt(value: Any, template: str, fallback: str) -> str:
  67. """``template.format(value)`` when value is truthy, else ``fallback``."""
  68. return template.format(value) if value else fallback
  69. def _nonempty(result: Optional[str]) -> Optional[str]:
  70. return result if isinstance(result, str) and result.strip() else None
  71. def _plural(count: int, word: str, suffix: str = "s") -> str:
  72. return f"{count} {word}{suffix if count != 1 else ''}"
  73. def _failure(data: Args, prefix: str) -> Optional[str]:
  74. """Structured tool-level failure text (``success: false`` or ``error`` set)."""
  75. failed = data.get("success") is False or data.get("error")
  76. return f"{prefix}: {data.get('error', 'unknown error')}" if failed else None
  77. def _structured(text_fallback: bool = False):
  78. """Completion formatter taking ``(tool_name, data: dict, args: dict)``; the wrapper parses
  79. ``result`` and returns ``None`` (or the raw text when ``text_fallback``) for non-dict payloads."""
  80. def deco(fn: Callable[[str, Args, Args], Optional[str]]) -> _Formatter:
  81. def wrapper(tool_name: str, result: Optional[str], args: Optional[Args]) -> Optional[str]:
  82. if isinstance(data := _json_loads_maybe(result), dict):
  83. return fn(tool_name, data, args or {})
  84. return _nonempty(result) if text_fallback else None
  85. return wrapper
  86. return deco
  87. def coerce_tool_args(raw: Any) -> Args:
  88. """Tool-call arguments as a dict: JSON strings are decoded (undecodable -> ``{"raw": ...}``),
  89. anything else non-dict becomes ``{}``."""
  90. if isinstance(raw, str):
  91. try:
  92. raw = json.loads(raw)
  93. except Exception:
  94. raw = {"raw": raw}
  95. return raw if isinstance(raw, dict) else {}
  96. def _args_json(arguments: Any) -> str:
  97. try:
  98. return json.dumps(arguments, indent=2, default=str)
  99. except (TypeError, ValueError):
  100. return str(arguments)
  101. def _json_loads_maybe(value: Optional[str]) -> Any:
  102. """Decode a JSON string; non-strings pass through, undecodable strings yield None.
  103. Some Hermes tools append a human hint after the payload (``{...}\\n\\n[Hint: ...]``),
  104. so fall back to decoding the first JSON value to keep the structured rendering path."""
  105. if not isinstance(value, str):
  106. return value
  107. try:
  108. return json.loads(value)
  109. except Exception:
  110. pass
  111. try:
  112. return json.JSONDecoder().raw_decode(value.lstrip())[0]
  113. except Exception:
  114. return None
  115. def _truncate_text(text: str, limit: int = 5000) -> str:
  116. return text if len(text) <= limit else text[: max(0, limit - 100)] + f"\n... ({len(text)} chars total, truncated)"
  117. def _fenced_text(text: str, language: str = "") -> str:
  118. """Return a Markdown fence that cannot be broken by backticks in text."""
  119. longest = max((len(run) for run in text.split("`")[1::2]), default=0)
  120. fence = "`" * max(3, longest + 1)
  121. return f"{fence}{language}\n{text}\n{fence}"
  122. def _tool_result_failed(result: Optional[str], tool_name: str | None = None) -> bool:
  123. """Return True when a structured Hermes tool result clearly failed.
  124. Deliberately conservative: plain text may legitimately contain "error", so
  125. only structured tool-level failures map to ACP failed status."""
  126. # The agent's tool executor wraps raised exceptions in a canonical
  127. # "Error executing tool '<name>': ..." prefix that well-behaved tool output
  128. # cannot produce; catch it so a tool that blew up is not shown green.
  129. if isinstance(result, str) and result.startswith("Error executing tool '"):
  130. return True
  131. data = _json_loads_maybe(result)
  132. if not isinstance(data, dict):
  133. return False
  134. exit_code = data.get("exit_code", data.get("returncode"))
  135. if any(data.get(key) is False for key in ("success", "ok")) or (isinstance(exit_code, int) and exit_code != 0):
  136. return True
  137. # Polished tools report failures as {"error": ...} without a success flag;
  138. # generic/plugin payloads stay conservative so diagnostics aren't marked failed.
  139. return bool(tool_name in _POLISHED_TOOLS and data.get("error") and not data.get("content"))
  140. # --- tool-call titles -------------------------------------------------------
  141. def build_tool_title(tool_name: str, args: Args) -> str:
  142. """``<tool_name>: <preview>`` using the same per-tool preview (and argument redaction) as
  143. every other Hermes surface, so ACP clients never show a different summary than the CLI/TUI;
  144. bare tool name when the arguments yield no preview."""
  145. preview = build_tool_preview(tool_name, args, max_len=80)
  146. return f"{tool_name}: {preview}" if preview else tool_name
  147. # --- completion formatters; all share the signature (tool_name, result, args) --
  148. @_structured()
  149. def _format_todo_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  150. if not isinstance(data.get("todos"), list):
  151. return None
  152. icon = {"completed": "✅", "in_progress": "🔄", "pending": "⏳", "cancelled": "✗"}
  153. todos = [t for t in data["todos"] if isinstance(t, dict)]
  154. by_id = {str(t.get("id") or ""): t for t in todos}
  155. def _depth(item: Args) -> int:
  156. depth, seen = 0, set()
  157. while (parent := str(item.get("parent") or "")) and parent in by_id and parent not in seen:
  158. seen.add(parent)
  159. depth += 1
  160. item = by_id[parent]
  161. return min(depth, 4)
  162. lines = ["**Todo list**", ""]
  163. for item in todos:
  164. if content := str(item.get("content") or item.get("id") or "").strip():
  165. lines.append(f"{' ' * _depth(item)}- {icon.get(str(item.get('status') or 'pending'), '•')} {content}")
  166. if isinstance(summary := data.get("summary"), dict) and summary:
  167. cancelled = summary.get("cancelled", 0)
  168. progress = f"{summary.get('completed', 0)} completed, {summary.get('in_progress', 0)} in progress, "
  169. progress += f"{summary.get('pending', 0)} pending" + (f", {cancelled} cancelled" if cancelled else "")
  170. lines += ["", f"**Progress:** {progress}"]
  171. return "\n".join(lines)
  172. @_structured()
  173. def _format_read_file_result(tool_name: str, data: Args, a: Args) -> Optional[str]:
  174. if data.get("error") and not data.get("content"):
  175. return f"Read failed: {data.get('error')}"
  176. if not isinstance(content := data.get("content"), str):
  177. return None
  178. range_bits = [f"{label} {a[key]}" for key, label in (("offset", "from line"), ("limit", "limit")) if a.get(key)]
  179. header = f"Read {str(a.get('path') or data.get('path') or 'file').strip()}"
  180. header += f" ({', '.join(range_bits)})" if range_bits else ""
  181. header += f" — {data.get('total_lines')} total lines" if data.get("total_lines") is not None else ""
  182. # read_file output is `|`-line-numbered; raw Markdown would let Zed parse
  183. # pipes as tables, so fence the payload to keep lines literal.
  184. return _truncate_text(f"{header}\n\n{_fenced_text(content)}")
  185. @_structured()
  186. def _format_search_files_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  187. files, matches = data.get("files"), data.get("matches")
  188. # Surface file/image attachments as compact text markers. The thread-context fetch is text-only, so
  189. # without this the agent has no idea prior messages carried images/files at all (#69185, #32315): "@bot
  190. # what do you think of the chart above?" reads as a question about nothing. Markers keep context bounded
  191. # — the agent can ask for a re-share (or the caller may separately deliver the thread root's image, see
  192. # _collect_thread_root_images).
  193. if isinstance(files, list):
  194. shown = min(len(files), 20)
  195. lines = ["File search results", f"Found {_plural(data.get('total_count', len(files)), 'file')}; showing {shown}.", ""]
  196. lines.extend(f"- {path}" for path in files[:shown])
  197. if bool(data.get("truncated")) or len(files) > shown:
  198. lines.extend(["", "Results truncated. Narrow the search, add path/file_glob, or use offset to page."])
  199. return _truncate_text("\n".join(lines), limit=7000)
  200. if not isinstance(matches, list):
  201. return None
  202. shown = min(len(matches), 12)
  203. lines = ["Search results", f"Found {_plural(data.get('total_count', len(matches)), 'match', 'es')}; showing {shown}.", ""]
  204. for match in matches[:shown]:
  205. if not isinstance(match, dict):
  206. lines.append(f"- {match}")
  207. continue
  208. path = str(_first(match, "path", "file", "filename", default="?"))
  209. line = match.get("line") or match.get("line_number")
  210. lines.append(f"- {path}:{line}" if line else f"- {path}")
  211. if content := str(match.get("content") or match.get("text") or "").strip():
  212. lines.append(f" {_truncate_text(' '.join(content.split()), 300)}")
  213. if bool(data.get("truncated")) or len(matches) > shown:
  214. lines.extend(["", "Results truncated. Narrow the search, add file_glob, or use offset to page."])
  215. return _truncate_text("\n".join(lines), limit=7000)
  216. @_structured(text_fallback=True)
  217. def _format_execute_code_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  218. exit_code = data.get("exit_code")
  219. parts = [f"Exit code: {exit_code}" if exit_code is not None else "Execution complete"]
  220. if data.get("stdout_truncated"):
  221. total, captured, omitted = (data.get(k) for k in ("stdout_bytes_total", "stdout_bytes_captured", "stdout_bytes_omitted"))
  222. if all(isinstance(v, int) for v in (captured, total, omitted)):
  223. parts.extend(["", f"Output truncated: captured {captured:,} of {total:,} bytes ({omitted:,} omitted)."])
  224. else:
  225. parts.extend(["", "Output truncated."])
  226. for key, label, value in (
  227. ("warning", "Warning:", str(data.get("warning") or "").strip()),
  228. ("output", "Output:", str(data.get("output") or "")), ("error", "Error:", str(data.get("error") or "")),
  229. ):
  230. if value:
  231. parts.extend(["", label, value])
  232. return _truncate_text("\n".join(parts))
  233. @_structured()
  234. def _format_skill_view_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  235. if data.get("success") is False:
  236. return f"Skill view failed: {data.get('error', 'unknown error')}"
  237. content = str(data.get("content") or "")
  238. lines = ["**Skill loaded**", "", f"- **Name:** `{data.get('name') or 'skill'}`",
  239. f"- **File:** `{data.get('file') or data.get('path') or 'SKILL.md'}`"]
  240. if description := str(data.get("description") or "").strip():
  241. lines.append(f"- **Description:** {description}")
  242. if content:
  243. lines.append(f"- **Content:** {len(content):,} chars loaded into agent context")
  244. if isinstance(linked := data.get("linked_files"), dict) and linked:
  245. lines.append(f"- **Linked files:** {sum(len(v) for v in linked.values() if isinstance(v, list))}")
  246. stripped = (line.strip() for line in content.splitlines())
  247. if headings := [h for h in (s.lstrip("#").strip() for s in stripped if s.startswith("#")) if h][:8]:
  248. lines.extend(["", "**Sections**", *(f"- {heading}" for heading in headings)])
  249. lines.extend(["", "_Full skill content is available to the agent but hidden here to keep ACP readable._"])
  250. return "\n".join(lines)
  251. @_structured()
  252. def _format_skill_manage_result(tool_name: str, data: Args, a: Args) -> Optional[str]:
  253. action = _arg(a, "action", default="manage")
  254. name = str(a.get("name") or data.get("name") or "skill").strip() or "skill"
  255. file_path = str(a.get("file_path") or data.get("file_path") or "SKILL.md").strip() or "SKILL.md"
  256. status = "✅ Skill updated" if data.get("success") is not False else "✗ Skill update failed"
  257. lines = [f"**{status}**", "", f"- **Action:** `{action}`", f"- **Skill:** `{name}`"]
  258. if action != "delete":
  259. lines.append(f"- **File:** `{file_path}`")
  260. if message := str(data.get("message") or data.get("error") or "").strip():
  261. lines.append(f"- **Result:** {message}")
  262. if (replacements := data.get("replacements") or data.get("replacement_count")) is not None:
  263. lines.append(f"- **Replacements:** {replacements}")
  264. if path := str(data.get("path") or "").strip():
  265. lines.append(f"- **Path:** `{path}`")
  266. return "\n".join(lines)
  267. @_structured()
  268. def _format_web_search_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  269. web = data.get("data", {}).get("web") if isinstance(data.get("data"), dict) else data.get("web")
  270. if not isinstance(web, list):
  271. return None
  272. lines = [f"Web results: {len(web)}"]
  273. for item in web[:10]:
  274. if not isinstance(item, dict):
  275. continue
  276. url = str(item.get("url") or "").strip()
  277. lines.append(f"• {str(item.get('title') or item.get('url') or 'result').strip()}" + (f" — {url}" if url else ""))
  278. if desc := str(item.get("description") or "").strip():
  279. lines.append(f" {desc}")
  280. return _truncate_text("\n".join(lines))
  281. @_structured()
  282. def _format_web_extract_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  283. """Return only web_extract errors for ACP; success stays compact via title."""
  284. if data.get("success") is False and data.get("error"):
  285. return f"Web extract failed: {data.get('error')}"
  286. if not isinstance(results := data.get("results"), list):
  287. return None
  288. failures: list[str] = []
  289. for item in results[:10]:
  290. error = str(item.get("error") or "").strip() if isinstance(item, dict) else ""
  291. if not error or error in {"None", "null"}:
  292. continue
  293. url = str(item.get("url") or "").strip()
  294. title = str(item.get("title") or url or "Untitled").strip()
  295. where = f" — {url}" if url and url != title else ""
  296. failures.append(f"- {title}{where}\n Error: {_truncate_text(error, limit=500)}")
  297. return "\n".join([f"Web extract failed for {_plural(len(failures), 'URL')}", *failures]) if failures else None
  298. @_structured(text_fallback=True)
  299. def _format_process_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  300. if data.get("success") is False and data.get("error"):
  301. return f"Process error: {data.get('error')}"
  302. action = _arg(args, "action", default="process")
  303. if isinstance(processes := data.get("processes"), list):
  304. lines = [f"Processes: {len(processes)}"]
  305. for proc in processes[:20]:
  306. if not isinstance(proc, dict):
  307. lines.append(f"- {proc}")
  308. continue
  309. bits = [str(proc.get("status") or ("exited" if proc.get("exited") else "running"))]
  310. bits += [f"{lbl} {proc[k]}" for k, lbl in (("pid", "pid"), ("exit_code", "exit")) if proc.get(k) is not None]
  311. cmd = str(proc.get("command") or "").strip()
  312. sid = _first(proc, "session_id", "id", default="?")
  313. lines.append(f"- `{sid}` — {', '.join(bits)}" + (f" — {cmd[:120]}" if cmd else ""))
  314. return "\n".join(lines + _more(processes, 20, " process(es)"))
  315. status = str(data.get("status") or data.get("state") or action).strip()
  316. sid = str(data.get("session_id") or args.get("session_id") or "").strip()
  317. lines = [f"Process {action}: {status}" + (f" (`{sid}`)" if sid else "")]
  318. for key, label in (("command", "Command"), ("pid", "PID"), ("exit_code", "Exit code"), ("returncode", "Exit code"), ("lines", "Lines")):
  319. if data.get(key) is not None:
  320. lines.append(f"- **{label}:** {data.get(key)}")
  321. output = _first(data, "output", "new_output", "log", "stdout", default=None)
  322. error = _first(data, "error", "stderr", default=None)
  323. for label, value, limit in (("Output:", output, 5000), ("Error:", error, 2000)):
  324. if value:
  325. lines.extend(["", label, _truncate_text(str(value), limit=limit)])
  326. if data.get("message") and not output and not error:
  327. lines.append(str(data.get("message")))
  328. return _truncate_text("\n".join(lines), limit=7000)
  329. @_structured()
  330. def _format_delegate_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  331. if not isinstance(results := data.get("results"), list):
  332. return f"Delegation failed: {data.get('error')}" if data.get("error") else None
  333. total = data.get("total_duration_seconds")
  334. lines = [f"Delegation results: {_plural(len(results), 'task')}" + (f" in {total}s" if total is not None else "")]
  335. icon = {"completed": "✅", "failed": "✗", "error": "✗", "timeout": "⏱", "interrupted": "⚠"}
  336. for item in results:
  337. if not isinstance(item, dict):
  338. lines.append(f"- {item}")
  339. continue
  340. idx, status = item.get("task_index"), str(item.get("status") or "unknown")
  341. header = f"{icon.get(status, '•')} Task {idx + 1 if isinstance(idx, int) else '?'}: {status}"
  342. bits = [str(item["model"])] if item.get("model") else []
  343. bits += [f"role={item['_child_role']}"] if item.get("_child_role") else []
  344. bits += [f"{item['duration_seconds']}s"] if item.get("duration_seconds") is not None else []
  345. lines.extend(["", header + (" (" + ", ".join(bits) + ")" if bits else "")])
  346. for key, prefix, limit in (("summary", "", 1200), ("error", "Error: ", 800)):
  347. if value := str(item.get(key) or "").strip():
  348. lines.append(prefix + _truncate_text(value, limit=limit))
  349. trace = item.get("tool_trace") if isinstance(item.get("tool_trace"), list) else []
  350. if names := [str(t.get("tool") or "?") for t in trace if isinstance(t, dict)]:
  351. lines.append("Tools: " + ", ".join(names[:12]) + (f" (+{len(names)-12})" if len(names) > 12 else ""))
  352. return _truncate_text("\n".join(lines), limit=8000)
  353. @_structured()
  354. def _format_session_search_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  355. if data.get("success") is False:
  356. return f"Session search failed: {data.get('error', 'unknown error')}"
  357. if not isinstance(results := data.get("results"), list):
  358. return None
  359. recent = (data.get("mode") or "search") == "recent"
  360. lines = ["Recent sessions" if recent else "Session search results" + _fmt(data.get("query"), " for `{}`", "")]
  361. if not results:
  362. lines.append(str(data.get("message") or "No matching sessions found."))
  363. return "\n".join(lines)
  364. for item in results:
  365. if not isinstance(item, dict):
  366. continue
  367. title = str(_first(item, "title", "when", default="Untitled session")).strip()
  368. when = str(_first(item, "last_active", "started_at", "when")).strip()
  369. count = item.get("message_count")
  370. meta = ", ".join(str(x) for x in [when, str(item.get("source") or "").strip(), f"{count} msgs" if count is not None else ""] if x)
  371. lines.append(f"- **{title}** (`{item.get('session_id') or '?'}`)" + (f" — {meta}" if meta else ""))
  372. if summary := str(item.get("summary") or item.get("preview") or "").strip():
  373. lines.append(" " + _truncate_text(" ".join(summary.split()), limit=500))
  374. return _truncate_text("\n".join(lines), limit=7000)
  375. @_structured()
  376. def _format_memory_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  377. action = _arg(args, "action", default="memory")
  378. target = str(data.get("target") or args.get("target") or "memory")
  379. if data.get("success") is False:
  380. lines = [f"✗ Memory {action} failed ({target})", str(data.get("error") or "unknown error")]
  381. if isinstance(matches := data.get("matches"), list) and matches:
  382. lines.extend(["Matches:", *(f"- {_truncate_text(str(m), 160)}" for m in matches[:5])])
  383. return "\n".join(lines)
  384. lines = [f"✅ Memory {action} saved ({target})"]
  385. if data.get("message"):
  386. lines.append(str(data.get("message")))
  387. if data.get("entry_count") is not None:
  388. lines.append(f"Entries: {data.get('entry_count')}")
  389. if data.get("usage"):
  390. lines.append(f"Usage: {data.get('usage')}")
  391. # Never dump all memory entries into the ACP UI; only preview the new value.
  392. if preview := _arg(args, "content", "old_text"):
  393. lines.append("Preview: " + _truncate_text(preview, limit=300))
  394. return "\n".join(lines)
  395. def _format_edit_result(tool_name: str, result: Optional[str], args: Optional[Args]) -> Optional[str]:
  396. data = _json_loads_maybe(result)
  397. path = str((args or {}).get("path") or "file").strip()
  398. done = f"✅ {tool_name} completed" + (f" for `{path}`" if path else "")
  399. if not isinstance(data, dict):
  400. return _truncate_text(text, limit=3000) if (text := _nonempty(result)) else done
  401. if failed := _failure(data, f"{tool_name} failed for {path}"):
  402. return failed
  403. lines = [done]
  404. if message := str(data.get("message") or "").strip():
  405. lines.append(message)
  406. if (replacements := data.get("replacements") or data.get("replacement_count")) is not None:
  407. lines.append(f"Replacements: {replacements}")
  408. if isinstance(files := data.get("files_modified"), list) and files:
  409. lines.append("Files: " + ", ".join(f"`{f}`" for f in files[:8]))
  410. return "\n".join(lines)
  411. @_structured(text_fallback=True)
  412. def _format_browser_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  413. if failed := _failure(data, f"{tool_name} failed"):
  414. return failed
  415. images = (data.get("images") or data.get("data")) if tool_name == "browser_get_images" else None
  416. if isinstance(images, list):
  417. lines = [f"Images found: {len(images)}"]
  418. for img in images[:12]:
  419. if isinstance(img, dict):
  420. url = str(img.get("url") or img.get("src") or "").strip()
  421. lines.append(f"- {str(img.get('alt') or '').strip() or 'image'}" + (f" — {url}" if url else ""))
  422. return _truncate_text("\n".join(lines), limit=5000)
  423. title = str(_first(data, "title", "url", "status", default=tool_name))
  424. lines = [title]
  425. if data.get("url") and data.get("url") != title:
  426. lines.append(str(data.get("url")))
  427. if text := str(_first(data, "text", "content", "snapshot", "analysis", "message")).strip():
  428. lines.extend(["", _truncate_text(text, limit=5000)])
  429. return _truncate_text("\n".join(lines), limit=7000)
  430. @_structured(text_fallback=True)
  431. def _format_media_or_cron_result(tool_name: str, data: Args, args: Args) -> Optional[str]:
  432. if failed := _failure(data, f"{tool_name} failed"):
  433. return failed
  434. keys = ("file_path", "path", "url", "image_url", "job_id", "id", "status", "message", "next_run")
  435. return "\n".join([f"✅ {tool_name} completed", *(f"- **{k}:** {data.get(k)}" for k in keys if data.get(k))])
  436. def _format_structured_value(key: str, value: Any, *, indent: int = 0, max_depth: int = 3, max_items: int = 8) -> list[str]:
  437. """Render nested JSON-ish values as compact Markdown bullets, not inline blobs."""
  438. pad = " " * indent
  439. bullet = f"{pad}- "
  440. label = f"**{key}:**" if key else ""
  441. def _line(text: str) -> str:
  442. return f"{bullet}{label} {text}" if label else f"{bullet}{text}"
  443. def _child(child_key: str, child_value: Any, extra_indent: int) -> list[str]:
  444. return _format_structured_value(child_key, child_value, indent=indent + extra_indent, max_depth=max_depth - 1,
  445. max_items=max_items)
  446. if value in _EMPTYISH:
  447. return []
  448. if max_depth <= 0:
  449. preview = json.dumps(value, ensure_ascii=False, default=str) if isinstance(value, (dict, list)) else str(value)
  450. return [_line(_truncate_text(preview, limit=240))]
  451. if isinstance(value, dict):
  452. lines = [f"{bullet}{label}" if label else f"{bullet}{len(value)} fields"]
  453. shown = 0
  454. for child_key, child_value in value.items():
  455. if child_value in _EMPTYISH:
  456. continue
  457. lines.extend(_child(str(child_key), child_value, 1))
  458. shown += 1
  459. if shown >= max_items:
  460. if len(value) > shown:
  461. lines.append(f"{pad} - ... {len(value) - shown} more fields")
  462. break
  463. return lines
  464. if isinstance(value, list):
  465. lines = [_line(_plural(len(value), "item"))]
  466. for idx, item in enumerate(value[:max_items], 1):
  467. if isinstance(item, dict):
  468. headline = str(_first(item, "content", "message", "title", "name", "id")).strip()
  469. if headline:
  470. lines.append(f"{pad} {idx}. {_truncate_text(headline, limit=220)}")
  471. for child_key in ("id", "status", "type", "scope", "quality_score", "score", "path", "url"):
  472. if item.get(child_key) not in _EMPTYISH:
  473. lines.append(f"{pad} - **{child_key}:** {_truncate_text(str(item[child_key]), limit=180)}")
  474. else:
  475. lines.append(f"{pad} {idx}.")
  476. for child_key, child_value in list(item.items())[:max_items]:
  477. lines.extend(_child(str(child_key), child_value, 2))
  478. elif isinstance(item, list):
  479. lines.append(f"{pad} {idx}. {len(item)} items")
  480. for nested in item[:max_items]:
  481. lines.extend(_child("", nested, 2))
  482. else:
  483. lines.append(f"{pad} {idx}. {_truncate_text(str(item), limit=240)}")
  484. if len(value) > max_items:
  485. lines.append(f"{pad} ... {len(value) - max_items} more items")
  486. return lines
  487. return [_line(_truncate_text(str(value), limit=500))]
  488. _PRIORITY_KEYS = (
  489. "message", "status", "id", "task_id", "issue_id", "title", "name", "entity_id",
  490. "state", "service", "url", "path", "file_path", "count", "total", "next_run",
  491. )
  492. def _format_generic_structured_result(tool_name: str, result: Optional[str], *, fallback_to_text: bool = True) -> Optional[str]:
  493. data = _json_loads_maybe(result)
  494. if not isinstance(data, (dict, list)):
  495. return _nonempty(result) if fallback_to_text else None
  496. if isinstance(data, list):
  497. lines = [f"{tool_name}: {_plural(len(data), 'item')}"]
  498. for item in data[:12]:
  499. if isinstance(item, (dict, list)):
  500. lines.extend(_format_structured_value("", item, indent=0, max_depth=2, max_items=6))
  501. else:
  502. lines.append(f"- {_truncate_text(str(item), limit=240)}")
  503. return _truncate_text("\n".join(lines + _more(data, 12, " items")), limit=5000)
  504. if failed := _failure(data, f"{tool_name} failed"):
  505. return failed
  506. lines = [f"✅ {tool_name} completed" if data.get("success") is True else f"{tool_name} result"]
  507. seen = {key for key in _PRIORITY_KEYS if data.get(key) not in _EMPTYISH}
  508. lines.extend(f"- **{key}:** {_truncate_text(str(data[key]), limit=500)}" for key in _PRIORITY_KEYS if key in seen)
  509. for key, value in data.items():
  510. if key in seen or key in {"success", "raw", "content", "entries"} or value in _EMPTYISH:
  511. continue
  512. lines.extend(_format_structured_value(str(key), value, indent=0, max_depth=3, max_items=8))
  513. if len(lines) >= 40:
  514. lines.append("- ... more fields truncated")
  515. break
  516. if isinstance(content := data.get("content"), str) and content.strip():
  517. lines.extend(["", _truncate_text(content.strip(), limit=1500)])
  518. return _truncate_text("\n".join(lines), limit=7000)
  519. _COMPLETION_FORMATTERS: dict[str, _Formatter] = {
  520. "todo": _format_todo_result,
  521. "read_file": _format_read_file_result,
  522. "write_file": _format_edit_result,
  523. "patch": _format_edit_result,
  524. "search_files": _format_search_files_result,
  525. "execute_code": _format_execute_code_result,
  526. "process": _format_process_result,
  527. "delegate_task": _format_delegate_result,
  528. "session_search": _format_session_search_result,
  529. "memory": _format_memory_result,
  530. "skill_view": _format_skill_view_result,
  531. "skill_manage": _format_skill_manage_result,
  532. "web_search": _format_web_search_result,
  533. **{n: _format_browser_result for n in ("browser_navigate", "browser_snapshot", "browser_vision", "browser_get_images")},
  534. **{n: _format_media_or_cron_result for n in ("vision_analyze", "image_generate", "cronjob")},
  535. }
  536. def _parse_unified_diff_content(diff_text: str) -> list[Any]:
  537. """Convert unified diff text into ACP diff content blocks (one per ``---``/``+++`` pair)."""
  538. content: list[Any] = []
  539. state: dict[str, Any] = {"old": None, "new": None, "old_lines": [], "new_lines": []}
  540. def _flush() -> None:
  541. old_path, new_path = state["old"], state["new"]
  542. path = new_path if new_path and new_path != "/dev/null" else old_path
  543. if path and path != "/dev/null":
  544. path = str(path).strip()
  545. content.append(acp.tool_diff_content(
  546. path=path[2:] if path.startswith(("a/", "b/")) else path,
  547. old_text="\n".join(state["old_lines"]) if state["old_lines"] else None,
  548. new_text="\n".join(state["new_lines"]),
  549. ))
  550. state.update(old=None, new=None, old_lines=[], new_lines=[])
  551. for line in diff_text.splitlines():
  552. if line.startswith("--- "):
  553. _flush()
  554. state["old"] = line[4:].strip()
  555. elif line.startswith("+++ "):
  556. state["new"] = line[4:].strip()
  557. elif line.startswith("@@") or (state["old"] is None and state["new"] is None):
  558. continue
  559. elif line.startswith("+"):
  560. state["new_lines"].append(line[1:])
  561. elif line.startswith("-"):
  562. state["old_lines"].append(line[1:])
  563. elif line.startswith(" "):
  564. state["old_lines"].append(line[1:])
  565. state["new_lines"].append(line[1:])
  566. _flush()
  567. return content
  568. def _build_tool_complete_content(
  569. tool_name: str, result: Optional[str], *, function_args: Optional[Args] = None, snapshot: Any = None
  570. ) -> list[Any]:
  571. """Build structured ACP completion content, falling back to plain text."""
  572. if tool_name == "skill_manage":
  573. try:
  574. from agent.display import extract_edit_diff
  575. diff_text = extract_edit_diff(tool_name, result, function_args=function_args, snapshot=snapshot)
  576. if isinstance(diff_text, str) and diff_text.strip():
  577. diff_content = _parse_unified_diff_content(diff_text)
  578. if diff_content:
  579. return diff_content
  580. except Exception:
  581. pass
  582. if (formatter := _COMPLETION_FORMATTERS.get(tool_name)) is not None:
  583. text = formatter(tool_name, result, function_args)
  584. else:
  585. text = _format_generic_structured_result(tool_name, result, fallback_to_text=tool_name in _POLISHED_TOOLS)
  586. return [_text(text)] if text else [_text(_truncate_text(result or ""))]
  587. # --- ToolCallStart / ToolCallProgress events ---------------------------------
  588. def _more(items: list, shown: int, unit: str = "") -> list[str]:
  589. """``["... N more<unit>"]`` trailer when ``items`` overflowed the ``shown`` cap, else ``[]``."""
  590. return [f"... {len(items) - shown} more{unit}"] if len(items) > shown else []
  591. def _start_todo(args: Args) -> str:
  592. if not isinstance(items := args.get("todos"), list):
  593. return "Reading todo list"
  594. lines = ["Updating todo list", ""]
  595. lines.extend(f"- {i.get('status', 'pending')}: {i.get('content', i.get('id', ''))}" for i in items[:8] if isinstance(i, dict))
  596. return "\n".join(lines + _more(items, 8))
  597. def _start_skill_manage(args: Args) -> Any:
  598. action = _arg(args, "action", default="manage")
  599. name = _arg(args, "name", default="?")
  600. file_path = _arg(args, "file_path", default="SKILL.md")
  601. path = f"skills/{name}/{file_path}"
  602. if action == "patch":
  603. old = str(args.get("old_string") or "")
  604. return acp.tool_diff_content(path=path, old_text=old or None, new_text=str(args.get("new_string") or ""))
  605. if action in {"edit", "create"}:
  606. return acp.tool_diff_content(path=path, new_text=str(args.get("content") or ""))
  607. if action == "write_file":
  608. target = str(args.get("file_path") or "file")
  609. return acp.tool_diff_content(path=f"skills/{name}/{target}", new_text=str(args.get("file_content") or ""))
  610. if action in {"delete", "remove_file"}:
  611. return f"Removing {args.get('file_path') or file_path!s} from skill '{name}'"
  612. return f"Running skill_manage action '{action}' on skill '{name}' ({file_path})"
  613. def _start_execute_code(args: Args) -> str:
  614. code = _arg(args, "code")
  615. preview = code[:1200] + (f"\n... ({len(code)} chars total, truncated)" if len(code) > 1200 else "")
  616. return _fmt(preview, "Running Python helper script:\n\n```python\n{}\n```", "Running Python helper script")
  617. def _start_delegate(args: Args) -> str:
  618. if not (isinstance(tasks := args.get("tasks"), list) and tasks):
  619. return "Delegating task" + _fmt(_truncate_text(_arg(args, "goal"), limit=800), ":\n{}", "")
  620. lines = [f"Delegating {len(tasks)} tasks", ""]
  621. for i, task in enumerate(tasks[:8], 1):
  622. if isinstance(task, dict):
  623. lines.append(f"{i}. " + _truncate_text(_arg(task, "goal"), limit=160) + _fmt(_arg(task, "role"), " ({})", ""))
  624. return "\n".join(lines + _more(tasks, 8))
  625. def _preview(label: str, value: str, limit: int) -> str:
  626. return f"\n{label}: {_truncate_text(value, limit=limit)}" if value else ""
  627. # Per-tool start-content builders returning text or one ACP content block. ``None`` means the
  628. # title/location already identify the target (read_file, web_extract): a synthetic content block
  629. # would make Zed render an unhelpful Output section before completion.
  630. _START_CONTENT_BUILDERS: dict[str, Optional[Callable[[Args], Any]]] = {
  631. "patch": lambda a: (
  632. f"Preparing {a.get('mode', 'replace')} edit for {a.get('path') or 'patch input'}. Approval prompt shows the diff."
  633. ),
  634. "write_file": lambda a: _fmt(a.get("path", ""), "Preparing write to {}. Approval prompt shows the diff.",
  635. "Preparing file write. Approval prompt shows the diff."),
  636. "terminal": lambda a: f"$ {a.get('command', '')}",
  637. "read_file": None,
  638. "search_files": lambda a: (
  639. f"Searching for '{a.get('pattern', '')}' ({a.get('target', 'content')})" + _fmt(a.get("path"), " in {}", "")
  640. ),
  641. "todo": _start_todo,
  642. "skill_view": lambda a: f"Loading skill '{_arg(a, 'name', default='?')}' ({_arg(a, 'file_path', default='SKILL.md')})",
  643. "skill_manage": _start_skill_manage,
  644. "execute_code": _start_execute_code,
  645. "web_search": lambda a: _fmt(_arg(a, "query"), "Searching the web for: {}", "Searching the web"),
  646. "web_extract": None,
  647. "process": lambda a: f"Process action: {_arg(a, 'action', default='manage')}" + _fmt(_arg(a, "session_id"), "\nSession: {}", "")
  648. + _preview("Input", _arg(a, "data"), 500),
  649. "delegate_task": _start_delegate,
  650. "session_search": lambda a: _fmt(_arg(a, "query"), "Searching past sessions for: {}", "Loading recent sessions"),
  651. "memory": lambda a: f"Memory {_arg(a, 'action', default='manage')} ({_arg(a, 'target', default='memory')})"
  652. + _preview("Preview", _arg(a, "content", "old_text"), 500),
  653. }
  654. def build_tool_start(tool_call_id: str, tool_name: str, arguments: Args, *, edit_diff: Any = None) -> ToolCallStart:
  655. """Create a ToolCallStart event for the given hermes tool invocation.
  656. A malformed argument (e.g. a non-string ``command``/``path`` from a model
  657. ignoring the schema) must never abort the render — this runs on the live
  658. tool-progress callback and during history replay — so any failure in the
  659. title/content/location builders falls back to a minimal valid start event
  660. (mirrors ``get_cute_tool_message`` in ``agent/display.py``)."""
  661. try:
  662. return _build_tool_start(tool_call_id, tool_name, arguments, edit_diff=edit_diff)
  663. except Exception as exc:
  664. logger.debug("ACP tool-start render failed for %r: %s", tool_name, exc)
  665. safe_name = tool_name if isinstance(tool_name, str) and tool_name else "tool"
  666. return acp.start_tool_call(tool_call_id, safe_name, kind=get_tool_kind(safe_name), content=None, locations=[])
  667. def _build_tool_start(tool_call_id: str, tool_name: str, arguments: Args, *, edit_diff: Any = None) -> ToolCallStart:
  668. """Build the ToolCallStart event (unguarded; see ``build_tool_start``)."""
  669. raw_input = None
  670. if tool_name in ("patch", "write_file") and edit_diff is not None:
  671. content = [acp.tool_diff_content(path=edit_diff.path, old_text=edit_diff.old_text, new_text=edit_diff.new_text)]
  672. elif tool_name in _START_CONTENT_BUILDERS:
  673. built = builder(arguments) if (builder := _START_CONTENT_BUILDERS[tool_name]) is not None else None
  674. content = None if built is None else [_text(built) if isinstance(built, str) else built]
  675. elif tool_name in _POLISHED_TOOLS:
  676. content = [_text(_truncate_text(_args_json(arguments), limit=1200))]
  677. elif not arguments:
  678. content = None
  679. else: # unknown tool with arguments: echo them as content and raw_input
  680. content = [_text(_args_json(arguments))]
  681. raw_input = arguments
  682. return acp.start_tool_call(
  683. tool_call_id, build_tool_title(tool_name, arguments), kind=get_tool_kind(tool_name),
  684. content=content, locations=extract_locations(arguments), raw_input=raw_input,
  685. )
  686. def build_tool_complete(
  687. tool_call_id: str, tool_name: str, result: Optional[str] = None, function_args: Optional[Args] = None,
  688. snapshot: Any = None, is_error: bool = False,
  689. ) -> ToolCallProgress:
  690. """Create a ToolCallUpdate (progress) event for a completed tool call.
  691. ``is_error`` is the executor's own verdict; the result-text heuristic stays as fallback."""
  692. if tool_name == "web_extract": # errors only; success stays compact via the title
  693. error_text = _format_web_extract_result(tool_name, result, function_args)
  694. content = [_text(error_text)] if error_text else None
  695. else:
  696. content = _build_tool_complete_content(tool_name, result, function_args=function_args, snapshot=snapshot)
  697. structured = isinstance(_json_loads_maybe(result), (dict, list))
  698. return acp.update_tool_call(
  699. tool_call_id, kind=get_tool_kind(tool_name),
  700. status="failed" if is_error or _tool_result_failed(result, tool_name) else "completed", content=content,
  701. raw_output=None if tool_name in _POLISHED_TOOLS or structured else result,
  702. )
  703. def build_tool_abandoned(tool_call_id: str, tool_name: str) -> ToolCallProgress:
  704. """Create a ToolCallUpdate for a call that ended without ever reporting a result.
  705. A blocked or permission-denied call projects no ``tool.completed``, so the
  706. turn ends with its bubble still spinning; ``failed`` is the honest terminal
  707. state — the tool did not produce a result."""
  708. return acp.update_tool_call(
  709. tool_call_id, kind=get_tool_kind(tool_name), status="failed",
  710. content=[_text("This tool call ended without a result (blocked, denied, or interrupted).")],
  711. )
  712. def extract_locations(arguments: Args) -> list[ToolCallLocation]:
  713. """Extract file-system locations from tool arguments."""
  714. if not (path := arguments.get("path")):
  715. return []
  716. return [ToolCallLocation(path=path, line=arguments.get("offset") or arguments.get("line"))]