refactor(hermes_cli): inline bind-board workdir sync, compact export/save renderers

This commit is contained in:
Teknium
2026-09-02 20:48:06 -07:00
parent 8d0354df15
commit 469c8f45ab
2 changed files with 34 additions and 82 deletions
+15 -39
View File
@@ -37,12 +37,7 @@ def normalize_export_only(only: Optional[str]) -> Optional[ExportOnly]:
raise ValueError(f"Unsupported session export filter: {only}")
def render_sessions_export(
sessions: Iterable[Dict[str, Any]],
*,
fmt: str = "jsonl",
only: Optional[str] = None,
) -> str:
def render_sessions_export(sessions: Iterable[Dict[str, Any]], *, fmt: str = "jsonl", only: Optional[str] = None) -> str:
"""Render exported sessions in a stable, reusable format.
``fmt=jsonl`` with no filter keeps the legacy shape (one full session object per line);
@@ -66,17 +61,13 @@ def render_sessions_export(
if not session_list:
lines += ["_No user prompts found._", ""]
return _finish_markdown(lines)
heading = lambda session: f"Session: {_heading_text(_session_title_or_id(session))}" # noqa: E731
return _finish_markdown(_render_sessions_markdown(
session_list, "Hermes sessions export",
lambda session: f"Session: {_heading_text(_session_title_or_id(session))}",
lambda session: f"Session: {_heading_text(_session_title_or_id(session))}",
_append_session_messages,
session_list, "Hermes sessions export", heading, heading, _append_session_messages,
))
def export_record_count(
sessions: Iterable[Dict[str, Any]], *, only: Optional[str] = None
) -> Tuple[int, str]:
def export_record_count(sessions: Iterable[Dict[str, Any]], *, only: Optional[str] = None) -> Tuple[int, str]:
"""Return ``(count, noun)`` for status messages after an export."""
session_list = list(sessions)
if normalize_export_only(only) == "user-prompts":
@@ -84,9 +75,7 @@ def export_record_count(
return len(session_list), "session"
def iter_user_prompt_records(
sessions: Iterable[Dict[str, Any]]
) -> Iterator[Dict[str, Any]]:
def iter_user_prompt_records(sessions: Iterable[Dict[str, Any]]) -> Iterator[Dict[str, Any]]:
"""Yield one normalized record for each user-authored prompt."""
for session in sessions:
session_id = str(session.get("id") or session.get("session_id") or "")
@@ -124,33 +113,25 @@ def _render_sessions_markdown(sessions, multi_title, single_heading, multi_headi
return lines
def _append_prompt_records(
lines: List[str], session: Dict[str, Any], *, heading_level: int
) -> None:
def _append_prompt_records(lines: List[str], session: Dict[str, Any], *, heading_level: int) -> None:
prompts = list(iter_user_prompt_records([session]))
if not prompts:
lines += ["_No user prompts found._", ""]
return
marker = "#" * heading_level
for prompt in prompts:
timestamp = prompt.get("created_at") or "timestamp unavailable"
lines.append(f"{marker} {prompt['index']}. {timestamp}")
lines.append(f"{marker} {prompt['index']}. {prompt.get('created_at') or 'timestamp unavailable'}")
if (message_id := prompt.get("message_id")) is not None:
lines += [f"Message ID: `{message_id}`", ""]
lines += [str(prompt.get("text") or ""), ""]
def _append_session_messages(
lines: List[str], session: Dict[str, Any], *, heading_level: int
) -> None:
def _append_session_messages(lines: List[str], session: Dict[str, Any], *, heading_level: int) -> None:
marker = "#" * heading_level
visible_messages = [
message for message in _messages(session) if message.get("role") != "system"
]
visible_messages = [message for message in _messages(session) if message.get("role") != "system"]
if not visible_messages:
lines += ["_No messages found._", ""]
return
for message in visible_messages:
role = str(message.get("role") or "unknown")
timestamp = _format_timestamp(message.get("timestamp"))
@@ -163,9 +144,9 @@ def _append_session_messages(
f"<details><summary>{html_escape(tool_name)}</summary>", "",
_fenced_text(text), "", "</details>", "",
]
continue
label = {"user": "User", "assistant": "Assistant"}.get(role, role.title())
lines += [f"{marker} {label}{suffix}", "", text, ""]
else:
label = {"user": "User", "assistant": "Assistant"}.get(role, role.title())
lines += [f"{marker} {label}{suffix}", "", text, ""]
def _messages(session: Dict[str, Any]) -> List[Dict[str, Any]]:
@@ -185,8 +166,7 @@ def _content_part_text(part: Any) -> str:
return part
if isinstance(part, dict):
for key in ("text", "content"):
value = part.get(key)
if isinstance(value, str):
if isinstance(value := part.get(key), str):
return value
return json.dumps(part, ensure_ascii=False, sort_keys=True)
return str(part)
@@ -273,9 +253,7 @@ def normalize_save_format(fmt: Optional[str]) -> str:
"""Map a user-typed /save format token to a canonical format."""
token = (fmt or "json").strip().lower()
if token not in _SAVE_FORMAT_ALIASES:
raise ValueError(
f"Unknown format {token!r} — expected one of: json, md, html"
)
raise ValueError(f"Unknown format {token!r} — expected one of: json, md, html")
return _SAVE_FORMAT_ALIASES[token]
@@ -302,7 +280,5 @@ def render_session_for_save(session: Dict[str, Any], fmt: str) -> str:
def default_save_filename(session_id: str, fmt: str) -> str:
"""Default filename for a /save export of the given session."""
safe_id = "".join(
ch for ch in str(session_id) if ch.isalnum() or ch in ("-", "_")
) or "session"
safe_id = "".join(ch for ch in str(session_id) if ch.isalnum() or ch in ("-", "_")) or "session"
return f"hermes_session_{safe_id}.{fmt}"