display.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. """CLI presentation -- spinner, kawaii faces, tool preview formatting.
  2. Pure display functions with no AIAgent dependency; used for CLI feedback.
  3. """
  4. import logging
  5. import os
  6. import re
  7. import sys
  8. import threading
  9. import time
  10. from dataclasses import dataclass, field, replace
  11. from difflib import unified_diff
  12. from pathlib import Path
  13. from typing import Any, Iterator
  14. from urllib.parse import urlsplit
  15. from utils import safe_json_loads
  16. from agent.i18n import t
  17. from agent.redact import redact_sensitive_text, sanitize_command_for_display
  18. from agent.tool_result_classification import (
  19. shape_failure_error, file_mutation_result_landed, has_failure_marker, is_guardrail_refusal)
  20. logger = logging.getLogger(__name__)
  21. _ANSI_RESET = "\033[0m"
  22. _MAX_INLINE_DIFF_FILES = 6
  23. _MAX_INLINE_DIFF_LINES = 80
  24. def _display_url(value: Any) -> str:
  25. """Extract a display-only URL without assuming model argument types."""
  26. value = (value.get("url") or value.get("href")) if isinstance(value, dict) else value
  27. return value.strip() if isinstance(value, str) else ""
  28. def _http_url(candidate: str) -> str | None:
  29. """``candidate`` when it parses as an absolute http(s) URL, else None."""
  30. try:
  31. parsed = urlsplit(candidate)
  32. except ValueError:
  33. return None
  34. return candidate if parsed.scheme.lower() in {"http", "https"} and parsed.netloc else None
  35. def _hex_rgb(h: str) -> tuple[int, int, int]:
  36. return int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16)
  37. def _get_skin():
  38. """Active skin config, or None when unavailable (lazy import avoids cycles)."""
  39. try:
  40. from hermes_cli.skin_engine import get_active_skin
  41. return get_active_skin()
  42. except Exception:
  43. return None
  44. # Diff colors resolve lazily from the skin engine (light/dark aware) and are
  45. # cached after the first resolution.
  46. _diff_colors_cached: dict[str, str] | None = None
  47. # Foreground diff colors: key -> (skin color key, dark-terminal fallback RGB).
  48. _DIFF_FG = {
  49. "dim": ("banner_dim", (150, 150, 150)), "file": ("session_label", (180, 160, 255)),
  50. "hunk": ("session_border", (120, 120, 140)),
  51. }
  52. # Background diff colors (white text on a dark tint of the skin's ui_error/ui_ok):
  53. # key -> (skin key, default hex, dominant channel index, dark-terminal fallback).
  54. _DIFF_BG = {
  55. "minus": ("ui_error", "#ef5350", 0, "\033[38;2;255;255;255;48;2;120;20;20m"),
  56. "plus": ("ui_ok", "#4caf50", 1, "\033[38;2;255;255;255;48;2;20;90;20m"),
  57. }
  58. def _fg(r: int, g: int, b: int) -> str:
  59. return f"\033[38;2;{r};{g};{b}m"
  60. def _tinted_bg(rgb: tuple[int, int, int], dominant: int) -> str:
  61. r, g, b = (max(v // 2, 20) if i == dominant else max(v // 4, 10) for i, v in enumerate(rgb))
  62. return f"\033[38;2;255;255;255;48;2;{r};{g};{b}m"
  63. def _diff_ansi() -> dict[str, str]:
  64. """Return ANSI escapes for diff display, resolved from the active skin."""
  65. global _diff_colors_cached
  66. if _diff_colors_cached is not None:
  67. return _diff_colors_cached
  68. colors = {k: _fg(*rgb) for k, (_, rgb) in _DIFF_FG.items()} | {k: v[3] for k, v in _DIFF_BG.items()}
  69. try:
  70. skin = _get_skin()
  71. for key, (skin_key, fallback) in _DIFF_FG.items():
  72. h = skin.get_color(skin_key, "")
  73. colors[key] = _fg(*(_hex_rgb(h) if h and len(h) == 7 and h[0] == "#" else fallback))
  74. bg_hex = {key: skin.get_color(skin_key, default) for key, (skin_key, default, _, _) in _DIFF_BG.items()}
  75. for key, (_, _, dominant, _) in _DIFF_BG.items():
  76. h = bg_hex[key]
  77. if h and len(h) == 7:
  78. colors[key] = _tinted_bg(_hex_rgb(h), dominant)
  79. except Exception:
  80. pass
  81. _diff_colors_cached = colors
  82. return colors
  83. @dataclass
  84. class LocalEditSnapshot:
  85. """Pre-tool filesystem snapshot used to render diffs locally after writes."""
  86. paths: list[Path] = field(default_factory=list)
  87. before: dict[str, str | None] = field(default_factory=dict)
  88. # Configurable tool preview length; set once at startup from display.tool_preview_length.
  89. _tool_preview_max_len: int = 0 # 0 = unlimited
  90. _friendly_tool_labels: bool = True
  91. def set_tool_preview_max_len(n: int) -> None:
  92. """Set the global max length for tool call previews. 0 = no limit."""
  93. global _tool_preview_max_len
  94. _tool_preview_max_len = max(int(n), 0) if n else 0
  95. def get_tool_preview_max_len() -> int:
  96. """Return the configured max preview length (0 = unlimited)."""
  97. return _tool_preview_max_len
  98. _JSON_ESCAPE_RE = re.compile(r"\\(.)")
  99. def verbose_tool_args_text(args: dict, max_len: int, code_block: bool) -> str:
  100. """Verbose tool-progress args: compact JSON (capped at ``max_len``; 0 = no cap). On markdown
  101. platforms it goes in a code block so the formatter keeps it verbatim (``**x**``/``a_b`` are
  102. otherwise rendered as markup), with JSON's ``\\n``/``\\t`` shown as real line breaks. Args
  103. holding ``` stay plain: Slack and Discord end a code block at any ``` inside it."""
  104. import json
  105. text = json.dumps(args, ensure_ascii=False, default=str)
  106. if max_len > 0 and len(text) > max_len:
  107. text = text[:max_len - 3] + "..."
  108. if not code_block or "```" in text:
  109. return text
  110. decoded = _JSON_ESCAPE_RE.sub(lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(0)), text)
  111. return f"```\n{decoded}\n```"
  112. def set_friendly_tool_labels(enabled: bool) -> None:
  113. """Toggle friendly human-phrased tool labels (display.friendly_tool_labels)."""
  114. global _friendly_tool_labels
  115. _friendly_tool_labels = bool(enabled)
  116. def get_skin_tool_prefix() -> str:
  117. """Get tool output prefix character from active skin."""
  118. skin = _get_skin()
  119. return skin.tool_prefix if skin else "┊"
  120. def get_tool_emoji(tool_name: str, default: str = "⚡") -> str:
  121. """Display emoji for a tool: skin ``tool_emojis`` override, then registry, then *default*."""
  122. skin = _get_skin()
  123. override = skin.tool_emojis.get(tool_name) if skin and skin.tool_emojis else None
  124. if override:
  125. return override
  126. try:
  127. from tools.registry import registry
  128. return registry.get_emoji(tool_name, default="") or default
  129. except Exception:
  130. return default
  131. # ── Tool preview (one-line summary of a tool call's primary argument) ─────
  132. def _oneline(text: str) -> str:
  133. """Collapse whitespace (including newlines) to single spaces."""
  134. return " ".join(text.split())
  135. def _tail_trunc(text: str, limit: int | None) -> str:
  136. """Tail-truncate to ``limit`` chars with ``...`` (0/None = unlimited). The result never
  137. exceeds ``limit``: for 1-3 the ellipsis itself is clipped (``text[:limit - 3]`` would go
  138. negative and hand back almost the whole string, #9439)."""
  139. if not limit or limit <= 0 or len(text) <= limit:
  140. return text
  141. return "." * limit if limit <= 3 else text[:limit - 3] + "..."
  142. def _clip(text: str, n: int) -> str:
  143. """``text[:n]`` plus ``...`` when longer (used inside quoted previews)."""
  144. return f"{text[:n]}{'...' if len(text) > n else ''}"
  145. @dataclass(frozen=True)
  146. class ToolPreview:
  147. """A compact tool preview plus presentation facts lost to truncation."""
  148. text: str
  149. truncated: bool = False
  150. url: str | None = None
  151. # ── Shell command summarisation ──────────────────────────────────────────
  152. _SHELL_SILENT_HEADS = {"cd", "pushd", "popd", "export", "set", "unset", "source", ".", "true", "false", ":"}
  153. _SHELL_PIPE_TAIL_HEADS = {"head", "tail", "wc", "sort", "uniq"}
  154. def _shell_basename(head: str) -> str:
  155. return head.rsplit("/", 1)[-1] if head else ""
  156. def _scan_quoted(text: str) -> Iterator[tuple[int, str, bool]]:
  157. """Yield ``(index, char, inside_quotes)``; a quote closes unless backslash-escaped."""
  158. quote: str | None = None
  159. for i, ch in enumerate(text):
  160. if quote:
  161. yield i, ch, True
  162. if ch == quote and (i == 0 or text[i - 1] != "\\"):
  163. quote = None
  164. elif ch in {"'", '"'}:
  165. quote = ch
  166. yield i, ch, True
  167. else:
  168. yield i, ch, False
  169. def _split_shell_words(segment: str) -> list[str]:
  170. parts: list[list[str]] = [[]]
  171. for _, ch, quoted in _scan_quoted(segment):
  172. if not quoted and ch.isspace():
  173. parts.append([])
  174. else:
  175. parts[-1].append(ch)
  176. return ["".join(p) for p in parts if p]
  177. def _strip_shell_pipe_tail(segment: str) -> str:
  178. """Drop a trailing ``| head/tail/wc/sort/uniq ...`` pipeline stage."""
  179. words = _split_shell_words(segment)
  180. for i, word in enumerate(words):
  181. if word == "|" and _shell_basename(words[i + 1] if i + 1 < len(words) else "") in _SHELL_PIPE_TAIL_HEADS:
  182. words = words[:i]
  183. break
  184. return " ".join(words).strip()
  185. def _split_shell_compound(command: str) -> list[str]:
  186. """Split on unquoted ``&&`` / ``||`` / ``;`` / newline, dropping pipe tails per segment."""
  187. raw: list[list[str]] = [[]]
  188. skip = False
  189. for i, ch, quoted in _scan_quoted(command):
  190. if skip:
  191. skip = False
  192. elif not quoted and (command.startswith("&&", i) or command.startswith("||", i)):
  193. raw.append([])
  194. skip = True
  195. elif not quoted and ch in {";", "\n"}:
  196. raw.append([])
  197. else:
  198. raw[-1].append(ch)
  199. segments = (_strip_shell_pipe_tail("".join(buf).strip()) for buf in raw)
  200. return [s for s in segments if s]
  201. def _shell_head_word(segment: str) -> str:
  202. """Command name of a segment, skipping leading ``VAR=value`` assignments."""
  203. words = _split_shell_words(segment)
  204. while words and re.match(r"^[A-Za-z_]\w*=", words[0]):
  205. words.pop(0)
  206. return _shell_basename(words[0] if words else "")
  207. def _clean_shell_segment(segment: str) -> str:
  208. """Drop redirections (``> file``, ``2>&1``) from a segment."""
  209. words = _split_shell_words(segment)
  210. out: list[str] = []
  211. i = 0
  212. while i < len(words):
  213. word = words[i]
  214. if re.match(r"^\d*(?:>>?|<)$", word):
  215. i += 2 # operator + target
  216. elif re.match(r"^\d*(?:>&|<&)\d+$", word):
  217. i += 1
  218. else:
  219. out.append(word)
  220. i += 1
  221. return " ".join(out).strip()
  222. def _is_shell_boundary_echo(segment: str) -> bool:
  223. words = _split_shell_words(segment)
  224. if _shell_basename(words[0] if words else "") != "echo":
  225. return False
  226. return bool(re.search(r"-{2,}|_exit=|(?:^|\s|=)\$[?{]|PIPESTATUS", " ".join(words[1:])))
  227. def summarize_shell_command(command: str) -> str:
  228. """Compact shell wrapper/plumbing for display while preserving raw command elsewhere."""
  229. original = _oneline(command)
  230. if not original:
  231. return ""
  232. segments = _split_shell_compound(original)
  233. if len(segments) <= 1:
  234. return _clean_shell_segment(segments[0] if segments else original) or original
  235. core: list[str] = []
  236. for segment in segments:
  237. cleaned = _clean_shell_segment(segment)
  238. if cleaned and _shell_head_word(cleaned) not in _SHELL_SILENT_HEADS and not _is_shell_boundary_echo(cleaned):
  239. core.append(cleaned)
  240. if not core:
  241. return original
  242. count = len(core) - 1
  243. if not count:
  244. return core[0]
  245. return t("display.preview.shell_plus_one" if count == 1 else "display.preview.shell_plus_many", first=core[0], count=count)
  246. def _read_file_line_label(args: dict) -> str:
  247. offset, limit = args.get("offset"), args.get("limit")
  248. if not isinstance(offset, int) or offset <= 0:
  249. return ""
  250. return f"L{offset}-{offset + limit - 1}" if isinstance(limit, int) and limit > 1 else f"L{offset}"
  251. def redact_tool_args_for_display(tool_name: str, args: dict | None) -> dict | None:
  252. """Return a copy of tool args safe for logs/progress UI (masks ``browser_type`` secrets)."""
  253. if not isinstance(args, dict):
  254. return args
  255. if tool_name == "browser_type" and isinstance(args.get("text"), str):
  256. return {**args, "text": redact_sensitive_text(args["text"], force=True)}
  257. return args
  258. def _delegate_task_goals(tasks: Any, *, per_goal_len: int) -> list[str]:
  259. """One truncated goal string per dict task (``?`` when missing)."""
  260. if not isinstance(tasks, list):
  261. return []
  262. raw_goals = (task.get("goal") for task in tasks if isinstance(task, dict))
  263. return [_tail_trunc(("?" if g is None else _oneline(str(g))) or "?", per_goal_len) for g in raw_goals]
  264. def _browser_exec_step_label(args: dict, max_chars: int = 80) -> str | None:
  265. """User-friendly step label from browser_exec code's leading comment."""
  266. first = str(args.get("code", "") or "").strip().split("\n", 1)[0].strip()
  267. label = first.lstrip("#").strip() if first.startswith("#") else ""
  268. if not label:
  269. return None
  270. return label[: max_chars - 1] + "…" if len(label) > max_chars else label
  271. _PRIMARY_ARGS = {
  272. "terminal": "command", "web_search": "query", "web_extract": "urls", "read_file": "path",
  273. "write_file": "path", "patch": "path", "search_files": "pattern", "browser_navigate": "url",
  274. "browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text",
  275. "vision_analyze": "question", "skill_view": "name", "skills_list": "category", "cronjob_manage": "action",
  276. "execute_code": "code", "browser_exec": "code", "delegate_task": "goal",
  277. "skill_manage": "name",
  278. }
  279. _FALLBACK_PREVIEW_KEYS = ("query", "text", "command", "path", "name", "prompt", "code", "goal")
  280. def _delegate_action_preview(args: dict) -> str | None:
  281. """Shared ``list/steer/stop <id>`` preview for delegate_task, or None for spawn calls."""
  282. action = str(args.get("action") or "").strip().lower()
  283. if action in ("list", "steer", "stop"):
  284. return f"{action} {str(args.get('subagent_id') or '').strip()}".strip()
  285. return None
  286. def _preview_browser_exec(args: dict, max_len: int) -> str | None:
  287. label = _browser_exec_step_label(args)
  288. if label is not None:
  289. return _tail_trunc(label, max_len)
  290. return _tail_trunc(_oneline(str(args.get("code", "") or "")), max_len) or None
  291. def _preview_delegate_task(args: dict, max_len: int) -> str | None:
  292. action_preview = _delegate_action_preview(args)
  293. tasks = args.get("tasks")
  294. if action_preview is not None:
  295. return _tail_trunc(action_preview, max_len)
  296. if tasks and isinstance(tasks, list):
  297. goals = _delegate_task_goals(tasks, per_goal_len=40)
  298. preview = (t("display.preview.delegate_tasks", count=len(goals), goals=" | ".join(goals)) if goals
  299. else t("display.preview.delegate_parallel_tasks", count=len(tasks)))
  300. return _tail_trunc(preview, max_len)
  301. goal = args.get("goal", "")
  302. return None if goal is None else _tail_trunc(_oneline(str(goal)), max_len) or None
  303. def _preview_process_manage(args: dict, _max_len: int) -> str | None:
  304. action, sid, data, timeout_val = (args.get(k) for k in ("action", "session_id", "data", "timeout"))
  305. parts = [str(action) if action else "", str(sid)[:16] if sid else "",
  306. f'"{_oneline(str(data)[:20])}"' if data else "", f"{timeout_val}s" if timeout_val and action == "wait" else ""]
  307. return " ".join(p for p in parts if p) or None
  308. def _preview_todo_list(args: dict, _max_len: int) -> str:
  309. todos_arg = args.get("todos")
  310. verb = t("display.preview.todo_verb_updating" if args.get("merge", False) else "display.preview.todo_verb_planning")
  311. return t("display.preview.todo_reading") if todos_arg is None else t("display.preview.todo_tasks", verb=verb, count=len(todos_arg))
  312. def _preview_shell(key: str):
  313. def _build(args: dict, max_len: int) -> str | None:
  314. command = args.get(key)
  315. # Sanitize before summarizing: the spinner sits under the approval prompt and must not hide what it does.
  316. return None if command is None else _tail_trunc(
  317. summarize_shell_command(sanitize_command_for_display(str(command))), max_len) or None
  318. return _build
  319. def _preview_read_file(args: dict, max_len: int) -> str | None:
  320. path = args.get("path") or args.get("file") or args.get("filepath")
  321. label = (Path(str(path).replace("\\", "/")).name or str(path)) if path is not None else None
  322. return None if label is None else _tail_trunc(f"{label} {_read_file_line_label(args)}".strip(), max_len) or None
  323. def _memory_first_op(args: dict) -> tuple[dict, str]:
  324. """The op a memory progress line shows and a ``" (N more)"`` suffix for the rest of an
  325. ``operations[]`` batch (the advertised shape); legacy top-level single-op args are their own op."""
  326. ops = args.get("operations")
  327. if not isinstance(ops, list) or not ops:
  328. return args, ""
  329. first = ops[0] if isinstance(ops[0], dict) else {}
  330. return first, (f" ({t('cli.shared.n_more', count=len(ops) - 1)})" if len(ops) > 1 else "")
  331. def _preview_memory(args: dict, _max_len: int) -> str:
  332. op, more = _memory_first_op(args)
  333. action, target = op.get("action", ""), args.get("target", "")
  334. if action == "add":
  335. return f"+{target}: \"{_clip(_oneline(op.get('content') or op.get('new_text') or ''), 25)}\"{more}"
  336. if action in ("replace", "patch", "remove"):
  337. old = _oneline(op.get("old_text") or "") or t("display.preview.missing_old_text")
  338. return f"{'-' if action == 'remove' else '~'}{target}: \"{old[:20]}\"{more}"
  339. return action
  340. def _preview_send_message(args: dict, _max_len: int) -> str:
  341. return t("display.preview.send_message_to", target=args.get("target", "?"),
  342. message=_tail_trunc(_oneline(args.get("message", "")), 20))
  343. def _preview_skill_view(args: dict, max_len: int) -> str | None:
  344. name = _oneline(str(args.get("name") or ""))
  345. file_path = args.get("file_path")
  346. label = (f"{name} → {_oneline(str(file_path))}" if name else _oneline(str(file_path))) if file_path else name
  347. return _tail_trunc(label, max_len) or None
  348. def _preview_clarify(args: dict, max_len: int) -> str | None:
  349. questions = args.get("questions")
  350. first = questions[0] if isinstance(questions, list) and questions else None
  351. if not isinstance(first, dict):
  352. return None
  353. return _tail_trunc(_oneline(str(first.get("question") or "")), max_len) or None
  354. def _preview_bridge_call(tool_name: str):
  355. def _build(args: dict, max_len: int) -> str | None:
  356. labels = bridge_tool_labels(tool_name, args)
  357. if not labels:
  358. return _primary_arg_preview(tool_name, args, max_len)
  359. extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
  360. return _tail_trunc(f"{labels[0].text}{extra}", max_len) or None
  361. return _build
  362. # Tool-specific preview builders: f(args, max_len) -> preview. Tools not listed
  363. # fall through to the primary-argument lookup in build_tool_preview.
  364. _PREVIEW_BUILDERS = {
  365. "browser_exec": _preview_browser_exec, "delegate_task": _preview_delegate_task,
  366. "process_manage": _preview_process_manage, "todo_list": _preview_todo_list,
  367. "terminal": _preview_shell("command"), "execute_code": _preview_shell("code"),
  368. "read_file": _preview_read_file, "memory": _preview_memory, "send_message": _preview_send_message,
  369. "skill_view": _preview_skill_view, "clarify": _preview_clarify,
  370. "session_search": lambda args, _m: t("display.preview.session_search_recall", query=_clip(_oneline(args.get("query", "")), 25)),
  371. "tool_call": _preview_bridge_call("tool_call"),
  372. "tool_search": _preview_bridge_call("tool_search"),
  373. "tool_describe": _preview_bridge_call("tool_describe"),
  374. }
  375. def build_tool_preview(tool_name: str, args: dict, max_len: int | None = None) -> str | None:
  376. """Build a short preview of a tool call's primary argument for display.
  377. *max_len* ``None`` defers to the global ``_tool_preview_max_len``; ``0`` means unlimited.
  378. """
  379. if max_len is None:
  380. max_len = _tool_preview_max_len
  381. if not args:
  382. return None
  383. args = redact_tool_args_for_display(tool_name, args) or args
  384. builder = _PREVIEW_BUILDERS.get(tool_name)
  385. if builder is not None:
  386. return builder(args, max_len)
  387. return _primary_arg_preview(tool_name, args, max_len)
  388. def _primary_arg_preview(tool_name: str, args: dict, max_len: int) -> str | None:
  389. key = _PRIMARY_ARGS.get(tool_name) or next((k for k in _FALLBACK_PREVIEW_KEYS if k in args), None)
  390. if not key or key not in args:
  391. return None
  392. value = args[key]
  393. preview = _oneline(str((value[0] if value else "") if isinstance(value, list) else value))
  394. return _tail_trunc(preview, max_len) if preview else None
  395. def prepare_tool_preview(tool_name: str, args: dict | None, *, fallback: str, max_len: int) -> ToolPreview:
  396. """Compact preview plus explicit truncation/URL facts (the uncapped preview is
  397. rebuilt from the arguments so an upstream display cap cannot drop its link target)."""
  398. full_text = build_tool_preview(tool_name, args, max_len=0) or fallback
  399. text = _tail_trunc(full_text, max_len)
  400. truncated = text != full_text
  401. url = _http_url(_display_url(full_text)) if truncated else None
  402. return ToolPreview(text=text, truncated=truncated, url=url)
  403. # ── Friendly tool labels: "web_search <q>" -> "Searching the web for <q>" ──
  404. # Curated built-ins only — we know each core tool's semantics so the verb is fixed,
  405. # not computed; custom/plugin/MCP tools have no entry and fall back to the raw preview.
  406. # Tools with a curated verb; the text itself lives in the catalog (``display.verb.<tool>``) and is
  407. # resolved at call time by ``get_tool_verb`` so a ``display.language`` change applies immediately.
  408. _TOOL_VERB_TOOLS: frozenset[str] = frozenset({
  409. "web_search", "web_extract", "browser_navigate", "browser_click", "browser_type",
  410. "read_file", "write_file", "patch", "search_files", "terminal", "execute_code",
  411. "image_generate", "video_generate", "text_to_speech", "vision_analyze", "session_search",
  412. "skill_view", "skills_list", "skill_manage", "delegate_task", "cronjob_manage", "clarify",
  413. "memory", "todo_list",
  414. })
  415. def _tool_verb(tool_name: str) -> str | None:
  416. return t(f"display.verb.{tool_name}") if tool_name in _TOOL_VERB_TOOLS else None
  417. # Verbs that read better without the argument preview appended.
  418. _TOOL_VERBS_NO_PREVIEW: frozenset[str] = frozenset({"skills_list", "session_search"})
  419. # Verbs joined to the preview with " for " (search-style phrasing).
  420. _TOOL_VERBS_FOR_CONNECTOR: frozenset[str] = frozenset({"web_search", "search_files"})
  421. _BRIDGE_GENERATING_TOOLS: frozenset[str] = frozenset({"tool_call", "tool_search", "tool_describe"})
  422. def bridge_generating_phrase(tool_name: str) -> str | None:
  423. if not _friendly_tool_labels or tool_name not in _BRIDGE_GENERATING_TOOLS:
  424. return None
  425. return t(f"display.bridge_generating.{tool_name}")
  426. def tool_labels_for_call(tool_name: str, args: dict | None) -> list:
  427. try:
  428. from tools.tool_labels import labels_for_call
  429. labels = labels_for_call(tool_name, args or {})
  430. except Exception as exc:
  431. logger.debug("bridge labels failed for %s: %s", tool_name, exc)
  432. return []
  433. skin = _get_skin()
  434. overrides = (skin.tool_emojis if skin and skin.tool_emojis else None) or {}
  435. return [replace(label, emoji=overrides[label.name]) if label.name in overrides else label
  436. for label in labels]
  437. def bridge_tool_labels(tool_name: str, args: dict | None) -> list:
  438. return tool_labels_for_call(tool_name, args) if _friendly_tool_labels else []
  439. def tool_row_emoji(tool_name: str, args: dict | None = None, default: str = "⚡") -> str:
  440. labels = bridge_tool_labels(tool_name, args) if args else []
  441. return labels[0].emoji if labels else get_tool_emoji(tool_name, default)
  442. def get_tool_verb(tool_name: str) -> str | None:
  443. """Friendly verb for a built-in tool, or None (labels disabled / no curated verb);
  444. callers compose ``f"{verb}{tool_verb_connector(tool)}{preview}"`` themselves."""
  445. return _tool_verb(tool_name) if _friendly_tool_labels else None
  446. def tool_verb_connector(tool_name: str) -> str:
  447. """Return the connector between a verb and its preview (" for " or " ")."""
  448. return t("display.verb_connector.search" if tool_name in _TOOL_VERBS_FOR_CONNECTOR else "display.verb_connector.default")
  449. def verb_drops_preview(tool_name: str) -> bool:
  450. """Whether the verb should render alone, without the argument preview."""
  451. return tool_name in _TOOL_VERBS_NO_PREVIEW
  452. def build_status_phrase(tool_name: str, args: dict | None, max_len: int = 49) -> str | None:
  453. """Lowercase "is <verb> <preview>…" phrase following the bot's display name (Slack setStatus).
  454. ``args=None`` gives a verb-only phrase (``display.live_status: verb`` keeps previews out
  455. of shared channels). None for ``_thinking`` or disabled labels so callers use their
  456. static default. Default ``max_len`` stays under Slack's ~50-char status truncation.
  457. """
  458. if not tool_name or tool_name == "_thinking" or not _friendly_tool_labels:
  459. return None
  460. verb = _tool_verb(tool_name)
  461. phrase = (t("display.status_phrase.verb", verb=f"{verb[0].lower()}{verb[1:]}") if verb
  462. else t("display.status_phrase.using_tool", tool=tool_name))
  463. with_preview = args and verb and tool_name not in _TOOL_VERBS_NO_PREVIEW
  464. preview = build_tool_preview(tool_name, args, max_len=None) if with_preview else None
  465. if preview: # previews can contain newlines (terminal commands); keep the first line
  466. phrase = f"{phrase}{tool_verb_connector(tool_name)}{preview.splitlines()[0].strip()}"
  467. return phrase[: max_len - 2].rstrip() + "…" if len(phrase) > max_len - 1 else phrase + "…"
  468. def build_tool_label(tool_name: str, args: dict, max_len: int | None = None) -> str | None:
  469. labels = bridge_tool_labels(tool_name, args)
  470. if labels:
  471. label = labels[0]
  472. preview = _tail_trunc(label.preview, max_len if max_len is not None else _tool_preview_max_len)
  473. extra = f" +{len(labels) - 1}" if len(labels) > 1 else ""
  474. return f"{label.text}{f' {preview}' if preview else ''}{extra}"
  475. verb = get_tool_verb(tool_name)
  476. if verb and tool_name in _TOOL_VERBS_NO_PREVIEW:
  477. return verb
  478. preview = build_tool_preview(tool_name, args, max_len=max_len)
  479. if not verb:
  480. return preview
  481. return f"{verb}{tool_verb_connector(tool_name)}{preview}" if preview else verb
  482. # ── Inline diff previews for write actions ────────────────────────────────
  483. def _resolved_path(path: str) -> Path:
  484. """Resolve a possibly-relative filesystem path against the current cwd."""
  485. return Path.cwd() / Path(os.path.expanduser(path)) # a `/` with an absolute rhs keeps the rhs
  486. def _snapshot_text(path: Path) -> str | None:
  487. """Return UTF-8 file content, or None for missing/unreadable files."""
  488. try:
  489. return path.read_text(encoding="utf-8-sig")
  490. except (FileNotFoundError, IsADirectoryError, UnicodeDecodeError, OSError):
  491. return None
  492. def _display_diff_path(path: Path) -> str:
  493. """Prefer cwd-relative paths in diffs when available."""
  494. try:
  495. return str(path.resolve().relative_to(Path.cwd().resolve()))
  496. except Exception:
  497. return str(path)
  498. def _resolve_skill_manage_paths(args: dict) -> list[Path]:
  499. """Resolve skill_manage write targets to filesystem paths."""
  500. action = args.get("action")
  501. name = args.get("name")
  502. if not action or not name:
  503. return []
  504. from tools.skill_manager_tool import _find_skill, _resolve_skill_dir
  505. if action == "create":
  506. return [_resolve_skill_dir(name, args.get("category")) / "SKILL.md"]
  507. existing = _find_skill(name)
  508. if not existing:
  509. return []
  510. skill_dir = Path(existing["path"])
  511. file_path = args.get("file_path")
  512. if action == "delete":
  513. return [path for path in sorted(skill_dir.rglob("*")) if path.is_file()]
  514. if file_path and action in {"edit", "patch", "write_file", "remove_file"}:
  515. return [skill_dir / file_path]
  516. return [skill_dir / "SKILL.md"] if action in {"edit", "patch"} else []
  517. def _resolve_local_edit_paths(tool_name: str, function_args: dict | None, task_id: str | None = None) -> list[Path]:
  518. """Resolve local filesystem targets for write-capable tools."""
  519. if not isinstance(function_args, dict):
  520. return []
  521. if tool_name == "skill_manage":
  522. return _resolve_skill_manage_paths(function_args)
  523. path = function_args.get("path") if tool_name in {"write_file", "patch"} else None
  524. if path and task_id is not None:
  525. from tools.file_tools_paths import _resolve_path_for_task, _terminal_env_type_for_task
  526. # A remote target may happen to exist on this host too. Never persist a
  527. # preview of that unrelated file; patch can still supply its own diff.
  528. if _terminal_env_type_for_task(task_id) != "local":
  529. return []
  530. return [Path(_resolve_path_for_task(path, task_id))]
  531. return [_resolved_path(path)] if path else []
  532. def capture_local_edit_snapshot(
  533. tool_name: str, function_args: dict | None, *, task_id: str | None = None,
  534. ) -> LocalEditSnapshot | None:
  535. """Capture before-state for local write previews."""
  536. paths = _resolve_local_edit_paths(tool_name, function_args, task_id)
  537. if not paths:
  538. return None
  539. return LocalEditSnapshot(paths=paths, before={str(path): _snapshot_text(path) for path in paths})
  540. def _result_succeeded(result: str | None) -> bool:
  541. """Conservatively detect whether a tool result represents success."""
  542. data = safe_json_loads(result) if result else None
  543. if not isinstance(data, dict) or data.get("error"):
  544. return False
  545. return bool(data.get("success")) if "success" in data else True
  546. def _diff_from_snapshot(snapshot: LocalEditSnapshot | None) -> str | None:
  547. """Generate unified diff text from a stored before-state and current files."""
  548. if not snapshot:
  549. return None
  550. chunks: list[str] = []
  551. for path in snapshot.paths:
  552. before, after = snapshot.before.get(str(path)), _snapshot_text(path)
  553. if before == after:
  554. continue
  555. display_path = _display_diff_path(path)
  556. diff = "".join(unified_diff(
  557. (before or "").splitlines(keepends=True), (after or "").splitlines(keepends=True),
  558. fromfile=f"a/{display_path}", tofile=f"b/{display_path}",
  559. ))
  560. if diff:
  561. chunks.append(diff if diff.endswith("\n") else diff + "\n")
  562. return "".join(chunks) or None
  563. def extract_edit_diff(
  564. tool_name: str, result: str | None, *,
  565. function_args: dict | None = None, snapshot: LocalEditSnapshot | None = None,
  566. ) -> str | None:
  567. """Extract a unified diff from a file-edit tool result."""
  568. if tool_name == "patch" and result:
  569. data = safe_json_loads(result)
  570. diff = data.get("diff") if isinstance(data, dict) else None
  571. if isinstance(diff, str) and diff.strip():
  572. return diff
  573. if tool_name not in {"write_file", "patch", "skill_manage"} or not _result_succeeded(result):
  574. return None
  575. return _diff_from_snapshot(snapshot)
  576. def _emit_inline_diff(diff_text: str, print_fn) -> bool:
  577. """Emit rendered diff text through the CLI's prompt_toolkit-safe printer."""
  578. if print_fn is None or not diff_text:
  579. return False
  580. try:
  581. for line in [t("display.diff.review_header"), *diff_text.rstrip("\n").splitlines()]:
  582. print_fn(line)
  583. return True
  584. except Exception:
  585. return False
  586. # Unified-diff line prefix -> diff color key (checked in order; "--- "/"+++ " handled first).
  587. _DIFF_LINE_COLORS = (("@@", "hunk"), ("-", "minus"), ("+", "plus"), (" ", "dim"))
  588. def _render_inline_unified_diff(diff: str) -> list[str]:
  589. """Render unified diff lines in Hermes' inline transcript style."""
  590. rendered: list[str] = []
  591. from_file = to_file = None
  592. for raw_line in diff.splitlines():
  593. if raw_line.startswith("--- "):
  594. from_file = raw_line[4:].strip()
  595. continue
  596. if raw_line.startswith("+++ "):
  597. to_file = raw_line[4:].strip()
  598. if from_file or to_file:
  599. rendered.append(f"{_diff_ansi()['file']}{from_file or 'a/?'} → {to_file or 'b/?'}{_ANSI_RESET}")
  600. continue
  601. color = next((c for prefix, c in _DIFF_LINE_COLORS if raw_line.startswith(prefix)), None)
  602. if color:
  603. rendered.append(f"{_diff_ansi()[color]}{raw_line}{_ANSI_RESET}")
  604. elif raw_line:
  605. rendered.append(raw_line)
  606. return rendered
  607. def _split_unified_diff_sections(diff: str) -> list[str]:
  608. """Split a unified diff into per-file sections."""
  609. sections: list[list[str]] = [[]]
  610. for line in diff.splitlines():
  611. if line.startswith("--- ") and sections[-1]:
  612. sections.append([])
  613. sections[-1].append(line)
  614. return ["\n".join(section) for section in sections if section]
  615. def _summarize_rendered_diff_sections(
  616. diff: str, *, max_files: int = _MAX_INLINE_DIFF_FILES, max_lines: int = _MAX_INLINE_DIFF_LINES,
  617. ) -> list[str]:
  618. """Render diff sections while capping file count and total line count."""
  619. sections = _split_unified_diff_sections(diff)
  620. rendered: list[str] = []
  621. omitted_files = omitted_lines = 0
  622. for idx, section in enumerate(sections):
  623. section_lines = _render_inline_unified_diff(section)
  624. remaining_budget = max_lines - len(rendered)
  625. if idx >= max_files or remaining_budget <= 0:
  626. omitted_files += 1
  627. omitted_lines += len(section_lines)
  628. continue
  629. if len(section_lines) <= remaining_budget:
  630. rendered.extend(section_lines)
  631. continue
  632. rendered.extend(section_lines[:remaining_budget])
  633. omitted_lines += len(section_lines) - remaining_budget
  634. omitted_files += 1 + max(0, len(sections) - idx - 1)
  635. for leftover in sections[idx + 1:]:
  636. omitted_lines += len(_render_inline_unified_diff(leftover))
  637. break
  638. if omitted_files or omitted_lines:
  639. summary = t("display.diff.omitted_lines", count=omitted_lines)
  640. if omitted_files:
  641. summary += t("display.diff.omitted_files", count=omitted_files)
  642. rendered.append(f"{_diff_ansi()['hunk']}{summary}{_ANSI_RESET}")
  643. return rendered
  644. def render_edit_diff_with_delta(
  645. tool_name: str, result: str | None, *,
  646. function_args: dict | None = None, snapshot: LocalEditSnapshot | None = None, print_fn=None,
  647. ) -> bool:
  648. """Render an edit diff inline without taking over the terminal UI."""
  649. diff = extract_edit_diff(tool_name, result, function_args=function_args, snapshot=snapshot)
  650. if not diff:
  651. return False
  652. try:
  653. rendered_lines = _summarize_rendered_diff_sections(diff)
  654. except Exception as exc:
  655. logger.debug("Could not render inline diff: %s", exc)
  656. return False
  657. return _emit_inline_diff("\n".join(rendered_lines), print_fn)
  658. # ── KawaiiSpinner ─────────────────────────────────────────────────────────
  659. class KawaiiSpinner:
  660. """Animated spinner with kawaii faces for CLI feedback during tool execution."""
  661. SPINNERS = {
  662. 'dots': list('⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'), 'bounce': list('⠁⠂⠄⡀⢀⠠⠐⠈'), 'grow': list('▁▂▃▄▅▆▇█▇▆▅▄▃▂'),
  663. 'arrows': list('←↖↑↗→↘↓↙'), 'star': list('✶✷✸✹✺✹✸✷'), 'moon': list('🌑🌒🌓🌔🌕🌖🌗🌘'),
  664. 'pulse': list('◜◠◝◞◡◟'), 'brain': list('🧠💭💡✨💫🌟💡💭'), 'sparkle': list('⁺˚*✧✦✧*˚'),
  665. }
  666. KAWAII_WAITING = [
  667. "(。◕‿◕。)", "(◕‿◕✿)", "٩(◕‿◕。)۶", "(✿◠‿◠)", "( ˘▽˘)っ", "♪(´ε` )", "(◕ᴗ◕✿)", "ヾ(^∇^)", "(≧◡≦)", "(★ω★)",
  668. ]
  669. KAWAII_THINKING = [
  670. "(。•́︿•̀。)", "(◔_◔)", "(¬‿¬)", "( •_•)>⌐■-■", "(⌐■_■)", "(´・_・`)", "◉_◉", "(°ロ°)", "( ˘⌣˘)♡", "ヽ(>∀<☆)☆",
  671. "٩(๑❛ᴗ❛๑)۶", "(⊙_⊙)", "(¬_¬)", "( ͡° ͜ʖ ͡°)", "ಠ_ಠ",
  672. ]
  673. # English fallback; ``get_thinking_verbs`` prefers the skin list, then the catalog
  674. # (``display.thinking_verbs``, comma-separated) for the active language.
  675. THINKING_VERBS = [
  676. "pondering", "contemplating", "musing", "cogitating", "ruminating", "deliberating", "mulling",
  677. "reflecting", "processing", "reasoning", "analyzing", "computing", "synthesizing", "formulating",
  678. "brainstorming",
  679. ]
  680. @staticmethod
  681. def _skin_spinner_list(key: str, fallback: list) -> list:
  682. """Return the active skin's ``spinner[key]`` list, or *fallback* when absent/empty."""
  683. try:
  684. skin = _get_skin()
  685. return (skin.spinner.get(key, []) if skin else None) or fallback
  686. except Exception:
  687. return fallback
  688. get_waiting_faces = classmethod(lambda cls: cls._skin_spinner_list("waiting_faces", cls.KAWAII_WAITING))
  689. get_thinking_faces = classmethod(lambda cls: cls._skin_spinner_list("thinking_faces", cls.KAWAII_THINKING))
  690. @classmethod
  691. def _catalog_thinking_verbs(cls) -> list[str]:
  692. verbs = [v.strip() for v in t("display.thinking_verbs").split(",") if v.strip()]
  693. return verbs if verbs and verbs != ["display.thinking_verbs"] else cls.THINKING_VERBS
  694. get_thinking_verbs = classmethod(lambda cls: cls._skin_spinner_list("thinking_verbs", cls._catalog_thinking_verbs()))
  695. def __init__(self, message: str = "", spinner_type: str = 'dots', print_fn=None):
  696. self.message = message
  697. self.spinner_frames = self.SPINNERS.get(spinner_type, self.SPINNERS['dots'])
  698. self.running = False
  699. self.thread = self.start_time = None
  700. self.frame_idx = self.last_line_len = 0
  701. self._print_fn = print_fn # when set, bypasses self._out so silenced agents stay silent
  702. self._out = sys.stdout # captured NOW, before any child redirect_stdout(devnull) replaces it
  703. def _write(self, text: str, end: str = '\n', flush: bool = False):
  704. """Write via print_fn when supplied, else to the stdout captured at creation."""
  705. if self._print_fn is not None:
  706. try:
  707. self._print_fn(text)
  708. except Exception:
  709. pass
  710. return
  711. try:
  712. self._out.write(text + end)
  713. if flush:
  714. self._out.flush()
  715. except (ValueError, OSError):
  716. pass
  717. @property
  718. def _is_tty(self) -> bool:
  719. """Check if output is a real terminal, safe against closed streams."""
  720. try:
  721. return hasattr(self._out, 'isatty') and self._out.isatty()
  722. except (ValueError, OSError):
  723. return False
  724. def _is_patch_stdout_proxy(self) -> bool:
  725. """True for prompt_toolkit's StdoutProxy: it injects newlines around each flush so the
  726. \\r overwrite never lands, and the CLI drives its own TUI spinner widget in that mode."""
  727. try:
  728. from prompt_toolkit.patch_stdout import StdoutProxy
  729. return isinstance(self._out, StdoutProxy)
  730. except ImportError:
  731. return False
  732. def _animate(self):
  733. tty = self._is_tty
  734. # Non-TTY (Docker, systemd, pipe): log once instead of spamming frames.
  735. if not tty:
  736. self._write(t("display.spinner.tool_line", message=self.message), flush=True)
  737. # Under patch_stdout the \r animation would overdraw the TUI status bar.
  738. if not tty or self._is_patch_stdout_proxy():
  739. while self.running:
  740. time.sleep(0.5 if not tty else 0.1)
  741. return
  742. skin = _get_skin()
  743. wings = skin.get_spinner_wings() if skin else []
  744. while self.running:
  745. if os.getenv("HERMES_SPINNER_PAUSE"):
  746. time.sleep(0.1)
  747. continue
  748. frame = self.spinner_frames[self.frame_idx % len(self.spinner_frames)]
  749. elapsed = f"({time.time() - self.start_time:.1f}s)"
  750. left, right = wings[self.frame_idx % len(wings)] if wings else ("", "")
  751. line = f" {left} {frame} {self.message} {right} {elapsed}" if wings else f" {frame} {self.message} {elapsed}"
  752. self._write(f"\r{line}{' ' * max(self.last_line_len - len(line), 0)}", end='', flush=True)
  753. self.last_line_len = len(line)
  754. self.frame_idx += 1
  755. time.sleep(0.12)
  756. def start(self):
  757. if self.running:
  758. return
  759. self.running, self.start_time = True, time.time()
  760. self.thread = threading.Thread(target=self._animate, daemon=True)
  761. self.thread.start()
  762. def update_text(self, new_message: str):
  763. self.message = new_message
  764. def _clear_line_blanks(self) -> str:
  765. return ' ' * max(self.last_line_len + 5, 40) # spaces, not \033[K: garbles under patch_stdout
  766. def print_above(self, text: str):
  767. """Print a line above the spinner (next tick redraws it below). Works inside
  768. redirect_stdout(devnull) because _write targets the stdout captured at creation."""
  769. self._write(f"\r{self._clear_line_blanks()}\r {text}" if self.running else f" {text}", flush=True)
  770. def stop(self, final_message: str | None = None):
  771. self.running = False
  772. if self.thread:
  773. self.thread.join(timeout=0.5)
  774. is_tty = self._is_tty
  775. if is_tty:
  776. self._write(f"\r{self._clear_line_blanks()}\r", end='', flush=True)
  777. if final_message:
  778. elapsed = f" ({time.time() - self.start_time:.1f}s)" if self.start_time else ""
  779. self._write(f" {final_message}" if is_tty else t("display.spinner.done_line", message=final_message, elapsed=elapsed), flush=True)
  780. def __enter__(self):
  781. self.start()
  782. return self
  783. def __exit__(self, *exc):
  784. self.stop()
  785. return False
  786. # ── Cute tool message (completion line that replaces the spinner) ─────────
  787. _ERROR_SUFFIX_MAX_LEN = 48
  788. # A degraded backend (Docker down, SSH host unreachable) needs the whole reason plus the fix hint.
  789. _DEGRADED_SUFFIX_MAX_LEN = 200
  790. def _trim_error(msg: str) -> str:
  791. """Shrink an error message for inline display (long 'File not found' paths -> filename)."""
  792. msg = msg.strip()
  793. if "File not found:" in msg:
  794. tail = msg.partition("File not found:")[2].strip()
  795. if "/" in tail:
  796. msg = t("display.failure.file_not_found", name=tail.rsplit("/", 1)[-1])
  797. return _tail_trunc(msg, _ERROR_SUFFIX_MAX_LEN)
  798. def _degraded_suffix(data: dict) -> str:
  799. """`` [<reason> — <retry_hint>]`` for a ``status: degraded`` terminal result (hint omitted when empty)."""
  800. reason = str(data.get("reason") or data.get("error") or t("display.failure.terminal_backend_unavailable")).strip()
  801. hint = str(data.get("retry_hint") or "").strip()
  802. text = f"{reason} — {hint}" if hint else reason
  803. return f" [{_tail_trunc(text, _DEGRADED_SUFFIX_MAX_LEN)}]"
  804. # Tools whose refused calls are the agent's own retry loop, not something the user must act on: a
  805. # skill_manage write refused by the size cap, a stale old_string or a guard is re-planned by the
  806. # agent. Renderers show these rows neutrally; the failure still reaches the model and the loop
  807. # guardrail unchanged (display-only).
  808. NEUTRAL_FAILURE_TOOLS = frozenset({"skill_manage"})
  809. # Except a batch whose rollback failed (tools/skill_manager_batch.py::_rollback): partial changes
  810. # are left on disk, which the user does have to see.
  811. _UNSAFE_FAILURE_MARKER = "ROLLBACK FAILED"
  812. def is_neutral_failure(tool_name: str, result: Any) -> bool:
  813. """True when a failed call of ``tool_name`` should render neutrally (see NEUTRAL_FAILURE_TOOLS)."""
  814. if tool_name not in NEUTRAL_FAILURE_TOOLS:
  815. return False
  816. # Only the error text: a refused patch also returns a file_preview of the skill, whose own
  817. # prose may mention the marker.
  818. data = result if isinstance(result, dict) else safe_json_loads(result)
  819. error = data.get("error") if isinstance(data, dict) else result
  820. return _UNSAFE_FAILURE_MARKER not in str(error or "")
  821. def _detect_tool_failure(tool_name: str, result: Any) -> tuple[bool, str]:
  822. """Return ``(is_failure, suffix)`` for a tool result, e.g. ``(True, " [exit 1]")``."""
  823. if result is None or file_mutation_result_landed(tool_name, result):
  824. return False, ""
  825. data = result if isinstance(result, dict) else safe_json_loads(result)
  826. # A harness REFUSAL of a redundant call (repeated identical read/search) is not a
  827. # failed call. This is the ``failed`` the executor hands the loop guardrail, so
  828. # counting it would escalate refusals into ``repeated_exact_failure_block``.
  829. if is_guardrail_refusal(data):
  830. return False, ""
  831. # A denied/timed-out approval carries one human sentence; show it instead of the model-facing
  832. # "BLOCKED: ... Do NOT retry" text (which stays in the JSON for the model).
  833. if isinstance(data, dict) and data.get("user_summary"):
  834. return True, f" [{_tail_trunc(str(data['user_summary']), _DEGRADED_SUFFIX_MAX_LEN)}]"
  835. # Terminal: non-zero exit code is the canonical failure signal.
  836. if tool_name == "terminal":
  837. exit_code = data.get("exit_code") if isinstance(data, dict) else None
  838. if exit_code is None or exit_code == 0:
  839. return False, ""
  840. if data.get("status") == "degraded":
  841. return True, _degraded_suffix(data)
  842. err_msg = data.get("error")
  843. return True, f" [{_trim_error(str(err_msg))}]" if err_msg else t("display.failure.exit_code", code=exit_code)
  844. if isinstance(data, dict):
  845. failed = data.get("success") is False
  846. # Memory: distinguish "store full" from real errors.
  847. if tool_name == "memory" and failed and "exceed the limit" in data.get("error", ""):
  848. return True, t("display.failure.memory_full")
  849. err = data.get("error") or data.get("message")
  850. if err and (failed or "error" in data):
  851. return True, f" [{_trim_error(str(err))}]"
  852. if shape_err := shape_failure_error(data):
  853. return True, f" [{_trim_error(shape_err)}]"
  854. # A JSON object is judged by its top-level shape only. An ``error`` key nested
  855. # inside a success payload is data the tool read (a page's own validation
  856. # message inside browser_cdp's ``result``), not a failure of the call.
  857. return False, ""
  858. # Multimodal results (dicts) are successes; failures arrive as JSON-encoded strings.
  859. if isinstance(result, str) and has_failure_marker(result):
  860. return True, t("display.failure.generic")
  861. return False, ""
  862. def _domain(url: str) -> str:
  863. return url.replace("https://", "").replace("http://", "").split("/")[0]
  864. def _cute_trunc(s) -> str:
  865. """Tail-truncate to the configured preview cap (0 = unlimited)."""
  866. return _tail_trunc(str(s), _tool_preview_max_len)
  867. def _cute_path(p) -> str:
  868. """Head-truncate a path to the configured preview cap, keeping the filename end."""
  869. p = str(p)
  870. limit = _tool_preview_max_len
  871. if not limit or len(p) <= limit:
  872. return p
  873. return "." * limit if limit <= 3 else "..." + p[-(limit - 3):]
  874. class _CuteRow(str):
  875. """A rendered completion row that also keeps its emoji, verb and detail, so the CLI's glyph
  876. layout can rebuild the row without re-parsing the padded ``┊ emoji verb`` string."""
  877. emoji: str
  878. verb: str
  879. detail: str
  880. def __new__(cls, text: str, emoji: str, verb: str, detail: str):
  881. row = super().__new__(cls, text)
  882. row.emoji, row.verb, row.detail = emoji.strip(), verb, detail
  883. return row
  884. def __reduce__(self): # copy/pickle as a plain str; the custom __new__ can't be re-called bare
  885. return (str, (str(self),))
  886. def _cute_row(emoji: str, verb: str, detail: str = "") -> str:
  887. """``┊ {emoji} {verb:9} {detail}`` -- verb column from ``display.cute.verb.<verb>`` (9 cells wide)."""
  888. label = t(f'display.cute.verb.{verb}')
  889. return _CuteRow(f"┊ {emoji} {label:9} {detail}", emoji, label, detail)
  890. def _cute_fallback_row(tool_name: str, args: dict) -> _CuteRow:
  891. """The row for a tool with no dedicated renderer: its registered (or skin) emoji, its name, and
  892. its preview. One source for both layouts, so their icons can't drift."""
  893. detail = _cute_trunc(build_tool_preview(tool_name, args) or "")
  894. emoji = get_tool_emoji(tool_name)
  895. return _CuteRow(f"┊ {emoji} {tool_name[:9]:9} {detail}", emoji, tool_name, detail)
  896. def get_tool_row_parts(tool_name: str, args: dict | None, result: str | None = None, *, is_error: bool = False):
  897. """``[(emoji, verb, detail, failure), ...]`` for one completed call: the parts the ``┊`` line
  898. uses, without its padding. ``failure`` is None for a row that succeeded, else that row's
  899. suffix (``" [exit 1]"``, possibly ``""``); batch calls mark the entry that failed."""
  900. try:
  901. args = redact_tool_args_for_display(tool_name, args) or args or {}
  902. is_failure, suffix = _detect_tool_failure(tool_name, result)
  903. call_failure = suffix if is_failure else ("" if is_error else None)
  904. labels = bridge_tool_labels(tool_name, args)
  905. if labels:
  906. suffixes = _bridge_row_suffixes(len(labels), result, suffix if is_failure else "")
  907. marks = [s or None for s in suffixes]
  908. if call_failure is not None and not any(suffixes):
  909. marks[-1] = call_failure # the call failed without naming an entry
  910. return [(lb.emoji, _cute_trunc(lb.text), _cute_trunc(lb.preview) if lb.preview else "", mark)
  911. for lb, mark in zip(labels, marks)]
  912. render = _CUTE_LINES.get(tool_name)
  913. row = render(args, result) if render else None
  914. row = row if isinstance(row, _CuteRow) else _cute_fallback_row(tool_name, args)
  915. return [(row.emoji, row.verb, row.detail, call_failure)]
  916. except Exception:
  917. logger.debug("Tool row parts failed for %s", tool_name, exc_info=True)
  918. return [("⚡", str(tool_name), "", None)]
  919. def _cute_web_extract(a: dict, _r) -> str:
  920. urls = a.get("urls", [])
  921. url = _display_url(urls[0] if isinstance(urls, list) else urls) if urls else ""
  922. if not url:
  923. return _cute_row("📄", "fetch", t("display.cute.fetch_pages"))
  924. extra = f" +{len(urls)-1}" if isinstance(urls, list) and len(urls) > 1 else ""
  925. return _cute_row("📄", "fetch", f"{_cute_trunc(_domain(url))}{extra}")
  926. def _cute_todo_list(a: dict, result) -> str:
  927. todos_arg = a.get("todos")
  928. total = done = 0
  929. try:
  930. summary = (safe_json_loads(result) or {}).get("summary", {}) if result else {}
  931. total, done = summary.get("total", 0), summary.get("completed", 0)
  932. except Exception:
  933. pass
  934. progress = t("display.cute.todo_progress", done=done, total=total)
  935. if todos_arg is None:
  936. detail = progress if total > 0 else t("display.cute.todo_reading")
  937. elif a.get("merge", False):
  938. detail = (t("display.cute.todo_update_progress", done=done, total=total) if total > 0 and done > 0
  939. else t("display.cute.todo_update_count", count=len(todos_arg)))
  940. else:
  941. detail = progress if total > 0 and done > 0 else t("display.cute.todo_count", count=len(todos_arg))
  942. return _cute_row("📋", "plan", detail)
  943. def _cute_memory(a: dict, _r) -> str:
  944. op, more = _memory_first_op(a)
  945. action, target = op.get("action", "?"), a.get("target", "")
  946. if action == "add":
  947. content = op.get("content") or op.get("new_text") or ""
  948. return _cute_row("🧠", "memory", f"+{target}: \"{_cute_trunc(content)}\"{more}")
  949. if action in ("replace", "patch", "remove"):
  950. old = op.get("old_text") or t("display.preview.missing_old_text")
  951. return _cute_row("🧠", "memory", f"{'-' if action == 'remove' else '~'}{target}: \"{_cute_trunc(old)}\"{more}")
  952. return _cute_row("🧠", "memory", str(action))
  953. def _cute_skill_view(a: dict, _r) -> str:
  954. label, file_path = a.get("name", ""), a.get("file_path")
  955. label = (f"{label} → {file_path}" if label else str(file_path)) if file_path else label
  956. return _cute_row("📚", "skill", _cute_trunc(label))
  957. def _cute_cronjob(a: dict, _r) -> str:
  958. action = a.get("action", "?")
  959. if action == "create":
  960. skills = a.get("skills") or ([a.get("skill")] if a.get("skill") else [])
  961. label = a.get("name") or (skills[0] if skills else None) or a.get("prompt", t("display.cute.cron_task_fallback"))
  962. return _cute_row("⏰", "cron", t("display.cute.cron_create", label=_cute_trunc(label)))
  963. if action == "list":
  964. return _cute_row("⏰", "cron", t("display.cute.cron_listing"))
  965. return _cute_row("⏰", "cron", f"{action} {a.get('job_id', '')}")
  966. def _cute_execute_code(a: dict, _r) -> str:
  967. code = a.get("code", "").strip()
  968. return _cute_row("🐍", "exec", _cute_trunc(code.split(chr(10))[0] if code else ""))
  969. def _cute_browser_exec(a: dict, _r) -> str:
  970. # Leading `# …` comment becomes the step label; code stays collapsed behind the preview cap.
  971. label = _browser_exec_step_label(a)
  972. return _cute_row("🌐", "browser", _cute_trunc(_oneline(str(a.get("code", "") or ""))) if label is None else label)
  973. def _cute_delegate(a: dict, _r) -> str:
  974. action_preview = _delegate_action_preview(a)
  975. tasks = a.get("tasks")
  976. if action_preview is not None:
  977. return _cute_row("🔀", "delegate", _cute_trunc(action_preview))
  978. if tasks and isinstance(tasks, list):
  979. goals = _delegate_task_goals(tasks, per_goal_len=30)
  980. joined = _cute_trunc(" | ".join(goals) if goals else t("display.cute.delegate_parallel"))
  981. return _cute_row("🔀", "delegate", f"{len(goals) or len(tasks)}x: {joined}")
  982. return _cute_row("🔀", "delegate", _cute_trunc(a.get("goal", "")))
  983. def _cute_process_manage(a: dict, _r) -> str:
  984. action, sid = a.get("action", "?"), a.get("session_id", "")[:12]
  985. return _cute_row("⚙️ ", "proc", t("display.cute.process_list") if action == "list" else f"{action} {sid}")
  986. _SCROLL_ARROWS = {"down": "↓", "up": "↑", "right": "→", "left": "←"}
  987. def _cute_scroll(a: dict, _r) -> str:
  988. direction = a.get("direction", "down")
  989. label = t(f"display.cute.scroll.{direction}") if direction in _SCROLL_ARROWS else str(direction)
  990. return _cute_row(f"{_SCROLL_ARROWS.get(direction, '↓')} ", "scroll", label)
  991. # Completion-line renderers: tool -> f(args, result) -> "┊ {emoji} {verb:9} {detail}" (duration appended by caller).
  992. _CUTE_LINES = {
  993. "web_search": lambda a, r: _cute_row("🔍", "search", _cute_trunc(a.get("query", ""))),
  994. "web_extract": _cute_web_extract,
  995. "terminal": lambda a, r: _cute_row("💻", "terminal", _cute_trunc(build_tool_preview("terminal", a) or a.get("command", ""))),
  996. "process_manage": _cute_process_manage,
  997. "read_file": lambda a, r: _cute_row("📖", "read", _cute_trunc(build_tool_preview("read_file", a) or a.get("path", ""))),
  998. "write_file": lambda a, r: _cute_row("✍️ ", "write", _cute_path(a.get("path", ""))),
  999. "patch": lambda a, r: _cute_row("🔧", "patch", _cute_path(a.get("path", ""))),
  1000. "search_files": lambda a, r: _cute_row("🔎", "find" if a.get("target", "content") == "files" else "grep", _cute_trunc(a.get("pattern", ""))),
  1001. "browser_navigate": lambda a, r: _cute_row("🌐", "navigate", _cute_trunc(_domain(a.get("url", "")))),
  1002. "browser_snapshot": lambda a, r: _cute_row("📸", "snapshot", t("display.cute.snapshot_full" if a.get("full") else "display.cute.snapshot_compact")),
  1003. "browser_click": lambda a, r: _cute_row("👆", "click", str(a.get("ref", "?"))),
  1004. "browser_type": lambda a, r: _cute_row("⌨️ ", "type", f"\"{_cute_trunc(a.get('text', ''))}\""),
  1005. "browser_scroll": _cute_scroll,
  1006. "browser_back": lambda a, r: _cute_row("◀️ ", "back"),
  1007. "browser_press": lambda a, r: _cute_row("⌨️ ", "press", str(a.get("key", "?"))),
  1008. "browser_get_images": lambda a, r: _cute_row("🖼️ ", "images", t("display.cute.images_extracting")),
  1009. "browser_vision": lambda a, r: _cute_row("👁️ ", "vision", t("display.cute.vision_analyzing_page")),
  1010. "todo_list": _cute_todo_list,
  1011. "session_search": lambda a, r: _cute_row("🔍", "recall", f"\"{_cute_trunc(a.get('query', ''))}\""),
  1012. "memory": _cute_memory,
  1013. "skills_list": lambda a, r: _cute_row("📚", "skills", t("display.cute.skills_list", category=a.get("category") or t("display.cute.skills_all"))),
  1014. "skill_view": _cute_skill_view,
  1015. "image_generate": lambda a, r: _cute_row("🎨", "create", _cute_trunc(a.get("prompt", ""))),
  1016. "text_to_speech": lambda a, r: (
  1017. _cute_row("🗣️ ", "voices", _cute_trunc((a.get("find_voices") or {}).get("query") or "browse"))
  1018. if isinstance(a.get("find_voices"), dict)
  1019. else _cute_row("🔊", "speak", _cute_trunc(a.get("text", "")))),
  1020. "vision_analyze": lambda a, r: _cute_row("👁️ ", "vision", _cute_trunc(a.get("question", ""))),
  1021. "send_message": lambda a, r: _cute_row("📨", "send", f"{a.get('target', '?')}: \"{_cute_trunc(a.get('message', ''))}\""),
  1022. "cronjob_manage": _cute_cronjob,
  1023. "execute_code": _cute_execute_code,
  1024. "browser_exec": _cute_browser_exec,
  1025. "delegate_task": _cute_delegate,
  1026. }
  1027. def _cute_bridge_rows(tool_name: str, args: dict) -> list[str] | None:
  1028. labels = bridge_tool_labels(tool_name, args)
  1029. if not labels:
  1030. return None
  1031. return [f"┊ {label.emoji} {_cute_trunc(label.text)}"
  1032. f"{f' {_cute_trunc(label.preview)}' if label.preview else ''}" for label in labels]
  1033. _BRIDGE_CALL_INDEX_RE = re.compile(r"calls\[(\d+)\]")
  1034. def _entry_failure_suffix(entry: Any) -> str:
  1035. if not isinstance(entry, dict):
  1036. return ""
  1037. error = entry.get("error")
  1038. if isinstance(error, dict):
  1039. return f" [{_trim_error(str(error.get('message') or error.get('code') or t('display.failure.generic_word')))}]"
  1040. if not (error or entry.get("success") is False):
  1041. return ""
  1042. return _detect_tool_failure(str(entry.get("name") or ""), entry)[1]
  1043. def _bridge_row_suffixes(rows: int, result: Any, call_suffix: str) -> list[str]:
  1044. suffixes = [""] * rows
  1045. data = result if isinstance(result, dict) else safe_json_loads(result)
  1046. entries = data.get("results") if isinstance(data, dict) else None
  1047. if isinstance(entries, list):
  1048. for position, entry in enumerate(entries[:rows]):
  1049. suffix = _entry_failure_suffix(entry)
  1050. if not suffix:
  1051. continue
  1052. index = entry.get("index")
  1053. suffixes[index if isinstance(index, int) and 0 <= index < rows else position] = suffix
  1054. if call_suffix and not any(suffixes):
  1055. match = _BRIDGE_CALL_INDEX_RE.search(call_suffix)
  1056. named = int(match.group(1)) if match else rows - 1
  1057. suffixes[named if 0 <= named < rows else rows - 1] = call_suffix
  1058. return suffixes
  1059. def _get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
  1060. args = redact_tool_args_for_display(tool_name, args) or args
  1061. is_failure, failure_suffix = _detect_tool_failure(tool_name, result)
  1062. render = _CUTE_LINES.get(tool_name)
  1063. rows = _cute_bridge_rows(tool_name, args)
  1064. if rows is None:
  1065. body = render(args, result) if render else _cute_fallback_row(tool_name, args)
  1066. rows, suffixes = [body], [failure_suffix if is_failure else ""]
  1067. else:
  1068. suffixes = _bridge_row_suffixes(len(rows), result, failure_suffix if is_failure else "")
  1069. rows = [*rows[:-1], f"{rows[-1]} {duration:.1f}s"]
  1070. prefix = get_skin_tool_prefix()
  1071. return "\n ".join(f"{row}{suffix}".replace("┊", prefix, 1) for row, suffix in zip(rows, suffixes))
  1072. def get_cute_tool_message(tool_name: str, args: dict, duration: float, result: str | None = None) -> str:
  1073. """Render a completion label without letting cosmetic failures escape."""
  1074. try:
  1075. return _get_cute_tool_message(tool_name, args, duration, result=result)
  1076. except Exception as exc:
  1077. logger.debug("Tool completion label failed for %s: %s", tool_name, exc)
  1078. safe_name = tool_name[:9] if isinstance(tool_name, str) and tool_name else t("display.cute.fallback_tool_name")
  1079. safe_duration = f"{duration:.1f}s" if isinstance(duration, (int, float)) else t("display.cute.fallback_done")
  1080. return t("display.cute.completed", tool=f"{safe_name:9}", duration=safe_duration)