session_listing.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. """Shared session-listing helpers for CLI and gateway slash surfaces."""
  2. from __future__ import annotations
  3. import shlex
  4. from pathlib import Path
  5. from typing import Any
  6. from utils import is_truthy_value
  7. _LIST_WORDS = {"list", "ls", "browse"}
  8. _SEARCH_WORDS = {"search", "find"}
  9. SUBAGENT_SOURCE = "subagent"
  10. def show_subagent_sessions(hermes_home: str | Path) -> bool:
  11. """``sessions.show_subagents`` from *hermes_home*'s own config.yaml. One ``serve`` lists many
  12. profiles' stores, so the store's home decides, never the process ``HERMES_HOME``. False when
  13. the config cannot be read (the listing keeps its default shape)."""
  14. from hermes_cli.config import load_config_readonly
  15. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  16. token = set_hermes_home_override(str(hermes_home))
  17. try:
  18. sessions_cfg = load_config_readonly().get("sessions") or {}
  19. except Exception:
  20. return False
  21. finally:
  22. reset_hermes_home_override(token)
  23. return isinstance(sessions_cfg, dict) and is_truthy_value(sessions_cfg.get("show_subagents"))
  24. def subagent_listing_scope(
  25. hermes_home: str | Path, *, source: str | None = None, sources: list[str] | None = None,
  26. exclude_sources: list[str] | None = None,
  27. ) -> tuple[bool, list[str] | None]:
  28. """``(include_subagents, exclude_sources)`` for one human-facing session list (#97202).
  29. With ``sessions.show_subagents`` on, delegate runs join a list that is not scoped to named
  30. sources and either has no exclusions or excludes the ``subagent`` source itself (the desktop
  31. recents shape); that exclusion is dropped so the runs actually land. A slice that excludes
  32. other sources without ``subagent`` (the per-platform messaging lists) keeps its shape.
  33. """
  34. excluded = list(exclude_sources or [])
  35. if source or sources or (excluded and SUBAGENT_SOURCE not in excluded):
  36. return False, exclude_sources
  37. if not show_subagent_sessions(hermes_home):
  38. return False, exclude_sources
  39. return True, [s for s in excluded if s != SUBAGENT_SOURCE] or None
  40. def parse_session_listing_args(raw_args: str) -> tuple[bool, bool, str, str | None]:
  41. """Parse `/sessions`-style args into ``(include_all_sources, include_unnamed, target, search_query)``.
  42. ``all`` widens source scope, ``full`` keeps unnamed sessions, ``search``/``find`` makes the rest
  43. a query (``None`` = not requested, ``""`` = requested with no terms). Flags are honored only
  44. before the first positional word so titles containing "all" aren't misparsed; anything else is
  45. a target so `/sessions <id-or-title>` can delegate to `/resume`.
  46. """
  47. parts = shlex.split(raw_args or "")
  48. flags = {"all": False, "full": False}
  49. target_parts: list[str] = []
  50. for i, part in enumerate(parts):
  51. lower = part.strip().lower()
  52. if not target_parts:
  53. if lower in _LIST_WORDS:
  54. continue
  55. if lower in {"all", "--all", "full", "--full"}:
  56. flags[lower.lstrip("-")] = True
  57. continue
  58. if lower in _SEARCH_WORDS:
  59. return flags["all"], flags["full"], "", " ".join(parts[i + 1:]).strip()
  60. target_parts.append(part)
  61. return flags["all"], flags["full"], " ".join(target_parts).strip(), None
  62. def query_session_listing(
  63. session_db: Any,
  64. *,
  65. source: str | None,
  66. session_key: str | None = None,
  67. current_session_id: str | None = None,
  68. include_current_session: bool = False,
  69. include_all_sources: bool = False,
  70. include_unnamed: bool = False,
  71. search_query: str | None = None,
  72. limit: int = 10,
  73. exclude_sources: list[str] | None = None,
  74. ) -> list[dict[str, Any]]:
  75. """Return session rows for interactive listing surfaces (shared CLI/gateway policy).
  76. Source-scoped unless global is requested; unnamed hidden unless a full listing is asked for;
  77. current session hidden unless requested (then marked ``is_current_session``); ``session_key``
  78. restricts gateway callers to one lane before the DB limit applies. With ``search_query`` rows
  79. are filtered by title/id in SQL, ordered by recent activity, and unnamed sessions stay visible
  80. since an id match may be the only handle.
  81. """
  82. search = (search_query or "").strip()
  83. rows = session_db.list_sessions_rich(
  84. source=None if include_all_sources else source,
  85. session_key=session_key,
  86. exclude_sources=exclude_sources,
  87. limit=max(limit * 4, limit),
  88. search_query=search or None,
  89. order_by_last_active=bool(search),
  90. )
  91. result: list[dict[str, Any]] = []
  92. for row in rows:
  93. is_current = bool(current_session_id and row.get("id") == current_session_id)
  94. if (is_current and not include_current_session) or (
  95. not include_unnamed and not row.get("title") and not search and not is_current
  96. ):
  97. continue
  98. result.append({**row, "is_current_session": True} if is_current else row)
  99. if len(result) >= limit:
  100. break
  101. return result
  102. def format_gateway_session_listing(
  103. rows: list[dict[str, Any]],
  104. *,
  105. include_source: bool = False,
  106. title: str = "Sessions",
  107. notice: str | None = None,
  108. ) -> str:
  109. """Render a compact Markdown-ish session list for gateway messengers.
  110. ``notice`` adds an explanatory line above the footer — e.g. when a requested scope widening
  111. (``all``) was declined, so the caller isn't left guessing why sessions are missing.
  112. """
  113. if not rows:
  114. return "\n".join([
  115. "No sessions found.\n"
  116. "Use `/title My Session` to name this chat, or `/sessions full` "
  117. "to include unnamed sessions.",
  118. *([notice] if notice else []),
  119. ])
  120. lines = [f"📋 **{title}**", ""]
  121. for idx, row in enumerate(rows, start=1):
  122. current_part = " (current)" if row.get("is_current_session") else ""
  123. preview = str(row.get("preview") or "")[:40]
  124. source = str(row.get("source") or "")
  125. source_part = f" `{source}`" if include_source and source else ""
  126. preview_part = f" — _{preview}_" if preview else ""
  127. lines.append(
  128. f"{idx}. **{row.get('title') or '—'}**{current_part}{source_part}"
  129. f" — `{row.get('id') or ''}`{preview_part}"
  130. )
  131. return "\n".join([
  132. *lines, "", *([notice] if notice else []),
  133. "Resume: `/resume <session id>` or `/resume <number>` from `/resume`.",
  134. "More: `/sessions all`, `/sessions full`, `/sessions search <query>`.",
  135. ])