|
| 1 | +"""Hermes Agent provider. Reads ~/.hermes/state.db directly. |
| 2 | +
|
| 3 | +Hermes (Nous Research) stores all sessions in one SQLite DB: |
| 4 | +- sessions(id, model, started_at, message_count, tool_call_count, title, ...) |
| 5 | +- messages(id, session_id, role, content, tool_calls, timestamp, ...) |
| 6 | +
|
| 7 | +Schema docs: https://hermes-agent.nousresearch.com/docs/developer-guide/session-storage |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import json |
| 12 | +import sqlite3 |
| 13 | +from collections.abc import Iterator |
| 14 | +from datetime import UTC, datetime |
| 15 | +from pathlib import Path |
| 16 | + |
| 17 | +from .common import utcnow_iso |
| 18 | +from .config import HERMES_DB_PATH |
| 19 | +from .transcript import Turn |
| 20 | + |
| 21 | + |
| 22 | +def _connect(path: Path) -> sqlite3.Connection: |
| 23 | + conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True) |
| 24 | + conn.row_factory = sqlite3.Row |
| 25 | + return conn |
| 26 | + |
| 27 | + |
| 28 | +def _epoch_to_iso(ts: float | None) -> str | None: |
| 29 | + if ts is None: |
| 30 | + return None |
| 31 | + try: |
| 32 | + return datetime.fromtimestamp(float(ts), UTC).isoformat() |
| 33 | + except (ValueError, TypeError, OSError): |
| 34 | + return None |
| 35 | + |
| 36 | + |
| 37 | +def list_hermes_sessions(db_path: Path = HERMES_DB_PATH) -> list[dict]: |
| 38 | + """Return session records; shape compatible with SessionRecord fields.""" |
| 39 | + if not db_path.exists(): |
| 40 | + return [] |
| 41 | + out: list[dict] = [] |
| 42 | + with _connect(db_path) as conn: |
| 43 | + rows = conn.execute( |
| 44 | + """ |
| 45 | + SELECT s.id, s.model, s.started_at, s.ended_at, |
| 46 | + s.message_count, s.tool_call_count, s.title, |
| 47 | + (SELECT content FROM messages |
| 48 | + WHERE session_id = s.id AND role = 'user' |
| 49 | + ORDER BY timestamp ASC LIMIT 1) AS first_prompt, |
| 50 | + (SELECT content FROM messages |
| 51 | + WHERE session_id = s.id AND role = 'user' |
| 52 | + ORDER BY timestamp DESC LIMIT 1) AS last_prompt, |
| 53 | + (SELECT MAX(timestamp) FROM messages |
| 54 | + WHERE session_id = s.id) AS last_msg_ts |
| 55 | + FROM sessions s |
| 56 | + ORDER BY s.started_at DESC |
| 57 | + """ |
| 58 | + ).fetchall() |
| 59 | + stat = db_path.stat() |
| 60 | + for r in rows: |
| 61 | + started = _epoch_to_iso(r["started_at"]) |
| 62 | + last_act = _epoch_to_iso(r["last_msg_ts"] or r["started_at"]) |
| 63 | + out.append({ |
| 64 | + "id": r["id"], |
| 65 | + "tool": "hermes", |
| 66 | + "path": f"hermes://{r['id']}", |
| 67 | + "cwd": None, |
| 68 | + "started_at": started, |
| 69 | + "last_activity": last_act, |
| 70 | + "mtime": stat.st_mtime, # shared DB mtime — not per-session |
| 71 | + "size": 0, |
| 72 | + "message_count": r["message_count"] or 0, |
| 73 | + "tool_call_count": r["tool_call_count"] or 0, |
| 74 | + "model": r["model"], |
| 75 | + "first_prompt": r["first_prompt"], |
| 76 | + "last_prompt": r["last_prompt"], |
| 77 | + "codex_summary": None, |
| 78 | + "native_title": r["title"], |
| 79 | + "indexed_at": utcnow_iso(), |
| 80 | + }) |
| 81 | + return out |
| 82 | + |
| 83 | + |
| 84 | +def iter_hermes_turns(session_id: str, |
| 85 | + db_path: Path = HERMES_DB_PATH) -> Iterator[Turn]: |
| 86 | + if not db_path.exists(): |
| 87 | + return |
| 88 | + with _connect(db_path) as conn: |
| 89 | + rows = conn.execute( |
| 90 | + """ |
| 91 | + SELECT role, content, tool_calls, tool_name, timestamp |
| 92 | + FROM messages |
| 93 | + WHERE session_id = :id |
| 94 | + ORDER BY timestamp ASC |
| 95 | + """, |
| 96 | + {"id": session_id}, |
| 97 | + ).fetchall() |
| 98 | + for r in rows: |
| 99 | + role = r["role"] |
| 100 | + ts = _epoch_to_iso(r["timestamp"]) |
| 101 | + if role in ("user", "assistant") and r["content"]: |
| 102 | + yield Turn(role, r["content"], {"ts": ts}) |
| 103 | + if r["tool_calls"]: |
| 104 | + try: |
| 105 | + tcs = json.loads(r["tool_calls"]) |
| 106 | + except (ValueError, TypeError): |
| 107 | + tcs = [] |
| 108 | + if isinstance(tcs, list): |
| 109 | + for tc in tcs: |
| 110 | + if not isinstance(tc, dict): |
| 111 | + continue |
| 112 | + fn = (tc.get("function") or {}) |
| 113 | + args = fn.get("arguments") or tc.get("arguments") or {} |
| 114 | + if isinstance(args, str): |
| 115 | + try: |
| 116 | + args = json.loads(args) |
| 117 | + except ValueError: |
| 118 | + pass |
| 119 | + name = fn.get("name") or tc.get("name") or r["tool_name"] |
| 120 | + body = json.dumps(args, indent=2) if not isinstance(args, str) else args |
| 121 | + yield Turn("tool_use", body[:4000], {"name": name, "ts": ts}) |
| 122 | + if role == "tool" and r["content"]: |
| 123 | + yield Turn("tool_result", str(r["content"])[:4000], |
| 124 | + {"name": r["tool_name"], "ts": ts}) |
0 commit comments