File size: 8,884 Bytes
c453128 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | """Parse Hermes messages into a human-readable activity feed."""
import json
import re
from dataclasses import dataclass, field
from agent_gui.message_sanitize import strip_injected_prefix
from agent_gui.db import Message
TOOL_ICONS = {
"bash": "β‘", "execute_command": "β‘", "terminal": "β‘", "run_command": "β‘",
"write_file": "π", "create_file": "π", "file_write": "π",
"str_replace_editor": "βοΈ", "edit_file": "βοΈ",
"read_file": "π", "file_read": "π",
"web_search": "π", "search": "π",
"browser": "π", "web_fetch": "π",
"memory": "π§ ", "remember": "π§ ",
"compress": "ποΈ", "summarize": "ποΈ",
"delegate": "π₯", "spawn_agent": "π₯", "subagent": "π₯",
"skill_view": "π", "skill_run": "π",
"python": "π",
# Claude Code (Claude Agent SDK) tool names β PascalCase, so they need their
# own entries; persisted faithfully (not remapped to the Hermes vocabulary).
"Read": "π", "Write": "π", "Edit": "βοΈ", "MultiEdit": "βοΈ", "NotebookEdit": "βοΈ",
"Bash": "β‘", "BashOutput": "β‘", "KillShell": "β‘",
"Glob": "π", "Grep": "π", "WebSearch": "π", "WebFetch": "π",
"Task": "π₯", "TodoWrite": "π", "ExitPlanMode": "π",
"default": "π§",
}
# An assistant message's visible text becomes a feed "message" event only when its
# stripped length exceeds this β tiny/whitespace-only runs (e.g. a stray space a
# model emits right before a tool call) are dropped. server._record_worker_evt_time
# applies the SAME threshold when recording real per-event time markers, so the
# per-kind marker count stays aligned 1:1 with these events (see _apply_real_times).
MIN_MESSAGE_LEN = 5
@dataclass
class ActivityEvent:
timestamp: str
event_type: str # tool_call | tool_result | message | user_message | error
icon: str
title: str
detail: str
tool_name: str = ""
is_error: bool = False
files_touched: list[str] = field(default_factory=list)
# True only when `timestamp` is a real recorded emit-time. False means it's
# Hermes's coarse batch-flush time (all events in a turn cluster together) β
# the UI shows those as approximate rather than pretending they're exact.
time_exact: bool = False
def _truncate(text: str, n: int = 160) -> str:
text = str(text).strip().replace("\n", " ")
return text[:n] + "β¦" if len(text) > n else text
def _clean(text: str) -> str:
"""Return text stripped but with newlines preserved (for message display)."""
return str(text).strip()
def _tool_detail(tool_name: str, tool_input: dict) -> str:
if tool_name in ("bash", "execute_command", "run_command", "terminal", "Bash"):
return _truncate(tool_input.get("command", tool_input.get("cmd", str(tool_input))))
if tool_name in ("write_file", "create_file", "file_write", "str_replace_editor",
"edit_file", "read_file", "file_read",
"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"):
path = (tool_input.get("path") or tool_input.get("file_path")
or tool_input.get("filename") or tool_input.get("notebook_path") or "")
return path or _truncate(str(tool_input))
if tool_name in ("web_search", "search", "WebSearch"):
return _truncate(tool_input.get("query", str(tool_input)))
if tool_name in ("Grep", "Glob"):
return _truncate(tool_input.get("pattern", str(tool_input)))
if tool_name in ("web_fetch", "WebFetch"):
return _truncate(tool_input.get("url", str(tool_input)))
return _truncate(str(tool_input))
def _files_from_tool(tool_name: str, tool_input: dict) -> list[str]:
for key in ("path", "file_path", "filename", "filepath", "notebook_path"):
val = tool_input.get(key)
if val and isinstance(val, str):
return [val]
return []
def parse_activity(messages: list[Message]) -> list[ActivityEvent]:
events: list[ActivityEvent] = []
tool_call_map: dict[str, dict] = {} # id β {name, input}
for msg in messages:
ts = msg.timestamp
# ββ User message βββββββββββββββββββββββββββββββββββββββββββββββββββββ
if msg.role == "user":
if msg.content and msg.content.strip():
clean = strip_injected_prefix(msg.content)
if clean:
events.append(ActivityEvent(
timestamp=ts,
event_type="user_message",
icon="π€",
title="User",
detail=_clean(clean),
))
# ββ Assistant message (may have tool_calls and/or text) βββββββββββββββ
elif msg.role == "assistant":
# Reasoning/thinking trace β emit first (it precedes the response) as a
# collapsible step so the full trace stays retrievable after the live
# stream ends. Carries the complete (untruncated) text in `detail`.
reasoning = (msg.reasoning_content or "").strip()
if reasoning:
events.append(ActivityEvent(
timestamp=ts,
event_type="thinking_start",
icon="π",
title="Reasoning",
detail=reasoning,
))
# Visible text comes BEFORE the tool calls: the model streams its
# message ("let me edit X") and only then invokes the tool β the same
# order the live feed shows (onLive flushes streamed text on
# tool_start). Emitting tool calls first (the old order) meant a reload
# reordered them, so the message's real recorded time landed *after*
# the tool it actually preceded, looking out of sync. Emit text first.
if msg.content and msg.content.strip() and len(msg.content.strip()) > MIN_MESSAGE_LEN:
text = msg.content.strip()
is_compression = any(kw in text.lower() for kw in ("compressing", "context compressed", "summarizing context"))
events.append(ActivityEvent(
timestamp=ts,
event_type="compression" if is_compression else "message",
icon="ποΈ" if is_compression else "π€",
title="Context compressed" if is_compression else "Agent",
detail=_truncate(text, 300) if is_compression else _clean(text),
))
for tc in msg.tool_calls:
if tc.get("type") != "function":
continue
fn = tc.get("function", {})
tool_name = fn.get("name", "unknown")
args_raw = fn.get("arguments", "{}")
try:
tool_input = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
except Exception:
tool_input = {}
tool_call_map[tc.get("id", "")] = {"name": tool_name, "input": tool_input}
icon = TOOL_ICONS.get(tool_name, TOOL_ICONS["default"])
files = _files_from_tool(tool_name, tool_input)
events.append(ActivityEvent(
timestamp=ts,
event_type="tool_call",
icon=icon,
title=f"calling {tool_name}",
detail=_tool_detail(tool_name, tool_input),
tool_name=tool_name,
files_touched=files,
))
# ββ Tool result βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
elif msg.role == "tool":
call = tool_call_map.get(msg.tool_call_id or "", {})
tool_name = msg.tool_name or call.get("name", "tool")
content = msg.content or ""
is_error = False
try:
result = json.loads(content)
if isinstance(result, dict):
is_error = bool(result.get("error")) and not result.get("success", True)
except Exception:
pass
icon = TOOL_ICONS.get(tool_name, TOOL_ICONS["default"])
events.append(ActivityEvent(
timestamp=ts,
event_type="tool_result",
icon="β" if is_error else icon,
title=f"{tool_name} {'failed' if is_error else 'done'}",
detail=_truncate(content, 200),
tool_name=tool_name,
is_error=is_error,
))
return events
|