import os, sys, sqlite3 from typing import Optional, Any from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext from lib_py.verify_session import workspace_key class HermesAgentAdapter(BaseAgentAdapter): @property def name(self) -> str: return 'hermes' @property def own_key(self) -> str: return 'hermes_conversation_id_own' @property def ready_tokens(self) -> str: return 'Hermes' @property def exit_key(self) -> str: return '/exit' @property def delegate_agent_key(self) -> str: return 'hermes-agent' @property def identity_cache_fields(self) -> tuple: return ('session_id',) def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str: return f"{ctx.home_dir}/.hermes/sessions/session_{uuid}.json" def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool: hdb = f"{ctx.home_dir}/.hermes/state.db" if not os.path.exists(hdb): return False if ctx.epoch and os.path.getmtime(hdb) < ctx.epoch: return False try: conn = sqlite3.connect(hdb) r = conn.execute("SELECT cwd FROM sessions WHERE id=?", (uuid,)).fetchone() conn.close() if not r: return False found_cwd = r[0] if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd): return False except Exception: return False return True def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> list: purged = [] json_file = self.artifact_path(uuid, ctx) if os.path.exists(json_file): os.remove(json_file) purged.append(json_file) hdb = f"{ctx.home_dir}/.hermes/state.db" if os.path.exists(hdb): try: conn = sqlite3.connect(hdb) conn.execute("DELETE FROM sessions WHERE id=?", (uuid,)) conn.execute("DELETE FROM messages WHERE session_id=?", (uuid,)) conn.commit() conn.close() purged.append(f"db records for session: {uuid}") except Exception as e: sys.stderr.write(f"WARN: purge hermes db records failed: {e}\n") return purged def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str: return binary def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str: if materialized and session_uuid: return f"{binary} --resume {session_uuid}" return binary def auth_ok(self, run_cmd: Optional[Any] = None) -> bool: return True def discover(self, ctx: DiscoveryContext) -> list: hdb = f"{ctx.home_dir}/.hermes/state.db" if os.path.exists(hdb): try: conn = sqlite3.connect(hdb) r = conn.execute("SELECT id FROM sessions WHERE cwd=? ORDER BY started_at DESC LIMIT 1", (ctx.workspace,)).fetchone() conn.close() if r: cand = r[0] if cand and self.verify_artifact(cand, ctx): return [cand] except Exception: pass return []