Skip to content

The agent that grows with you

refactor(hermes_cli): compact session filter describe table and listing helpers

Teknium18255b027b59
diff --git a/hermes_cli/session_filters.py b/hermes_cli/session_filters.py
index 9d252fdbd3c..5b009a0f9dd 100644
--- a/hermes_cli/session_filters.py
+++ b/hermes_cli/session_filters.py
@@ -20,13 +20,12 @@ _UNIT_SECONDS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
def parse_duration_seconds(value: str) -> Optional[float]:
- """Parse ``5h`` / ``30m`` / ``2d`` / ``1w`` / ``90`` (bare = days) into
- seconds. Returns None when the value doesn't look like a duration."""
+ """Parse ``5h`` / ``30m`` / ``2d`` / ``1w`` / ``90`` (bare = days, backward compatible with
+ ``--older-than 90``) into seconds. Returns None when the value doesn't look like a duration."""
s = str(value).strip().lower()
if not s:
return None
if re.fullmatch(r"\d+(?:\.\d+)?", s):
- # Bare number = days (backward compatible with --older-than 90)
return float(s) * 86400
m = _DURATION_RE.match(s)
if not m:
@@ -67,13 +66,8 @@ def format_epoch(ts: Optional[float]) -> str:
def build_prune_filters(args: Any) -> Dict[str, Any]:
"""Translate argparse Namespace flags into SessionDB filter kwargs.
- Understands: ``--older-than``, ``--newer-than``, ``--before``, ``--after``, ``--source``,
- ``--title``, ``--end-reason``, ``--cwd``, ``--min-messages``, ``--max-messages``,
- ``--archived``/``--no-archived``.
-
- ``--older-than`` / ``--newer-than`` bound last activity, while ``--before`` / ``--after``
- explicitly bound session start time. Last activity is the latest message timestamp, falling back
- to ``started_at`` for empty sessions.
+ ``--older-than`` / ``--newer-than`` bound last activity (latest message timestamp, falling back
+ to ``started_at`` for empty sessions); ``--before`` / ``--after`` bound session start time.
"""
bounds: Dict[str, Optional[float]] = {}
for key, attr, flag in _TIME_BOUNDS:
@@ -88,9 +82,8 @@ def build_prune_filters(args: Any) -> Dict[str, Any]:
f"{hi_flag} bound ({format_epoch(bounds[hi])})."
)
- # older_than_days=None: the epoch bounds above are the whole story.
- # Without this, prune_sessions' default 90-day cutoff would silently
- # cap an --after/--newer-than-only window.
+ # older_than_days=None: the epoch bounds are the whole story; otherwise prune_sessions' default
+ # 90-day cutoff would silently cap an --after/--newer-than-only window.
filters: Dict[str, Any] = {"older_than_days": None, **bounds}
for key, attr in _ARG_FILTERS:
filters[key] = getattr(args, attr, None)
@@ -109,60 +102,52 @@ _WINDOWS = (
("started_after", "started_before", "start-time", "--after", "--before"),
("last_active_after", "last_active_before", "activity", "--newer-than", "--older-than"),
)
+# (filter key, argparse attr) for pass-through filters; also the describe order after the bounds.
_ARG_FILTERS = (
- ("source", "source"),
- ("title_like", "title"),
- ("end_reason", "end_reason"),
- ("cwd_prefix", "cwd"),
- ("min_messages", "min_messages"),
- ("max_messages", "max_messages"),
- ("model_like", "model"),
- ("provider", "provider"),
- ("user_id", "user"),
- ("chat_id", "chat_id"),
- ("chat_type", "chat_type"),
- ("branch_like", "branch"),
- ("min_tokens", "min_tokens"),
- ("max_tokens", "max_tokens"),
- ("min_cost", "min_cost"),
- ("max_cost", "max_cost"),
- ("min_tool_calls", "min_tool_calls"),
+ ("source", "source"), ("title_like", "title"), ("end_reason", "end_reason"), ("cwd_prefix", "cwd"),
+ ("min_messages", "min_messages"), ("max_messages", "max_messages"), ("model_like", "model"),
+ ("provider", "provider"), ("user_id", "user"), ("chat_id", "chat_id"), ("chat_type", "chat_type"),
+ ("branch_like", "branch"), ("min_tokens", "min_tokens"), ("max_tokens", "max_tokens"),
+ ("min_cost", "min_cost"), ("max_cost", "max_cost"), ("min_tool_calls", "min_tool_calls"),
("max_tool_calls", "max_tool_calls"),
)
-# (filter key, description template, include when: "set" == `is not None`, "truthy" == bool(v)).
-_DESCRIBE = (
- ("last_active_before", "last active before {e}", "set"),
- ("last_active_after", "last active after {e}", "set"),
- ("started_before", "started before {e}", "set"),
- ("started_after", "started after {e}", "set"),
- ("source", "source '{v}'", "truthy"),
- ("title_like", "title contains '{v}'", "truthy"),
- ("end_reason", "end reason '{v}'", "truthy"),
- ("cwd_prefix", "cwd under '{v}'", "truthy"),
- ("min_messages", ">= {v} messages", "set"),
- ("max_messages", "<= {v} messages", "set"),
- ("model_like", "model contains '{v}'", "truthy"),
- ("provider", "provider '{v}'", "truthy"),
- ("user_id", "user '{v}'", "truthy"),
- ("chat_id", "chat '{v}'", "truthy"),
- ("chat_type", "chat type '{v}'", "truthy"),
- ("branch_like", "git branch contains '{v}'", "truthy"),
- ("min_tokens", ">= {v} tokens", "set"),
- ("max_tokens", "<= {v} tokens", "set"),
- ("min_cost", ">= ${v}", "set"),
- ("max_cost", "<= ${v}", "set"),
- ("min_tool_calls", ">= {v} tool calls", "set"),
- ("max_tool_calls", "<= {v} tool calls", "set"),
-)
+# filter key -> description template. ``{e}`` renders an epoch (shown when not None); ``{v}`` on a
+# numeric filter is shown when not None, on a text filter only when truthy.
+_DESCRIBE = {
+ "last_active_before": "last active before {e}",
+ "last_active_after": "last active after {e}",
+ "started_before": "started before {e}",
+ "started_after": "started after {e}",
+ "source": "source '{v}'",
+ "title_like": "title contains '{v}'",
+ "end_reason": "end reason '{v}'",
+ "cwd_prefix": "cwd under '{v}'",
+ "min_messages": ">= {v} messages",
+ "max_messages": "<= {v} messages",
+ "model_like": "model contains '{v}'",
+ "provider": "provider '{v}'",
+ "user_id": "user '{v}'",
+ "chat_id": "chat '{v}'",
+ "chat_type": "chat type '{v}'",
+ "branch_like": "git branch contains '{v}'",
+ "min_tokens": ">= {v} tokens",
+ "max_tokens": "<= {v} tokens",
+ "min_cost": ">= ${v}",
+ "max_cost": "<= ${v}",
+ "min_tool_calls": ">= {v} tool calls",
+ "max_tool_calls": "<= {v} tool calls",
+}
def describe_filters(filters: Dict[str, Any]) -> str:
"""Human-readable summary of active filters for confirmation prompts."""
parts = []
- for key, template, mode in _DESCRIBE:
+ for key, template in _DESCRIBE.items():
value = filters.get(key)
- if (value is not None) if mode == "set" else bool(value):
- shown = format_epoch(value) if "{e}" in template else value
+ is_epoch = "{e}" in template
+ numeric = is_epoch or key.startswith(("min_", "max_"))
+ if (value is not None) if numeric else bool(value):
+ shown = format_epoch(value) if is_epoch else value
parts.append(template.replace("{e}", "{v}").format(v=shown))
return ", ".join(parts) if parts else "no filters (all ended sessions)"
diff --git a/hermes_cli/session_listing.py b/hermes_cli/session_listing.py
index 9cae4f4d53a..7eff337f3fd 100644
--- a/hermes_cli/session_listing.py
+++ b/hermes_cli/session_listing.py
@@ -2,20 +2,21 @@
from __future__ import annotations
+import shlex
from typing import Any
+_LIST_WORDS = {"list", "ls", "browse"}
+_SEARCH_WORDS = {"search", "find"}
+
def parse_session_listing_args(raw_args: str) -> tuple[bool, bool, str, str | None]:
- """Parse `/sessions`-style args into listing flags, a resume target, and a search query.
+ """Parse `/sessions`-style args into ``(include_all_sources, include_unnamed, target, search_query)``.
- Returns ``(include_all_sources, include_unnamed, target, search_query)``. ``all`` widens
- source scope, ``full`` keeps unnamed sessions, ``search``/``find`` makes the rest a query
- (``None`` = not requested, ``""`` = requested with no terms). Flags are honored only before
- the first positional word so titles containing "all" aren't misparsed; anything else is a
- target so `/sessions <id-or-title>` can delegate to `/resume`.
+ ``all`` widens source scope, ``full`` keeps unnamed sessions, ``search``/``find`` makes the rest
+ a query (``None`` = not requested, ``""`` = requested with no terms). Flags are honored only
+ before the first positional word so titles containing "all" aren't misparsed; anything else is
+ a target so `/sessions <id-or-title>` can delegate to `/resume`.
"""
- import shlex
-
parts = shlex.split(raw_args or "")
include_all = False
include_unnamed = False
@@ -23,7 +24,7 @@ def parse_session_listing_args(raw_args: str) -> tuple[bool, bool, str, str | No
for i, part in enumerate(parts):
lower = part.strip().lower()
if not target_parts:
- if lower in {"list", "ls", "browse"}:
+ if lower in _LIST_WORDS:
continue
if lower in {"all", "--all"}:
include_all = True
@@ -31,9 +32,8 @@ def parse_session_listing_args(raw_args: str) -> tuple[bool, bool, str, str | No
if lower in {"full", "--full"}:
include_unnamed = True
continue
- if lower in {"search", "find"}:
- query = " ".join(parts[i + 1:]).strip()
- return include_all, include_unnamed, "", query
+ if lower in _SEARCH_WORDS:
+ return include_all, include_unnamed, "", " ".join(parts[i + 1:]).strip()
target_parts.append(part)
return include_all, include_unnamed, " ".join(target_parts).strip(), None
@@ -59,14 +59,12 @@ def query_session_listing(
limit applies. With ``search_query`` rows are filtered by title/id in SQL, ordered by recent
activity, and unnamed sessions stay visible since an id match may be the only handle.
"""
- query_source = None if include_all_sources else source
- fetch_limit = max(limit * 4, limit)
search = (search_query or "").strip()
rows = session_db.list_sessions_rich(
- source=query_source,
+ source=None if include_all_sources else source,
session_key=session_key,
exclude_sources=exclude_sources,
- limit=fetch_limit,
+ limit=max(limit * 4, limit),
search_query=search or None,
order_by_last_active=bool(search),
)
@@ -78,8 +76,7 @@ def query_session_listing(
if not include_unnamed and not row.get("title") and not search and not is_current:
continue
if is_current:
- row = dict(row)
- row["is_current_session"] = True
+ row = {**row, "is_current_session": True}
result.append(row)
if len(result) >= limit:
break
@@ -95,8 +92,8 @@ def format_gateway_session_listing(
) -> str:
"""Render a compact Markdown-ish session list for gateway messengers.
- ``notice`` appends an explanatory line above the footer — used e.g. when a requested scope
- widening (``all``) was declined so the caller isn't left guessing why sessions are missing.
+ ``notice`` adds an explanatory line above the footer — e.g. when a requested scope widening
+ (``all``) was declined, so the caller isn't left guessing why sessions are missing.
"""
if not rows:
parts = [
@@ -110,14 +107,15 @@ def format_gateway_session_listing(
lines = [f"📋 **{title}**", ""]
for idx, row in enumerate(rows, start=1):
- session_id = str(row.get("id") or "")
- title_text = str(row.get("title") or "—")
current_part = " (current)" if row.get("is_current_session") else ""
preview = str(row.get("preview") or "")[:40]
source = str(row.get("source") or "")
source_part = f" `{source}`" if include_source and source else ""
preview_part = f" — _{preview}_" if preview else ""
- lines.append(f"{idx}. **{title_text}**{current_part}{source_part} — `{session_id}`{preview_part}")
+ lines.append(
+ f"{idx}. **{row.get('title') or '—'}**{current_part}{source_part}"
+ f" — `{row.get('id') or ''}`{preview_part}"
+ )
lines.append("")
if notice:
lines.append(notice)