sessions.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. """``hermes sessions`` subcommand parser."""
  2. from __future__ import annotations
  3. from pathlib import Path
  4. from typing import Callable
  5. from hermes_cli.subcommands._shared import add_json_flag, add_yes_flag
  6. def _flag(parser, *names, help, **kw):
  7. parser.add_argument(*names, action="store_true", help=help, **kw)
  8. def cmd_sessions_lazy(args, **kwargs):
  9. """``hermes sessions`` handler; sessions_cmd imports only when the subcommand runs."""
  10. from hermes_cli.sessions_cmd import cmd_sessions
  11. return cmd_sessions(args, **kwargs)
  12. def _add_rename_and_discard(sessions_subparsers) -> None:
  13. sessions_rename = sessions_subparsers.add_parser(
  14. "rename", help="Set or change a session's title")
  15. sessions_rename.add_argument("session_id", help="Session ID to rename")
  16. sessions_rename.add_argument("title", nargs="+", help="New title for the session")
  17. from hermes_cli.sessions_discard import add_discard_parser
  18. add_discard_parser(sessions_subparsers)
  19. from hermes_cli.sessions_adopt import add_adopt_parser
  20. add_adopt_parser(sessions_subparsers)
  21. def _add_refresh_prompts(sessions_subparsers) -> None:
  22. refresh = sessions_subparsers.add_parser(
  23. "refresh-prompts", help="Make continuing sessions rebuild their system prompt on their next turn",
  24. description="After updating SOUL.md, skills or context files in this profile, ask every "
  25. "continuing session (or one with --session) to rebuild its stored system prompt once, "
  26. "on its next turn, from the current sources. Conversation history and session ids are "
  27. "kept; each refreshed session pays one prompt-cache miss. Works while the gateway runs "
  28. "and across restarts. Use -p/--profile to target another profile.")
  29. refresh.add_argument("--session", default=None, metavar="SESSION_ID",
  30. help="Refresh only this session (id or unique prefix)")
  31. _flag(refresh, "--json", help="Machine-readable output")
  32. def build_sessions_parser(subparsers, *, cmd_sessions: Callable) -> None:
  33. """Attach the ``sessions`` subcommand to ``subparsers``."""
  34. sessions_parser = subparsers.add_parser(
  35. "sessions", help="Manage session history (list, rename, export, prune, delete)",
  36. description="View and manage the SQLite session store")
  37. sessions_subparsers = sessions_parser.add_subparsers(dest="sessions_action")
  38. sessions_list = sessions_subparsers.add_parser("list", help="List recent sessions")
  39. sessions_list.add_argument("--source", help="Filter by source (cli, telegram, discord, etc.)")
  40. sessions_list.add_argument("--limit", type=int, default=20, help="Max sessions to show")
  41. sessions_list.add_argument("--workspace", metavar="NEEDLE",
  42. help="Only sessions in one workspace: a git repo root or project dir "
  43. "(matched by path substring or basename).")
  44. _filter_args = (
  45. ("--newer-than", dict(metavar="AGE", help="Only match sessions active within the last AGE "
  46. "(e.g. '5h', '2d') or after an ISO timestamp")),
  47. ("--before", dict(metavar="TIME", help="Only match sessions started before TIME "
  48. "(duration ago like '5h', or ISO timestamp like '2026-07-05 14:30')")),
  49. ("--after", dict(metavar="TIME", help="Only match sessions started at/after TIME "
  50. "(duration ago like '5h', or ISO timestamp)")),
  51. ("--source", dict(help="Only match sessions from this source")),
  52. ("--title", dict(help="Only match sessions whose title contains this substring")),
  53. ("--end-reason", dict(help="Only match sessions with this end reason")),
  54. ("--cwd", dict(help="Only match sessions whose working directory is under this path")),
  55. ("--min-messages", dict(type=int, help="Only match sessions with >= N messages")),
  56. ("--max-messages", dict(type=int, help="Only match sessions with <= N messages")),
  57. ("--model", dict(help="Only match sessions whose model name contains this substring "
  58. "(e.g. 'sonnet', 'gpt-5', 'hermes')")),
  59. ("--provider", dict(help="Only match sessions billed through this provider "
  60. "(e.g. openrouter, anthropic, nous)")),
  61. ("--user", dict(help="Only match sessions from this user ID")),
  62. ("--chat-id", dict(help="Only match sessions from this chat/channel ID")),
  63. ("--chat-type", dict(help="Only match sessions with this chat type (e.g. dm, group)")),
  64. ("--branch", dict(help="Only match sessions whose git branch contains this substring")),
  65. ("--min-tokens", dict(type=int,
  66. help="Only match sessions with >= N total tokens (input+output)")),
  67. ("--max-tokens", dict(type=int,
  68. help="Only match sessions with <= N total tokens (input+output)")),
  69. ("--min-cost", dict(type=float,
  70. help="Only match sessions costing >= N USD (actual or estimated)")),
  71. ("--max-cost", dict(type=float,
  72. help="Only match sessions costing <= N USD (actual or estimated)")),
  73. ("--min-tool-calls", dict(type=int, help="Only match sessions with >= N tool calls")),
  74. ("--max-tool-calls", dict(type=int, help="Only match sessions with <= N tool calls")),
  75. ("--dry-run", dict(action="store_true",
  76. help="List matching sessions without changing anything")))
  77. def _add_session_filter_args(p, default_older_help):
  78. p.add_argument("--older-than", metavar="AGE", help=default_older_help)
  79. for flag, kw in _filter_args:
  80. p.add_argument(flag, **kw)
  81. add_yes_flag(p, "Skip confirmation")
  82. sessions_export = sessions_subparsers.add_parser(
  83. "export", help="Export sessions to JSONL, Markdown, or QMD")
  84. sessions_export.add_argument("output", nargs="?", metavar="OUTPUT",
  85. help="Where to write. jsonl/html/trace: a file path, or a directory (existing, or ending in /) "
  86. "to write a default-named file into; - for stdout (jsonl/trace only; jsonl requires OUTPUT). "
  87. "md/qmd: a directory, one file per session (default: <hermes home>/session-exports)")
  88. sessions_export.add_argument(
  89. "--format", choices=["jsonl", "md", "qmd", "html", "trace"], default="jsonl",
  90. help="Export format (default: jsonl). 'trace' emits Claude Code JSONL "
  91. "for the Hugging Face Agent Trace Viewer")
  92. _flag(sessions_export, "--upload",
  93. help="trace only: upload to your Hugging Face traces dataset instead "
  94. "of writing a local file (needs HF_TOKEN)")
  95. _flag(sessions_export, "--public",
  96. help="trace --upload only: create/update a public dataset instead of private")
  97. _flag(sessions_export, "--no-redact",
  98. help=("trace only: skip the forced secret redaction; only use after manual review"))
  99. sessions_export.add_argument("--only", choices=["user-prompts"],
  100. help="Export only a filtered view (user-prompts: one prompt record "
  101. "per line for jsonl, headed sections for md)")
  102. sessions_export.add_argument("--session-id", help="Session ID or unique prefix to export")
  103. _add_session_filter_args(
  104. sessions_export, "Only export sessions older than AGE (duration like '5h'/'2d', "
  105. "bare number of days, or an ISO timestamp). Filtered exports include pinned and archived "
  106. "sessions, so they back up everything a matching prune could delete")
  107. _flag(sessions_export, "--redact",
  108. help="Redact secrets (API keys, tokens, credentials) from exported content")
  109. sessions_export.add_argument("--lineage", choices=["single", "logical"], default="single",
  110. help="md/qmd only: export one row or its compression lineage")
  111. _flag(sessions_export, "--delete-after-verified",
  112. help="md/qmd only: after verified single-session export, delete that session (needs --yes)")
  113. _flag(sessions_export, "--force", help="md/qmd only: overwrite an existing export file")
  114. sessions_delete = sessions_subparsers.add_parser("delete", help="Delete a specific session")
  115. sessions_delete.add_argument("session_id", help="Session ID to delete")
  116. add_yes_flag(sessions_delete, "Skip confirmation")
  117. sessions_prune = sessions_subparsers.add_parser(
  118. "prune", help="Delete old sessions (filterable by time window, source, title, ...)")
  119. _add_session_filter_args(
  120. sessions_prune, "Delete sessions older than AGE — days if bare number, or a duration "
  121. "like '5h'/'2d'/'1w', or an ISO timestamp (bare prune with no filters "
  122. "defaults to 90 days; any filter matches all ages)")
  123. _flag(sessions_prune, "--include-archived",
  124. help="Also delete archived sessions (excluded by default)")
  125. _flag(sessions_prune, "--include-pinned",
  126. help="Also delete pinned sessions (excluded by default — pin is a keep flag)")
  127. _flag(sessions_prune, "--never-active",
  128. help="Instead of ended sessions, delete keyed gateway rows that were "
  129. "opened and never used (no messages, tokens, tool calls or title) "
  130. "and are older than AGE (default 30 days). Ordinary prune can "
  131. "never reach these — it only ever selects ended sessions")
  132. _flag(sessions_prune, "--force",
  133. help="With no gateway running: run even while another Hermes process (Desktop, dashboard, cron) holds state.db — rewriting the store under a live writer can leave every agent refusing turns until all writers are stopped. With the gateway running, prune always goes through it")
  134. sessions_archive = sessions_subparsers.add_parser(
  135. "archive", help="Bulk-archive (soft-hide) sessions matching filters — no deletion")
  136. _add_session_filter_args(sessions_archive, "Only archive sessions older than AGE (duration like '5h'/'2d', "
  137. "bare number of days, or ISO timestamp)")
  138. _flag(sessions_archive, "--include-open", help="Also archive never-ended sessions, e.g. Desktop chats")
  139. sessions_optimize = sessions_subparsers.add_parser(
  140. "optimize", help="Reclaim disk space: merge FTS5 segments + VACUUM (no data change)")
  141. _flag(sessions_optimize, "--force",
  142. help="Run even while another Hermes process (gateway, Desktop, dashboard, cron) holds state.db — rewriting the store under a live writer can leave every agent refusing turns until all writers are stopped")
  143. sessions_clean_markers = sessions_subparsers.add_parser("clean-markers",
  144. help="Permanently clear stale tool-call marker content left by sessions from before #78148",
  145. description="Before the #78148 fix, a local tool-call template could persist a "
  146. "bare bracketed marker (e.g. \"[memory]\") as an assistant turn's "
  147. "content instead of real text. This is already repaired in memory "
  148. "on every session load, so running this is optional — it rewrites "
  149. "the affected rows once, in place, so long-lived sessions stop "
  150. "re-scanning/re-repairing the same rows on every resume. Only the "
  151. "content column is touched; tool_calls and every other column on "
  152. "the row are left untouched.")
  153. _flag(sessions_clean_markers, "--dry-run", default=False,
  154. help="Report the affected row count without writing")
  155. _flag(sessions_clean_markers, "--no-backup", default=False,
  156. help="Skip the timestamped state.db backup taken before writing (not recommended)")
  157. sessions_optimize_storage = sessions_subparsers.add_parser("optimize-storage",
  158. help="Migrate the search index to the compact v23 layout (reclaims disk on large DBs)",
  159. description="Rebuild the full-text search index in the compact v23 "
  160. "external-content layout. On large databases this reclaims a "
  161. "large fraction of state.db (the old layout stored duplicate "
  162. "copies of every message and indexed tool output). Runs "
  163. "foreground with progress for every phase (refusing while a gateway "
  164. "or other Hermes process holds state.db, pacing itself if one opens it mid-run) and "
  165. "VACUUMs at the end. Safe to interrupt and re-run — it resumes where it left off. No conversation data is "
  166. "changed; only the search index is rebuilt.")
  167. _flag(sessions_optimize_storage, "--no-vacuum", default=False,
  168. help="Skip the final VACUUM (index is rebuilt but freed pages aren't returned to the OS until a later VACUUM)")
  169. _flag(sessions_optimize_storage, "--yes", "-y", default=False,
  170. help="Skip the disk-space confirmation prompt")
  171. _flag(sessions_optimize_storage, "--force",
  172. help="Run even while another Hermes process (gateway, Desktop, dashboard, cron) holds state.db — rewriting the store under a live writer can leave every agent refusing turns until all writers are stopped; the rebuild then paces itself so that process stays responsive (much slower)")
  173. sessions_repair = sessions_subparsers.add_parser(
  174. "repair", help="Repair a malformed state.db schema so hidden sessions reappear",
  175. description="Recover a state.db whose schema is malformed (e.g. 'table "
  176. "messages_fts already exists'), which makes Desktop/Dashboard show "
  177. "no sessions. A backup is made first; sessions and messages are "
  178. "preserved and the FTS search index is rebuilt if needed.")
  179. _flag(sessions_repair, "--check-only",
  180. help="Only report whether the database opens cleanly; do not modify it")
  181. _flag(sessions_repair, "--no-backup", help="Skip the timestamped backup copy (not recommended)")
  182. sessions_set_journal_mode = sessions_subparsers.add_parser(
  183. "set-journal-mode", help="Convert state.db between journal_mode=WAL and DELETE offline (every holder stopped)",
  184. description="Switch the on-disk journal mode of the session store. Hermes never "
  185. "live-downgrades a WAL database at startup (other processes may hold "
  186. "uncheckpointed commits), so `database.journal_mode: delete` cannot "
  187. "self-apply to an existing WAL store. Run this with the gateway, "
  188. "dashboard and every CLI stopped: it refuses while any process holds "
  189. "the file, switches the mode, and verifies the file header.")
  190. sessions_set_journal_mode.add_argument("mode", choices=("delete", "wal"), help="Target journal mode")
  191. sessions_set_journal_mode.add_argument("--db", default=None, metavar="PATH",
  192. help="Convert another Hermes SQLite store (e.g. kanban.db) instead of the profile's state.db")
  193. _flag(sessions_set_journal_mode, "--force",
  194. help="Proceed when the holder scan itself fails (cannot prove the store is quiet) after stopping every "
  195. "Hermes process yourself; a process the scan does find is still refused")
  196. sessions_repair_routing = sessions_subparsers.add_parser(
  197. "repair-routing", help="Re-stamp gateway sessions that lost their routing identity",
  198. description="Find gateway conversations stranded in session rows whose "
  199. "routing identity (session_key/chat_id/origin) was never "
  200. "written — the damage a corrupt state.db write path leaves "
  201. "behind (#82616). Such a row is invisible to restart recovery, "
  202. "so the chat resumes an older session instead. Re-stamps each "
  203. "orphan from the keyed predecessor it continues, and only when "
  204. "that predecessor is unambiguous. Reports without touching the "
  205. "database unless --apply is given.")
  206. _flag(sessions_repair_routing, "--apply", help="Perform the adoptions (default: report only)")
  207. sessions_repair_routing.add_argument("--max-gap-seconds", type=float, default=None,
  208. help="Window between a keyed predecessor's last activity and an "
  209. "orphan's start for them to count as the same conversation "
  210. "(default: 900)")
  211. sessions_repair_profiles = sessions_subparsers.add_parser(
  212. "repair-profiles", help="Settle session/routing state that landed under the wrong profile",
  213. description="Scan every profile's state.db (and the gateway's voice-mode / sessions.json "
  214. "files) for durable state crossed between profiles: rows whose profile_name "
  215. "disagrees with their session key, rows sitting in another profile's store, "
  216. "parent links crossing namespaces, routing rows outside the default store or for a "
  217. "profile that no longer exists, and Telegram topic / voice-mode entries missing "
  218. "their bot's profile. Reports without touching anything unless --apply is given; "
  219. "--apply refuses while a gateway is running, snapshots every store first, and is "
  220. "safe to re-run.")
  221. _flag(sessions_repair_profiles, "--apply", help="Perform the repairs (default: report only)")
  222. _flag(sessions_repair_profiles, "--json", help="Machine-readable report")
  223. _flag(sessions_repair_profiles, "--yes", "-y", default=False, help="Skip the confirmation prompt")
  224. sessions_repair_profiles.add_argument(
  225. "--legacy-main", choices=("report", "rekey", "move"), default="report",
  226. help="What to do with agent:main rows found inside a named profile's store: 'rekey' them "
  227. "to that profile (a standalone gateway's own history, e.g. after multiplexing was "
  228. "switched on), 'move' them to the default store (a default chat that leaked in), or "
  229. "'report' (default) — the rows themselves cannot tell the two cases apart")
  230. sessions_repair_prompts = sessions_subparsers.add_parser(
  231. "repair-prompts", help="Report or clear stored system prompts degraded to a reduced-toolset build",
  232. description="Repair session rows degraded by the pre-#122822 gateway hygiene/compress bug. "
  233. "Automatic repair requires positive tools[] evidence; rows without a readable pin are "
  234. "reported as unverifiable and never changed by a scan. Clearing a prompt makes the next "
  235. "turn rebuild and persist healthy bytes. Reports without touching anything unless --apply "
  236. "is given; a session_id is an explicit destructive override and can clear even a healthy prompt.")
  237. _flag(sessions_repair_prompts, "--apply", help="Clear the verified prompts (default: report only)")
  238. _flag(sessions_repair_prompts, "--json",
  239. help="Machine-readable output; with --apply, apply without an interactive confirmation")
  240. sessions_repair_prompts.add_argument("session_id", nargs="?", default=None,
  241. help="Destructive override: clear this session even when its stored prompt is healthy")
  242. _add_refresh_prompts(sessions_subparsers)
  243. sessions_recover = sessions_subparsers.add_parser(
  244. "recover", help="Rebuild canonical session data into a separate clean database",
  245. description="Offline, non-destructive recovery for a damaged state.db. The "
  246. "source database and its WAL/SHM/rollback-journal sidecars are "
  247. "copied before SQLite opens anything. Canonical rows are rebuilt "
  248. "into a new output database; derived search indexes are recreated "
  249. "and the active database is never replaced automatically.")
  250. sessions_recover.add_argument("--source", type=Path, required=True,
  251. help="Source state.db or preserved backup to inspect/recover")
  252. sessions_recover.add_argument(
  253. "--output", type=Path, help="New recovery database path (required unless --inspect-only)")
  254. _flag(sessions_recover, "--inspect-only",
  255. help="Only report canonical table readability; do not create an output database")
  256. sessions_recover.add_argument("--work-dir", type=Path,
  257. help="Existing directory for the disposable source copy (defaults beside the output)")
  258. sessions_recover.add_argument("--chunk-size", type=int, default=1000,
  259. help="Rows committed per recovery batch (default: 1000)")
  260. _flag(sessions_recover, "--allow-partial",
  261. help="Best-effort salvage across damaged row ranges; the output remains "
  262. "separate and every skipped range is recorded")
  263. sessions_recover.add_argument(
  264. "--report", type=Path, help="JSON report path (defaults to <output>.recovery.json)")
  265. sessions_subparsers.add_parser("stats", help="Show session store statistics")
  266. _add_rename_and_discard(sessions_subparsers)
  267. sessions_pin = sessions_subparsers.add_parser(
  268. "pin", help="Pin session(s) — durable keep flag, exempt from auto-archive",
  269. description="Set the durable 'keep' flag on one or more sessions. Pinned "
  270. "sessions are exempt from the sessions.auto_archive stale sweep "
  271. "and always appear in listings. The same flag drives the Desktop "
  272. "sidebar's Pinned section — pin from either surface, both see it.")
  273. sessions_pin.add_argument(
  274. "session_ids", nargs="+", help="Session ID(s) or unique prefix(es) to pin")
  275. sessions_unpin = sessions_subparsers.add_parser(
  276. "unpin", help="Remove the pin (durable keep flag) from session(s)")
  277. sessions_unpin.add_argument(
  278. "session_ids", nargs="+", help="Session ID(s) or unique prefix(es) to unpin")
  279. sessions_pinned = sessions_subparsers.add_parser("pinned", help="List pinned sessions")
  280. add_json_flag(sessions_pinned, "Emit machine-readable JSON (for backup/restore scripting)")
  281. sessions_retitle = sessions_subparsers.add_parser(
  282. "retitle-skills", help="Re-title sessions whose auto-title came from a /skill's own text",
  283. description="Sessions opened with a /skill were auto-titled from the expanded "
  284. "message, which embeds the whole skill body — so the title "
  285. "describes the SKILL, not the request. This regenerates those "
  286. "titles from what the user actually typed. Lists what it would "
  287. "change unless --apply is passed.")
  288. _flag(sessions_retitle, "--apply", help="Write the new titles (default: dry run)")
  289. sessions_retitle.add_argument(
  290. "--limit", type=int, default=200, help="Maximum sessions to examine (default: 200)")
  291. sessions_browse = sessions_subparsers.add_parser(
  292. "browse", help="Interactive session picker — browse, search, and resume sessions")
  293. sessions_browse.add_argument("--source", help="Filter by source (cli, telegram, discord, etc.)")
  294. sessions_browse.add_argument(
  295. "--limit", type=int, default=500, help="Max sessions to load (default: 500)")
  296. sessions_import = sessions_subparsers.add_parser(
  297. "import", help="Import a Claude Code or Codex CLI session into Hermes",
  298. description="Pull a conversation started in Claude Code (~/.claude/projects) "
  299. "or Codex CLI (~/.codex/sessions) into the Hermes session store "
  300. "so it can be resumed with 'hermes --resume <id>'. The foreign "
  301. "files are only read, never modified.")
  302. sessions_import.add_argument("--from", dest="from_source", choices=["claude", "codex"],
  303. help="Which tool to import from (default: pick across both)")
  304. sessions_import.add_argument(
  305. "path", nargs="?", help="Path to a specific session JSONL file (skips the picker)")
  306. # cmd_sessions lives in hermes_cli/sessions_cmd.py; the parser is threaded
  307. # in because the fallthrough branch calls sessions_parser.print_help().
  308. # main() injects a lazy indirection so sessions_cmd is only imported when
  309. # the subcommand runs.
  310. def _dispatch_sessions(_args, *, sessions_parser=sessions_parser):
  311. return cmd_sessions(_args, sessions_parser=sessions_parser)
  312. sessions_parser.set_defaults(func=_dispatch_sessions)