Home / Skills / fathah/hermes-desktop

hermes-agent

Expert in building self-improving AI agents with tool use, multi-platform messaging, and a closed learning loop. Proficient in LLM orchestration, tool integration, session management, and agent autonomy.

skillLicense: MIT Source: fathah/hermes-desktop

Install

Copy this folder into your Claude Code project (needs Node.js):

npx degit fathah/hermes-desktop/.agents/skills/hermes-agent .claude/skills/hermes-agent

Or install it for every project:

npx degit fathah/hermes-desktop/.agents/skills/hermes-agent ~/.claude/skills/hermes-agent

File content

Made by its original authors and shared under MIT. We show it unchanged, with credit and a link to the source. Source β†—

---
name: hermes-agent
description: Expert in building self-improving AI agents with tool use, multi-platform messaging, and a closed learning loop. Proficient in LLM orchestration, tool integration, session management, and agent autonomy.
---

# Hermes Agent - Complete Project Guide (A-Z)

> **Purpose of this document:** A single, comprehensive reference that explains everything about the Hermes Agent project β€” its architecture, source code, features, release history, and design patterns β€” so that any AI or developer can fully understand the system.

---

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Key Features Summary](#2-key-features-summary)
3. [Installation & Getting Started](#3-installation--getting-started)
4. [Project Structure](#4-project-structure)
5. [Core Architecture](#5-core-architecture)
   - 5.1 [AIAgent Class (run_agent.py)](#51-aiagent-class-run_agentpy)
   - 5.2 [Tool Orchestration (model_tools.py)](#52-tool-orchestration-model_toolspy)
   - 5.3 [Toolset System (toolsets.py)](#53-toolset-system-toolsetspy)
   - 5.4 [Tool Registry (tools/registry.py)](#54-tool-registry-toolsregistrypy)
   - 5.5 [Session Database (hermes_state.py)](#55-session-database-hermes_statepy)
   - 5.6 [Constants & Home Directory (hermes_constants.py)](#56-constants--home-directory-hermes_constantspy)
6. [CLI System](#6-cli-system)
   - 6.1 [Interactive CLI (cli.py)](#61-interactive-cli-clipy)
   - 6.2 [CLI Entry Point (hermes_cli/main.py)](#62-cli-entry-point-hermes_climainpy)
   - 6.3 [Configuration System (hermes_cli/config.py)](#63-configuration-system-hermes_cliconfigpy)
   - 6.4 [Slash Command Registry (hermes_cli/commands.py)](#64-slash-command-registry-hermes_clicommandspy)
   - 6.5 [Setup Wizard (hermes_cli/setup.py)](#65-setup-wizard-hermes_clisetupy)
   - 6.6 [Model Catalog (hermes_cli/models.py)](#66-model-catalog-hermes_climodelspy)
   - 6.7 [Skin/Theme Engine (hermes_cli/skin_engine.py)](#67-skintheme-engine-hermes_cliskin_enginepy)
7. [Tool System](#7-tool-system)
   - 7.1 [Terminal Tool (tools/terminal_tool.py)](#71-terminal-tool-toolsterminal_toolpy)
   - 7.2 [File Tools (tools/file_tools.py)](#72-file-tools-toolsfile_toolspy)
   - 7.3 [Web Tools (tools/web_tools.py)](#73-web-tools-toolsweb_toolspy)
   - 7.4 [Browser Tool (tools/browser_tool.py)](#74-browser-tool-toolsbrowser_toolpy)
   - 7.5 [Delegate Tool (tools/delegate_tool.py)](#75-delegate-tool-toolsdelegate_toolpy)
   - 7.6 [MCP Tool (tools/mcp_tool.py)](#76-mcp-tool-toolsmcp_toolpy)
   - 7.7 [Approval System (tools/approval.py)](#77-approval-system-toolsapprovalpy)
   - 7.8 [Terminal Backends (tools/environments/)](#78-terminal-backends-toolsenvironments)
8. [Agent Internals](#8-agent-internals)
   - 8.1 [Prompt Builder (agent/prompt_builder.py)](#81-prompt-builder-agentprompt_builderpy)
   - 8.2 [Context Compressor (agent/context_compressor.py)](#82-context-compressor-agentcontext_compressorpy)
   - 8.3 [Prompt Caching (agent/prompt_caching.py)](#83-prompt-caching-agentprompt_cachingpy)
   - 8.4 [Auxiliary Client (agent/auxiliary_client.py)](#84-auxiliary-client-agentauxiliary_clientpy)
   - 8.5 [Display & Spinner (agent/display.py)](#85-display--spinner-agentdisplaypy)
   - 8.6 [Skill Commands (agent/skill_commands.py)](#86-skill-commands-agentskill_commandspy)
9. [Messaging Gateway](#9-messaging-gateway)
   - 9.1 [GatewayRunner (gateway/run.py)](#91-gatewayrunner-gatewayrunpy)
   - 9.2 [Session Store (gateway/session.py)](#92-session-store-gatewaysessionpy)
   - 9.3 [Platform Adapters (gateway/platforms/)](#93-platform-adapters-gatewayplatforms)
10. [Cron Scheduling](#10-cron-scheduling)
11. [Skills System](#11-skills-system)
12. [Plugin System](#12-plugin-system)
13. [Memory System](#13-memory-system)
14. [ACP Server (IDE Integration)](#14-acp-server-ide-integration)
15. [API Server](#15-api-server)
16. [MCP Server Mode](#16-mcp-server-mode)
17. [RL Training Environments](#17-rl-training-environments)
18. [Profiles (Multi-Instance)](#18-profiles-multi-instance)
19. [Security Model](#19-security-model)
20. [Provider & Model System](#20-provider--model-system)
21. [Streaming & Reasoning](#21-streaming--reasoning)
22. [Release History](#22-release-history)
23. [File Dependency Chain](#23-file-dependency-chain)
24. [Key Design Patterns](#24-key-design-patterns)
25. [Configuration Reference](#25-configuration-reference)
26. [Known Pitfalls](#26-known-pitfalls)

---

## 1. Project Overview

**Hermes Agent** is a self-improving AI agent built by [Nous Research](https://nousresearch.com). It is an open-source (MIT licensed), Python-based project that provides:

- A **full interactive terminal UI** (CLI) for conversing with LLMs
- A **messaging gateway** supporting 16+ platforms (Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, etc.)
- A **closed learning loop** β€” the agent creates skills from experience, improves them during use, nudges itself to persist knowledge, searches past conversations, and builds a deepening model of who you are
- **40+ built-in tools** β€” terminal execution, file manipulation, web search, browser automation, code execution, image generation, TTS/STT, and more
- **Any LLM provider** β€” OpenRouter (200+ models), Nous Portal (400+ models), OpenAI, Anthropic, Hugging Face, GitHub Copilot, z.ai/GLM, Kimi/Moonshot, MiniMax, Alibaba/DashScope, custom endpoints
- **Six terminal backends** β€” local, Docker, SSH, Modal (serverless), Daytona (serverless), Singularity (HPC)
- **Scheduled automations** via built-in cron scheduler
- **IDE integration** via ACP (Agent Communication Protocol) for VS Code, Zed, JetBrains
- **MCP integration** β€” both client (connect to any MCP server) and server (expose Hermes to MCP clients)
- **RL training** via Atropos environments for training the next generation of tool-calling models

**Tech Stack:**

- Python 3.11+ (core agent, tools, gateway, cron)
- Node.js (browser automation via agent-browser)
- SQLite with WAL mode and FTS5 (session storage, full-text search)
- OpenAI-compatible API (primary inference interface)
- Anthropic SDK (native Anthropic support)
- Rich + prompt_toolkit (CLI rendering)

**Repository:** `github.com/NousResearch/hermes-agent`
**Version:** 0.7.0 (as of April 2026)
**License:** MIT

---

## 2. Key Features Summary

| Feature                      | Description                                                                                                                                                                      |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Terminal UI**              | Full TUI with multiline editing, slash-command autocomplete, conversation history, interrupt-and-redirect, streaming tool output                                                 |
| **Multi-Platform Messaging** | Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, Home Assistant, DingTalk, Feishu/Lark, WeCom, Mattermost, SMS, Webhook β€” all from a single gateway process            |
| **Learning Loop**            | Agent-curated memory with periodic nudges, autonomous skill creation, skills self-improve during use, FTS5 session search with LLM summarization, Honcho dialectic user modeling |
| **Scheduled Tasks**          | Built-in cron scheduler with delivery to any platform (daily reports, nightly backups, weekly audits)                                                                            |
| **Subagent Delegation**      | Spawn isolated subagents for parallel workstreams with restricted toolsets                                                                                                       |
| **Execute Code**             | Python scripts that call tools via RPC, collapsing multi-step pipelines into zero-context-cost turns                                                                             |
| **Terminal Backends**        | Local, Docker, SSH, Modal, Daytona, Singularity β€” run on a $5 VPS or a GPU cluster                                                                                               |
| **Skills**                   | 70+ bundled skills across 28 categories, Skills Hub for community discovery, agentskills.io compatibility                                                                        |
| **Plugins**                  | Drop-in Python plugins with lifecycle hooks (pre_llm_call, post_llm_call, on_session_start, on_session_end)                                                                      |
| **MCP**                      | Client (connect to MCP servers for extended tools) and Server (expose conversations to MCP clients)                                                                              |
| **IDE Integration**          | VS Code, Zed, JetBrains via ACP server with session management and tool streaming                                                                                                |
| **API Server**               | OpenAI-compatible `/v1/chat/completions` endpoint for headless integrations                                                                                                      |
| **Profiles**                 | Multi-instance support β€” each profile gets isolated config, memory, sessions, skills, gateway                                                                                    |
| **Security**                 | Command approval system, secret redaction, SSRF protection, PII redaction, injection detection, credential directory protection                                                  |
| **RL Training**              | Atropos environments for batch trajectory generation and agent policy optimization                                                                                               |

---

## 3. Installation & Getting Started

```bash
# One-line install (Linux, macOS, WSL2)
curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash

# After install
source ~/.bashrc    # or: source ~/.zshrc
hermes              # start chatting

# Key commands
hermes model        # Choose LLM provider and model
hermes tools        # Configure which tools are enabled
hermes config set   # Set individual config values
hermes gateway      # Start the messaging gateway
hermes setup        # Run the full setup wizard
hermes update       # Update to latest version
hermes doctor       # Diagnose any issues
```

**For development:**

```bash
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv venv --python 3.11
source venv/bin/activate
uv pip install -e ".[all,dev]"
python -m pytest tests/ -q    # ~3000 tests
```

---

## 4. Project Structure

```
hermes-agent/
β”œβ”€β”€ run_agent.py              # AIAgent class β€” core conversation loop
β”œβ”€β”€ model_tools.py            # Tool orchestration, _discover_tools(), handle_function_call()
β”œβ”€β”€ toolsets.py               # Toolset definitions, _HERMES_CORE_TOOLS list
β”œβ”€β”€ toolset_distributions.py  # Toolset sampling distributions for RL
β”œβ”€β”€ cli.py                    # HermesCLI class β€” interactive CLI orchestrator
β”œβ”€β”€ hermes_state.py           # SessionDB β€” SQLite session store (FTS5 search)
β”œβ”€β”€ hermes_constants.py       # Shared constants, get_hermes_home()
β”œβ”€β”€ hermes_time.py            # Timezone handling
β”œβ”€β”€ utils.py                  # Shared utility functions
β”œβ”€β”€ batch_runner.py           # Parallel batch processing
β”œβ”€β”€ trajectory_compressor.py  # Trajectory compression for RL training
β”œβ”€β”€ mcp_serve.py              # MCP server mode entry point
β”œβ”€β”€ mini_swe_runner.py        # Minimal SWE benchmark runner
β”œβ”€β”€ rl_cli.py                 # RL CLI commands
β”‚
β”œβ”€β”€ agent/                    # Agent internals
β”‚   β”œβ”€β”€ prompt_builder.py         # System prompt assembly
β”‚   β”œβ”€β”€ context_compressor.py     # Auto context compression
β”‚   β”œβ”€β”€ prompt_caching.py         # Anthropic prompt caching
β”‚   β”œβ”€β”€ auxiliary_client.py       # Auxiliary LLM client (vision, summarization)
β”‚   β”œβ”€β”€ model_metadata.py         # Model context lengths, token estimation
β”‚   β”œβ”€β”€ models_dev.py             # models.dev registry integration
β”‚   β”œβ”€β”€ display.py                # KawaiiSpinner, tool preview formatting
β”‚   β”œβ”€β”€ skill_commands.py         # Skill slash commands (shared CLI/gateway)
β”‚   └── trajectory.py             # Trajectory saving helpers
β”‚
β”œβ”€β”€ hermes_cli/               # CLI subcommands and setup
β”‚   β”œβ”€β”€ main.py               # Entry point β€” all `hermes` subcommands
β”‚   β”œβ”€β”€ config.py             # DEFAULT_CONFIG, OPTIONAL_ENV_VARS, migration
β”‚   β”œβ”€β”€ commands.py           # Slash command definitions + SlashCommandCompleter
β”‚   β”œβ”€β”€ callbacks.py          # Terminal callbacks (clarify, sudo, approval)
β”‚   β”œβ”€β”€ setup.py              # Interactive setup wizard
β”‚   β”œβ”€β”€ skin_engine.py        # Skin/theme engine
β”‚   β”œβ”€β”€ skills_config.py      # `hermes skills` β€” skill management
β”‚   β”œβ”€β”€ tools_config.py       # `hermes tools` β€” tool management
β”‚   β”œβ”€β”€ skills_hub.py         # Skills Hub integration
β”‚   β”œβ”€β”€ models.py             # Model catalog, provider model lists
β”‚   β”œβ”€β”€ model_switch.py       # Shared /model switch pipeline
β”‚   └── auth.py               # Provider credential resolution
β”‚
β”œβ”€β”€ tools/                    # Tool implementations (one file per tool)
β”‚   β”œβ”€β”€ registry.py           # Central tool registry
β”‚   β”œβ”€β”€ approval.py           # Dangerous command detection
β”‚   β”œβ”€β”€ terminal_tool.py      # Terminal/shell execution
β”‚   β”œβ”€β”€ process_registry.py   # Background process management
β”‚   β”œβ”€β”€ file_tools.py         # File read/write/search/patch
β”‚   β”œβ”€β”€ web_tools.py          # Web search/extract
β”‚   β”œβ”€β”€ browser_tool.py       # Browser automation
β”‚   β”œβ”€β”€ code_execution_tool.py # execute_code sandbox
β”‚   β”œβ”€β”€ delegate_tool.py      # Subagent delegation
β”‚   β”œβ”€β”€ mcp_tool.py           # MCP client integration
β”‚   β”œβ”€β”€ skills_tool.py        # Skill management tool
β”‚   β”œβ”€β”€ todo_tool.py          # Todo/task tracking tool
β”‚   β”œβ”€β”€ memory_tool.py        # Memory read/write tool
β”‚   β”œβ”€β”€ tts_tool.py           # Text-to-speech
β”‚   β”œβ”€β”€ vision_tool.py        # Image analysis
β”‚   β”œβ”€β”€ image_gen_tool.py     # Image generation
β”‚   └── environments/         # Terminal backends
β”‚       β”œβ”€β”€ base.py               # BaseEnvironment ABC
β”‚       β”œβ”€β”€ local.py              # Local execution
β”‚       β”œβ”€β”€ docker.py             # Docker containers
β”‚       β”œβ”€β”€ ssh.py                # SSH remote execution
β”‚       β”œβ”€β”€ modal.py              # Modal serverless
β”‚       β”œβ”€β”€ managed_modal.py      # Nous-hosted Modal
β”‚       β”œβ”€β”€ daytona.py            # Daytona serverless
β”‚       β”œβ”€β”€ singularity.py        # Singularity HPC containers
β”‚       └── persistent_shell.py   # Persistent shell mixin
β”‚
β”œβ”€β”€ gateway/                  # Messaging platform gateway
β”‚   β”œβ”€β”€ run.py                # GatewayRunner β€” main message loop
β”‚   β”œβ”€β”€ session.py            # SessionStore β€” conversation persistence
β”‚   β”œβ”€β”€ status.py             # Gateway status, token locks
β”‚   └── platforms/            # 16 platform adapters
β”‚       β”œβ”€β”€ base.py               # BasePlatformAdapter ABC
β”‚       β”œβ”€β”€ telegram.py           # Telegram (polling + webhook)
β”‚       β”œβ”€β”€ discord.py            # Discord
β”‚       β”œβ”€β”€ slack.py              # Slack
β”‚       β”œβ”€β”€ whatsapp.py           # WhatsApp
β”‚       β”œβ”€β”€ matrix.py             # Matrix (E2EE)
β”‚       β”œβ”€β”€ signal.py             # Signal
β”‚       β”œβ”€β”€ email.py              # Email (IMAP/SMTP)
β”‚       β”œβ”€β”€ homeassistant.py      # Home Assistant
β”‚       β”œβ”€β”€ sms.py                # SMS (Twilio)
β”‚       β”œβ”€β”€ mattermost.py         # Mattermost
β”‚       β”œβ”€β”€ dingtalk.py           # DingTalk
β”‚       β”œβ”€β”€ feishu.py             # Feishu/Lark
β”‚       β”œβ”€β”€ wecom.py              # WeCom (Enterprise WeChat)
β”‚       β”œβ”€β”€ webhook.py            # Generic webhook
β”‚       └── api_server.py         # OpenAI-compatible API server
β”‚
β”œβ”€β”€ acp_adapter/              # ACP server (IDE integration)
β”‚   β”œβ”€β”€ server.py             # HermesACPAgent class
β”‚   β”œβ”€β”€ session.py            # SessionManager
β”‚   β”œβ”€β”€ events.py             # Streaming callbacks
β”‚   β”œβ”€β”€ permissions.py        # Approval callbacks
β”‚   └── entry.py              # Entry point
β”‚
β”œβ”€β”€ cron/                     # Scheduler
β”‚   β”œβ”€β”€ scheduler.py          # tick() β€” job execution engine
β”‚   └── jobs.py               # Job storage and CRUD
β”‚
β”œβ”€β”€ plugins/                  # Plugin system
β”‚   └── memory/               # 8 memory provider plugins
β”‚       β”œβ”€β”€ openviking/
β”‚       β”œβ”€β”€ mem0/
β”‚       β”œβ”€β”€ hindsight/
β”‚       β”œβ”€β”€ holographic/
β”‚       β”œβ”€β”€ honcho/
β”‚       β”œβ”€β”€ retaindb/
β”‚       └── byterover/
β”‚
β”œβ”€β”€ environments/             # RL training environments (Atropos)
β”‚   β”œβ”€β”€ hermes_base_env.py    # Abstract base RL environment
β”‚   β”œβ”€β”€ agent_loop.py         # HermesAgentLoop β€” rollout execution
β”‚   β”œβ”€β”€ tool_context.py       # ToolContext β€” sandbox for RL
β”‚   β”œβ”€β”€ web_research_env.py   # Web research tasks
β”‚   └── agentic_opd_env.py    # Observation-Prediction-Demo env
β”‚
β”œβ”€β”€ skills/                   # 70+ bundled skills across 28 categories
β”œβ”€β”€ optional-skills/          # Additional optional skills
β”œβ”€β”€ tests/                    # ~3000 pytest tests
β”œβ”€β”€ scripts/                  # Install, update, packaging scripts
β”œβ”€β”€ docker/                   # Docker build files
β”œβ”€β”€ docs/                     # Documentation source (Docusaurus)
β”œβ”€β”€ website/                  # Landing page
β”œβ”€β”€ desktop/                  # Desktop app (Electron, separate repo)
β”œβ”€β”€ tinker-atropos/           # RL submodule
β”‚
β”œβ”€β”€ pyproject.toml            # Python package config
β”œβ”€β”€ AGENTS.md                 # Developer guide for AI assistants
β”œβ”€β”€ RELEASE_v0.2.0.md β†’ v0.7.0.md  # Release notes
└── cli-config.yaml.example   # Example config
```

**User config directory:** `~/.hermes/`

```
~/.hermes/
β”œβ”€β”€ config.yaml           # User settings
β”œβ”€β”€ .env                  # API keys and secrets
β”œβ”€β”€ MEMORY.md             # Persistent agent memory
β”œβ”€β”€ USER.md               # User profile
β”œβ”€β”€ SOUL.md               # Agent personality/identity
β”œβ”€β”€ sessions.db           # SQLite session database
β”œβ”€β”€ skills/               # User-installed skills
β”œβ”€β”€ skins/                # Custom CLI themes
β”œβ”€β”€ plugins/              # User plugins
β”œβ”€β”€ cron/                 # Cron jobs and output
β”‚   β”œβ”€β”€ jobs.json
β”‚   └── output/
β”œβ”€β”€ cache/                # Image/audio cache
β”œβ”€β”€ plans/                # Generated plans
β”œβ”€β”€ profiles/             # Multi-instance profiles
└── mcp/                  # MCP server configs
```

---

## 5. Core Architecture

### 5.1 AIAgent Class (run_agent.py)

The `AIAgent` class is the heart of the system β€” the core conversation loop that orchestrates LLM calls, tool execution, context management, and response delivery.

**Constructor (~60 parameters):**

```python
class AIAgent:
    def __init__(self,
        model: str = "anthropic/claude-opus-4.6",
        max_iterations: int = 90,
        enabled_toolsets: list = None,
        disabled_toolsets: list = None,
        quiet_mode: bool = False,
        save_trajectories: bool = False,
        platform: str = None,            # "cli", "telegram", etc.
        session_id: str = None,
        session_db: SessionDB = None,
        skip_context_files: bool = False,
        skip_memory: bool = False,
        base_url: str = None,
        api_key: str = None,
        provider: str = None,
        api_mode: str = "chat_completions",  # or "anthropic_messages" or "codex_responses"
        tool_progress_callback = None,
        stream_delta_callback = None,
        thinking_callback = None,
        status_callback = None,
        iteration_budget: IterationBudget = None,
        credential_pool = None,
        checkpoints_enabled: bool = False,
        # ... plus provider, routing, callback params
    )
```

**Main Methods:**

| Method                                                                          | Returns  | Purpose                                                                            |
| ------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------- |
| `chat(message, stream_callback)`                                                | `str`    | Simple interface β€” returns final response text                                     |
| `run_conversation(user_message, system_message, conversation_history, task_id)` | `dict`   | Full interface β€” returns `{final_response, messages, completed, api_calls, error}` |
| `_interruptible_api_call(api_kwargs)`                                           | Response | Runs API request in background thread with interrupt support                       |
| `_interruptible_streaming_api_call(api_kwargs, on_first_delta)`                 | Response | Streaming variant with delta callbacks                                             |

**The Core Agent Loop** (inside `run_conversation()`):

```python
while api_call_count < self.max_iterations and self.iteration_budget.remaining > 0:
    response = client.chat.completions.create(
        model=model, messages=messages, tools=tool_schemas
    )
    if response.tool_calls:
        for tool_call in response.tool_calls:
            result = handle_function_call(tool_call.name, tool_call.args, task_id)
            messages.append(tool_result_message(result))
        api_call_count += 1
    else:
        return response.content  # Final text response
```

**Key Behaviors:**

- **Three API modes:** `chat_completions` (OpenAI-compatible), `anthropic_messages` (Anthropic SDK), `codex_responses` (OpenAI Codex)
- **Parallel tool execution:** Independent tool calls run concurrently via ThreadPoolExecutor (unless they share file paths or are in the never-parallel list)
- **Interrupt support:** Background threads allow interrupt detection without blocking on HTTP
- **Error recovery:** Automatic fallback chain (primary β†’ fallback model), retry with exponential backoff, context compression on token overflow
- **Budget pressure:** Warnings at 70% (caution) and 90% (urgent) of iteration budget
- **Oversized results:** Tool results >100K chars are saved to temp files with a preview
- **Stale connection detection:** 90s timeout for streaming, 60s read timeout

**IterationBudget** (thread-safe):

```python
class IterationBudget:
    def consume() -> bool    # Check and consume one iteration
    def refund()             # Give back iteration (for execute_code turns)
    @property remaining      # Remaining iterations
```

---

### 5.2 Tool Orchestration (model_tools.py)

Bridges the agent and tool registry β€” handles discovery, schema generation, and dispatch.

**Key Functions:**

| Function                                                                                | Purpose                                                                   |
| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `_discover_tools()`                                                                     | Imports all tool modules (each calls `registry.register()` on import)     |
| `get_tool_definitions(enabled_toolsets, disabled_toolsets, quiet_mode)`                 | Returns OpenAI-format tool schemas filtered by toolset                    |
| `handle_function_call(function_name, function_args, task_id, user_task, enabled_tools)` | Main dispatcher β€” routes calls to registry with arg coercion              |
| `coerce_tool_args(tool_name, args)`                                                     | Type coercion for LLM-generated arguments (string→int, string→bool, etc.) |

**Tool Discovery Order:**

1. Static tools (web_tools, terminal_tool, file_tools, browser_tool, etc.)
2. Optional tools (fal_client for image gen, honcho, etc.) β€” graceful fallback if missing
3. Plugin-registered tools
4. MCP server tools (dynamic, via tools/list_changed notifications)

**Special Tool Handling:**

- **Agent-level tools** (todo, memory, session_search, delegate_task): Intercepted by `run_agent.py` before `handle_function_call()`
- **execute_code**: Passes `enabled_tools` for sandbox tool list
- **Dynamic schema adjustments**: `browser_navigate` strips web_search reference if tools unavailable

**Async Bridging:**

- Persistent event loops (not `asyncio.run()`) to prevent "Event loop is closed" errors
- Main thread uses shared loop; worker threads get per-thread loops
- `_run_async()` detects running loop and spins up disposable thread if needed

---

### 5.3 Toolset System (toolsets.py)

Provides flexible tool grouping and composition.

**Core Toolsets:**

| Toolset          | Tools Included                                                                                   |
| ---------------- | ------------------------------------------------------------------------------------------------ |
| `web`            | web_search, web_extract, web_crawl                                                               |
| `terminal`       | terminal                                                                                         |
| `file`           | read_file, write_file, edit_file, list_files, search_files                                       |
| `browser`        | browser_navigate, browser_snapshot, browser_click, browser_type, browser_scroll, browser_extract |
| `vision`         | analyze_image                                                                                    |
| `image_gen`      | generate_image                                                                                   |
| `tts`            | text_to_speech                                                                                   |
| `todo`           | todo_read, todo_write                                                                            |
| `memory`         | memory_read, memory_write                                                                        |
| `session_search` | session_search                                                                                   |
| `delegation`     | delegate_task                                                                                    |
| `code_execution` | execute_code                                                                                     |
| `cronjob`        | create_job, list_jobs, delete_job                                                                |
| `messaging`      | send_message                                                                                     |
| `homeassistant`  | ha_get_states, ha_call_service, ...                                                              |

**Composite Toolsets:**

- `hermes-cli` β€” All core tools for CLI platform
- `hermes-telegram`, `hermes-discord`, etc. β€” Platform-specific tool sets
- `hermes-gateway` β€” Union of all platform tools
- `debugging` β€” terminal + file + web
- `safe` β€” Everything except terminal

**Resolution:**

```python
resolve_toolset(name, visited=None) β†’ List[str]
# Recursively resolves toolset to tool names
# Handles composition (includes) and cycle detection
# Special aliases: "all" or "*" = all tools
```

---

### 5.4 Tool Registry (tools/registry.py)

Singleton managing all tool schemas and handlers. Circular-import safe β€” has no tool dependencies.

**ToolEntry** (per-tool metadata):

```python
@dataclass(slots=True)
class ToolEntry:
    name: str
    toolset: str
    schema: dict           # OpenAI-format tool definition
    handler: Callable      # Sync or async handler function
    check_fn: Callable     # Returns True if tool is available
    requires_env: list     # Required environment variables
    is_async: bool
    description: str
    emoji: str
```

**Key Methods:**

```python
registry.register(name, toolset, schema, handler, check_fn, requires_env)
registry.get_definitions(tool_names, quiet)  # Returns filtered schemas
registry.dispatch(name, args, **kwargs)      # Execute with async bridging
registry.deregister(name)                    # Remove (for MCP tool refresh)
registry.check_tool_availability()           # Returns (available, unavailable)
```

---

### 5.5 Session Database (hermes_state.py)

SQLite-based persistent session storage with FTS5 full-text search.

**Schema (v6):**

```sql
-- Sessions table
sessions (
    id TEXT PRIMARY KEY,
    source TEXT, user_id TEXT, model TEXT, model_config TEXT,
    system_prompt TEXT, parent_session_id TEXT,
    started_at TEXT, ended_at TEXT, end_reason TEXT,
    message_count INTEGER, tool_call_count INTEGER,
    input_tokens INTEGER, output_tokens INTEGER,
    cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER,
    estimated_cost_usd REAL, actual_cost_usd REAL,
    title TEXT  -- UNIQUE INDEX
)

-- Messages table
messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id TEXT, role TEXT, content TEXT,
    tool_call_id TEXT, tool_calls TEXT,  -- JSON
    tool_name TEXT, timestamp TEXT,
    token_count INTEGER, finish_reason TEXT,
    reasoning TEXT, reasoning_details TEXT, codex_reasoning_items TEXT
)

-- FTS5 virtual table (auto-synced via triggers)
messages_fts (content)
```

**Concurrency Model:**

- WAL (Write-Ahead Logging) for concurrent readers + single writer
- `BEGIN IMMEDIATE` for write transactions (lock at start, not commit)
- Jitter retry on lock: 20-150ms random backoff, max 15 retries
- Periodic WAL checkpoint every 50 writes

**Key Operations:**

- `create_session()`, `end_session()`, `reopen_session()`
- `add_message()`, `get_messages()`
- `search_sessions(query)` β€” FTS5 full-text search
- `update_token_counts()` β€” Supports both incremental (CLI) and absolute (gateway) modes

---

### 5.6 Constants & Home Directory (hermes_constants.py)

Import-safe constants module with no circular dependencies.

```python
get_hermes_home() β†’ Path          # HERMES_HOME env var or ~/.hermes
display_hermes_home() β†’ str       # User-friendly display: "~/.hermes"
get_optional_skills_dir() β†’ Path  # HERMES_OPTIONAL_SKILLS env var
parse_reasoning_effort(str) β†’ Dict  # "high" β†’ {"enabled": True, "effort": "high"}

# Key constants
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
NOUS_API_BASE_URL = "https://inference-api.nousresearch.com/v1"
AI_GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh/v1"
VALID_REASONING_EFFORTS = ("xhigh", "high", "medium", "low", "minimal")
```

---

## 6. CLI System

### 6.1 Interactive CLI (cli.py)

The `HermesCLI` class provides the interactive terminal interface.

**Features:**

- **Rich** for banner/panels, **prompt_toolkit** for input with autocomplete
- **KawaiiSpinner** β€” animated faces during API calls, `β”Š` activity feed for tool results
- Multiline editing with Shift+Enter
- Slash-command autocomplete
- Session history with up/down arrow navigation
- Clipboard image paste (Alt+V / Ctrl+V)
- Status bar showing model, provider, and token counts
- Inline diff previews for file write/patch operations

**Configuration Loading:**

```python
load_cli_config() β†’ dict
# Loads from ~/.hermes/config.yaml (or ./cli-config.yaml fallback)
# Merges with hardcoded defaults
# Expands ${ENV_VAR} references
# Maps terminal config β†’ env vars
```

---

### 6.2 CLI Entry Point (hermes_cli/main.py)

All `hermes` subcommands are dispatched from here:

```
hermes                    # Default: interactive chat
hermes chat               # Explicit interactive mode
hermes gateway start|stop|status|install|uninstall
hermes setup              # Setup wizard
hermes model              # Select model/provider
hermes tools              # Configure tools
hermes skills             # Manage skills
hermes config set|get     # Direct config manipulation
hermes cron list|delete   # Cron job management
hermes doctor             # Diagnose issues
hermes sessions browse    # Session picker
hermes profile create|list|switch|delete|export|import
hermes mcp serve|add|remove  # MCP management
hermes acp                # Start ACP server
hermes update|uninstall|version
```

**Profile System:**

- `_apply_profile_override()` runs BEFORE any imports to set `HERMES_HOME`
- Pre-parses `--profile/-p` from argv
- Allows fully isolated agent instances with separate config, memory, sessions, skills

---

### 6.3 Configuration System (hermes_cli/config.py)

**Key Configuration Sections:**

```yaml
model: "anthropic/claude-opus-4.6" # or dict with provider/base_url/api_key
providers: {} # Provider-specific configs
fallback_providers: [] # Ordered failover list
credential_pool: {} # Multiple API keys per provider

agent:
  max_turns: 90
  gateway_timeout: 1800
  tool_use_enforcement: "auto"

terminal:
  backend: "local" # local|docker|modal|daytona|ssh|singularity
  timeout: 180
  persistent_shell: true
  docker_image: "nikolaik/python-nodejs:..."

compression:
  enabled: true
  threshold: 0.50 # Compress when 50% of context used
  target_ratio: 0.20 # Summary = 20% of compressed content
  protect_last_n: 20

auxiliary:
  vision: { provider, model }
  web_extract: { provider, model }
  compression: { provider, model }

memory:
  memory_enabled: true
  provider: "" # "" | "honcho" | "mem0" | etc.
  memory_char_limit: 2200

display:
  personality: "kawaii"
  show_reasoning: false
  inline_diffs: true
  skin: "default"
  streaming: true

tts:
  provider: "edge" # edge|elevenlabs|openai|neutts

stt:
  enabled: true
  provider: "local" # local|groq|openai

privacy:
  redact_pii: false

mcp_servers: {} # MCP server configurations

skills:
  external_dirs: [] # Additional skill directories

approvals:
  mode: "smart" # smart|always|off
```

**Config Files:**

- `~/.hermes/config.yaml` β€” User settings (authoritative)
- `~/.hermes/.env` β€” API keys and secrets
- Config version migration system (currently v5)

---

### 6.4 Slash Command Registry (hermes_cli/commands.py)

All slash commands defined centrally in `COMMAND_REGISTRY`:

```python
CommandDef(name, description, category, aliases, args_hint, cli_only, gateway_only)
```

**Derived automatically by:**

- CLI `process_command()` β€” dispatch on canonical name
- Gateway dispatch + help
- Telegram BotCommand menu
- Slack `/hermes` subcommands
- Autocomplete + help text

**Key Commands:**

| Command        | Aliases    | Description                   |
| -------------- | ---------- | ----------------------------- |
| `/new`         | `/reset`   | Start fresh conversation      |
| `/model`       |            | Show/switch model             |
| `/personality` |            | Set agent personality         |
| `/retry`       |            | Retry last turn               |
| `/undo`        |            | Remove last turn              |
| `/compress`    | `/compact` | Compress context              |
| `/usage`       | `/cost`    | Show token usage              |
| `/insights`    |            | Usage analytics               |
| `/skills`      |            | Browse/install skills         |
| `/background`  | `/bg`      | Manage background processes   |
| `/plan`        |            | Generate implementation plan  |
| `/rollback`    |            | Restore filesystem checkpoint |
| `/verbose`     |            | Toggle debug output           |
| `/reasoning`   |            | Set reasoning effort          |
| `/yolo`        |            | Toggle approval bypass        |
| `/btw`         |            | Ephemeral side question       |
| `/stop`        |            | Kill current agent run        |
| `/queue`       |            | Queue next prompt             |
| `/browser`     |            | Interactive browser session   |
| `/history`     | `/resume`  | Session browser               |
| `/skin`        |            | Switch CLI theme              |

---

### 6.5 Setup Wizard (hermes_cli/setup.py)

Modular interactive wizard with independent sections:

1. **Model & Provider** β€” Select AI provider, enter API keys, choose model
2. **Terminal Backend** β€” Choose execution environment
3. **Agent Settings** β€” Max iterations, compression, session policies
4. **Messaging Platforms** β€” Configure Telegram, Discord, Slack, etc.
5. **Tools** β€” TTS, STT, web search, image generation, browser

Features:

- Live credential validation
- Real-time model list fetching from provider APIs
- Automatic OpenClaw migration detection
- Atomic config file writes

---

### 6.6 Model Catalog (hermes_cli/models.py)

Provider-specific model lists:

```python
_PROVIDER_MODELS = {
    "nous": ["anthropic/claude-opus-4.6", "anthropic/claude-sonnet-4.6", ...],  # 25+
    "openrouter": ["anthropic/claude-opus-4.6", "google/gemini-3-flash", ...],  # 30+
    "anthropic": ["claude-opus-4-6", "claude-sonnet-4-6", ...],
    "openai": ["gpt-5", "gpt-5.4-mini", "gpt-4.1", "gpt-4o", ...],
    "copilot": ["gpt-5.4", "gpt-5.4-mini", "gpt-5.3-codex", ...],
    "huggingface": [...],
    "minimax": [...],
    "kimi-coding": [...],
    "alibaba": [...],
    "deepseek": [...],
    # ... more providers
}
```

Features:

- Dynamic fetching via provider `/models` endpoints
- Curated lists used when live probe returns fewer models
- Fuzzy matching for typo correction
- Validation against provider catalog

---

### 6.7 Skin/Theme Engine (hermes_cli/skin_engine.py)

Data-driven CLI visual customization β€” no code changes needed.

**Customizable Elements:**

| Element                          | Key                      | Used By           |
| -------------------------------- | ------------------------ | ----------------- |
| Banner border/title/accent       | `colors.*`               | banner.py         |
| Response box border              | `colors.response_border` | cli.py            |
| Spinner faces (waiting/thinking) | `spinner.*`              | display.py        |
| Spinner verbs/wings              | `spinner.*`              | display.py        |
| Tool output prefix               | `tool_prefix`            | display.py        |
| Per-tool emojis                  | `tool_emojis`            | display.py        |
| Agent name/welcome/prompt        | `branding.*`             | banner.py, cli.py |

**Built-in Skins:** default, ares, mono, slate, poseidon, sisyphus, charizard

**User Skins:** Drop `~/.hermes/skins/<name>.yaml` and activate with `/skin <name>`

---

## 7. Tool System

### 7.1 Terminal Tool (tools/terminal_tool.py)

Shell command execution across multiple backends.

```python
def terminal_tool(
    command: str,
    background: bool = False,
    timeout: Optional[int] = None,
    task_id: Optional[str] = None,
    force: bool = False,        # Skip approval for dangerous commands
    workdir: Optional[str] = None,
    check_interval: Optional[int] = None,  # Background task polling
    pty: bool = False,
) -> str  # JSON result
```

**Features:**

- Multi-backend: Selects based on `TERMINAL_ENV` (local/docker/ssh/modal/daytona/singularity)
- Per-task_id sandboxes with thread-safe creation locks
- Dangerous command routing through approval system
- Background task support with file-based IPC
- Interrupt handling β€” polls `is_interrupted()` during execution
- Auto-cleanup daemon thread for idle environments (>300s)
- Disk usage warnings at configurable threshold

---

### 7.2 File Tools (tools/file_tools.py)

Safe file operations with size guards and sensitive path protection.

- `read_file_tool(path, offset, limit)` β€” Read with pagination (default 100K char limit)
- `write_file_tool(path, content)` β€” Write with approval for sensitive paths
- `edit_file_tool(path, old_text, new_text)` β€” String replacement editing
- `list_files_tool(path)` β€” Directory listing
- `search_files_tool(pattern, path)` β€” Glob/regex file search

**Safety:**

- Device path blocklist (`/dev/zero`, `/dev/stdin`, etc.)
- Read dedup tracking β€” returns stub on re-read if mtime unchanged
- Sensitive path blocking: `/etc/`, `/boot/`, `~/.ssh` without approval
- Prompt injection protection for known dangerous paths

---

### 7.3 Web Tools (tools/web_tools.py)

Web search and content extraction.

- `web_search_tool(query, limit)` β€” Search via configurable backend
- `web_extract_tool(urls, format)` β€” Extract content from URLs
- `web_crawl_tool(url, instructions)` β€” LLM-guided web crawling

**Backends:** Firecrawl, Parallel Web, Tavily, Exa, DuckDuckGo

- Fallback detection by highest-priority available API key
- LLM processing via auxiliary client (Gemini 3 Flash) for intelligent extraction
- SSRF protection and URL safety checks

---

### 7.4 Browser Tool (tools/browser_tool.py)

Headless browser automation with accessibility tree.

```python
browser_navigate(url, task_id) β†’ str
browser_snapshot(task_id, max_chars) β†’ str
browser_click(ref, task_id) β†’ str      # Element refs like @e1, @e2
browser_type(ref, text, task_id) β†’ str
browser_scroll(ref, direction, task_id) β†’ str
browser_extract(task, max_chars, task_id) β†’ str
```

**Backends:**

- **Local:** Headless Chromium via `agent-browser` CLI
- **Cloud:** Browserbase (stealth, proxies, CAPTCHA solving)
- **Camofox:** Anti-detection browser using Camoufox

**Features:**

- Accessibility tree for text-based snapshots (no vision required)
- Session isolation per task_id with inactivity cleanup
- API key detection in URLs (prevents exfiltration)
- SSRF protection for private/internal addresses

---

### 7.5 Delegate Tool (tools/delegate_tool.py)

Spawn isolated subagents for parallel workstreams.

```python
def delegate_task(
    goal: str,
    context: str = None,
    toolsets: List[str] = None,       # Default: ["terminal", "file", "web"]
    tasks: List[Dict] = None,          # Batch mode: up to 3 concurrent
    max_iterations: int = 50,
    parent_agent = None,
) β†’ str
```

**Isolation:**

- Fresh conversation (no parent history)
- Own task_id (separate terminal session, file ops)
- Restricted toolset (configurable, blocked tools always stripped)
- Focused system prompt from goal + context
- Parent only sees delegation call and summary result

**Blocked Tools:** delegate_task, clarify, memory, send_message, execute_code (no recursion, no user interaction)

**Constraints:** MAX_DEPTH=2, MAX_CONCURRENT_CHILDREN=3

---

### 7.6 MCP Tool (tools/mcp_tool.py)

Model Context Protocol client integration.

**Configuration (config.yaml):**

```yaml
mcp_servers:
  filesystem:
    command: "npx"
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
    timeout: 120
  remote_api:
    url: "https://my-mcp-server.example.com/mcp"
    headers:
      Authorization: "Bearer sk-..."
    sampling:
      enabled: true
      model: "gemini-3-flash"
```

**Features:**

- **Transports:** Stdio (local processes) and HTTP/StreamableHTTP (remote)
- **Dynamic tool discovery:** Listens for `tools/list_changed` notifications
- **Sampling support:** MCP servers can request LLM completions
- **Automatic reconnection** with exponential backoff (5 retries)
- Dedicated background event loop in daemon thread
- Thread-safe via lock protecting server dict

---

### 7.7 Approval System (tools/approval.py)

Dangerous command detection and approval flow.

```python
detect_dangerous_command(command: str) β†’ (is_dangerous, pattern_key, description)
```

**106 patterns covering:**

- Destructive operations (`rm -r /`, `mkfs`, `dd if=`)
- Privilege escalation (`chmod 777`, `chown -R root`)
- SQL injection (`DROP TABLE`, `DELETE FROM` without WHERE)
- System targeting (`/etc/` writes, `systemctl stop`, fork bombs)
- Shell injection (pipe to sh, wget to sh, process substitution)
- Network exfiltration (curl with embedded API keys)
- Secret access (`cat ~/.env`, `cat ~/.netrc`)

**Normalization:** Strips ANSI escapes, null bytes, normalizes Unicode

**Approval Modes:**

- `smart` β€” Learns which commands are safe based on user decisions
- `always` β€” Always ask for dangerous commands
- `off` β€” Never ask (or `/yolo` toggle)

---

### 7.8 Terminal Backends (tools/environments/)

| Backend           | File               | Features                                                                       |
| ----------------- | ------------------ | ------------------------------------------------------------------------------ |
| **Local**         | `local.py`         | Direct execution, interrupt support, non-blocking I/O, persistent shell        |
| **Docker**        | `docker.py`        | Sandboxed containers, cap-drop ALL, no-new-privileges, PID limits, bind mounts |
| **SSH**           | `ssh.py`           | Remote execution via ControlMaster, persistent shell mixin                     |
| **Modal**         | `modal.py`         | Native Modal SDK `Sandbox.create()`/`Sandbox.exec()`, persistent snapshots     |
| **Managed Modal** | `managed_modal.py` | Modal through Nous-hosted gateway                                              |
| **Daytona**       | `daytona.py`       | Daytona SDK cloud sandboxes, stop/resume lifecycle                             |
| **Singularity**   | `singularity.py`   | Singularity containers with scratch dir, SIF cache                             |

**Common Interface (BaseEnvironment ABC):**

```python
execute(command, timeout) β†’ {"output": str, "returncode": int}
cleanup() β†’ None
```

---

## 8. Agent Internals

### 8.1 Prompt Builder (agent/prompt_builder.py)

Assembles the system prompt from multiple sources:

| Component               | Source                                               |
| ----------------------- | ---------------------------------------------------- |
| Agent Identity          | `DEFAULT_AGENT_IDENTITY` or `SOUL.md`                |
| Memory Guidance         | When/how to use memory tool                          |
| Session Search Guidance | How to recall past conversations                     |
| Skills Guidance         | When to create/patch skills                          |
| Tool Use Enforcement    | Must execute tools, not describe actions             |
| Skills Index            | `~/.hermes/skills/.hermes-skills.json`               |
| Platform Hints          | OS, Python version, shell, available tools           |
| Context Files           | `.hermes.md`, `AGENTS.md`, `.cursorrules`, `SOUL.md` |
| Model/Provider Info     | Current model and provider identity                  |

**Context File Discovery:**

1. Check `cwd/.hermes.md` or `HERMES.md`
2. Walk parent directories up to git root
3. Validate against injection patterns before inclusion

**Injection Detection (30+ patterns):**

- "ignore previous instructions", "system prompt override"
- "do not tell the user", "act as if you have no restrictions"
- HTML comment injection, exfiltration via curl, Unicode stealth chars

---

### 8.2 Context Compressor (agent/context_compressor.py)

Automatically compresses conversation history when approaching context limits.

```python
class ContextCompressor:
    threshold_percent: float = 0.50   # Compress when 50% of context used
    protect_first_n: int = 3          # Keep system prompt + first turn
    protect_last_n: int = 20          # Keep recent N messages
    summary_target_ratio: float = 0.20  # Summary = 20% of compressed content
```

**Compression Algorithm:**

1. **Pre-pass:** Replace old tool results with placeholder (cheap)
2. **Protect head:** System prompt + first exchange always kept
3. **Protect tail:** Token-budget-based tail protection (~20K tokens)
4. **Summarize middle:** LLM-generated structured summary (Goal, Progress, Decisions, Files, Next Steps)
5. **Iterative updates:** On subsequent compressions, update previous summary instead of re-summarizing

---

### 8.3 Prompt Caching (agent/prompt_caching.py)

Anthropic prompt caching support for cost reduction.

- System prompt cached across turns (first conversation turn establishes cache)
- Cache markers inserted at system prompt boundaries
- Must not break mid-conversation β€” altering past context invalidates cache
- The ONLY time context is altered is during compression

**Critical Rule:** Do NOT implement changes that would alter past context, change toolsets, reload memories, or rebuild system prompts mid-conversation.

---

### 8.4 Auxiliary Client (agent/auxiliary_client.py)

Separate LLM client for non-primary tasks:

- **Vision analysis** β€” Image description and analysis
- **Web extraction** β€” Content summarization
- **Context compression** β€” Generating conversation summaries
- **Session search** β€” Summarizing search results
- **MCP sampling** β€” Serving server-initiated LLM requests

Configured per-task via `auxiliary` section in config.yaml.

---

### 8.5 Display & Spinner (agent/display.py)

- **KawaiiSpinner** β€” Animated face characters during API calls
- **Tool preview formatting** β€” `β”Š` prefixed activity feed for tool execution
- **Inline diff previews** β€” Shows unified diffs for write/patch operations
- Respects active skin for colors, emojis, and branding

---

### 8.6 Skill Commands (agent/skill_commands.py)

Shared skill invocation for CLI and gateway:

- Skills loaded from `~/.hermes/skills/` and external directories
- Injected as **user message** (not system prompt) to preserve prompt caching
- `/plan` command generates implementation plans stored in `.hermes/plans/`
- Skill content includes setup instructions, tool options, usage examples

---

## 9. Messaging Gateway

### 9.1 GatewayRunner (gateway/run.py)

Main controller managing all platform adapters and routing messages.

**Key Attributes:**

- `adapters: Dict[Platform, BasePlatformAdapter]` β€” Active platform instances
- `session_store: SessionStore` β€” Conversation persistence
- `_running_agents: Dict[str, AIAgent]` β€” Per-session cached agents (preserves prompt caching)
- `_pending_approvals: Dict[str, Dict]` β€” Dangerous command approval tracking
- `pairing_store: PairingStore` β€” DM code-based user authorization

**Message Flow:**

1. Platform adapter queues `MessageEvent`
2. GatewayRunner dequeues, calls `_handle_message()`
3. Slash command? β†’ dispatch to handler
4. Regular message? β†’ `_handle_message_with_agent()` (async, with per-session locking)
5. Response delivered back via platform adapter

**Features:**

- Agent caching per session (preserves Anthropic prompt cache across turns)
- Session reset policies (inactivity timeout, hard reset)
- Per-session model overrides via `/model`
- Background memory flush on session expiry
- Approval routing (`/approve`, `/deny`) with interactive buttons (Discord)
- 30+ slash command handlers

---

### 9.2 Session Store (gateway/session.py)

**SessionSource** β€” Where a message originated (platform, chat_id, user info)
**SessionContext** β€” Full context for system prompt injection (platforms, home channels, metadata)
**SessionStore** β€” Loads/saves conversation transcripts as JSON files

```
~/.hermes/sessions/{session_key}.json
Format: [{role, content, timestamp}, ...]
```

**Features:**

- Session key computed from platform + chat_id + thread_id (deterministic hash)
- Inactivity timeout for session resets
- PII redaction (phone numbers hashed)
- Survives gateway restarts

---

### 9.3 Platform Adapters (gateway/platforms/)

**16 adapters sharing `BasePlatformAdapter` interface:**

| Platform           | Key Features                                                                                             |
| ------------------ | -------------------------------------------------------------------------------------------------------- |
| **Telegram**       | Polling + webhook mode, media handling, inline keyboards, forum topic isolation, group mention gating    |
| **Discord**        | Server channels, threads, reactions (processing/done/error), button-based approval, @mention requirement |
| **Slack**          | Multi-workspace OAuth, thread handling, app_mention, `/hermes` subcommands                               |
| **WhatsApp**       | Group & DM support, media captions, LID↔phone alias resolution                                           |
| **Matrix**         | E2EE room encryption, threaded messages, trusted device flow, native voice messages                      |
| **Signal**         | Encrypted DMs, group membership, SSE keepalive, phone URL encoding                                       |
| **Email**          | IMAP/SMTP, multi-recipient, skip_attachments option                                                      |
| **Home Assistant** | REST tools + WebSocket, service discovery, smart home automation                                         |
| **SMS**            | Twilio integration                                                                                       |
| **Mattermost**     | Self-hosted Slack alternative, configurable mention behavior                                             |
| **DingTalk**       | Alibaba enterprise messaging                                                                             |
| **Feishu/Lark**    | Enterprise messaging, message cards, approval workflows                                                  |
| **WeCom**          | Enterprise WeChat, department management                                                                 |
| **Webhook**        | Generic HTTP POST for custom integrations                                                                |
| **API Server**     | OpenAI-compatible `/v1/chat/completions` endpoint                                                        |

**Common Features:**

- Image/audio caching for vision and STT tools
- Rate limiting with exponential backoff
- Session routing with authorization rules
- Cross-platform conversation continuity

---

## 10. Cron Scheduling

Built-in job scheduler running in the gateway background thread.

**Schedule Types:**

- `"once in 5m"` β€” One-shot after duration
- `"every 30m"` β€” Recurring interval
- `"0 9 * * *"` β€” Standard cron expression
- `"2026-04-06T14:00"` β€” Absolute datetime

**Job Storage:** `~/.hermes/cron/jobs.json`

**Execution Flow:**

1. `tick()` called every 60s from gateway background thread
2. Fetch due jobs past `next_run_at`
3. Spawn `hermes` CLI subprocess with job prompt + skills
4. Capture output β†’ save to `~/.hermes/cron/output/{job_id}/{timestamp}.md`
5. Deliver to target platform (or stay local)

**Delivery Targets:**

- `"local"` β€” Output saved locally only
- `"origin"` β€” Send to originating chat
- `"telegram:<chat_id>"` β€” Explicit platform/chat routing
- `[SILENT]` prefix β€” Suppress delivery but keep logs

**Grace Windows:** Based on schedule frequency (120s–2hrs) to handle missed jobs

---

## 11. Skills System

**Skills are composable, agent-invokable knowledge units.**

**Structure:**

```
skills/
β”œβ”€β”€ creative/              # ASCII art, diagrams, music
β”œβ”€β”€ software-development/  # Debugging, testing, docs
β”œβ”€β”€ github/                # Codebase inspection, PR workflow
β”œβ”€β”€ research/              # Literature, web scraping
β”œβ”€β”€ productivity/          # Task management
β”œβ”€β”€ media/                 # Image, video, audio processing
β”œβ”€β”€ mlops/                 # ML experiment tracking
β”œβ”€β”€ autonomous-ai-agents/  # Multi-agent orchestration
└── [20+ more categories]
```

**Per-Skill Structure:**

```
skill-name/
β”œβ”€β”€ SKILL.md     # Metadata (YAML frontmatter) + implementation instructions
└── [sub-skills]/
```

**SKILL.md Example:**

```yaml
---
name: ascii-art
description: Generate ASCII art using multiple tools
version: 4.0.0
dependencies: []
metadata:
  hermes:
    tags: [ASCII, Art, Banners, Creative]
    related_skills: [excalidraw]
---
[Implementation instructions, tool options, examples...]
```

**Discovery:**

- Auto-discovered from `~/.hermes/skills/` + external dirs
- Skills index built at startup (`.hermes-skills.json`)
- Loaded as user messages to preserve prompt caching
- Per-platform enable/disable via `hermes skills`
- Skills Hub (`agentskills.io`) for community sharing

---

## 12. Plugin System

Drop Python files into `~/.hermes/plugins/` to extend Hermes.

**Plugin Capabilities:**

- Register custom tools and toolsets
- Inject messages into conversation
- Lifecycle hooks: `pre_llm_call`, `post_llm_call`, `on_session_start`, `on_session_end`
- Enable/disable via `hermes plugins enable/disable <name>`

**Memory Provider Plugins (plugins/memory/):**
8 implementations: openviking, mem0, hindsight, holographic, honcho, retaindb, byterover

Each implements:

```python
class MemoryProvider:
    def is_available() β†’ bool
    def store(key, value)
    def retrieve(query) β†’ list
    def clear()
```

---

## 13. Memory System

Hermes has a pluggable memory provider interface:

**Built-in Memory:**

- `MEMORY.md` β€” Markdown file with persistent facts
- `USER.md` β€” User profile information
- Memory read/write tools called by agent during conversation
- Periodic nudges prompt agent to save important information
- FTS5 session search for cross-session recall

**Honcho Integration:**

- AI-native dialectic user modeling
- Async memory writes
- Profile-scoped host/peer resolution
- Multi-user isolation in gateway mode

**Configuration:**

```yaml
memory:
  memory_enabled: true
  provider: "" # "" for built-in, "honcho", "mem0", etc.
  memory_char_limit: 2200
```

---

## 14. ACP Server (IDE Integration)

Agent Communication Protocol server for VS Code, Zed, JetBrains.

**Entry:** `hermes acp` β†’ `acp_adapter/server.py`

**HermesACPAgent Class:**

```python
initialize()                    # Handshake with IDE client
authenticate(method_id)         # Validate credentials
new_session(cwd, mcp_servers)   # Create isolated session
load_session(session_id)        # Resume session
fork_session(session_id)        # Branch for parallel work
list_sessions()                 # Browse all sessions
cancel(session_id)              # Interrupt running agent
```

**Features:**

- Slash command support (`/model`, `/tools`, `/reset`, `/compact`)
- Client-provided MCP servers (IDE's MCP ecosystem flows into agent)
- Streaming callbacks for messages, thinking, tool progress
- Dangerous command approval via IDE UI

---

## 15. API Server

OpenAI-compatible API endpoint for headless integrations (e.g., Open WebUI).

**Endpoint:** `POST /v1/chat/completions`

**Features:**

- `X-Hermes-Session-Id` header for persistent sessions
- Tool progress streaming via SSE events
- `/api/jobs` REST API for cron management
- Input limits, field whitelists, SQLite-backed response persistence
- CORS origin protection

---

## 16. MCP Server Mode

Expose Hermes conversations to MCP-compatible clients.

**Entry:** `hermes mcp serve`

**Features:**

- Browse conversations and sessions
- Read messages and search across sessions
- Manage attachments
- Supports both stdio and Streamable HTTP transports
- Compatible with Claude Desktop, Cursor, VS Code, etc.

---

## 17. RL Training Environments

Atropos-based RL training framework for agent policy optimization.

**Base Class:** `HermesAgentBaseEnv` (extends `atroposlib.BaseEnv`)

**Configuration:**

```python
HermesAgentEnvConfig:
    enabled_toolsets: ["terminal", "file", "web"]
    max_agent_turns: 30
    agent_temperature: 1.0
    terminal_backend: "local"  # or docker/modal for isolation
    dataset_name: str
```

**Subclass Requirements:**

- `setup()` β€” Load dataset
- `get_next_item()` β€” Return next task
- `format_prompt()` β€” Convert item β†’ user message
- `compute_reward()` β€” Score rollout
- `evaluate()` β€” Periodic eval on test set

**Example Environments:**

- `web_research_env.py` β€” Web research tasks
- `agentic_opd_env.py` β€” Observation-Prediction-Demonstration
- `hermes_swe_env.py` β€” Software engineering tasks

**Supporting:**

- `HermesAgentLoop` β€” Orchestrates step-by-step rollouts
- `ToolContext` β€” Sandbox for tool execution, records side effects
- `trajectory_compressor.py` β€” Compresses trajectories for training data

---

## 18. Profiles (Multi-Instance)

Run multiple fully isolated Hermes instances from the same installation.

**Commands:**

```bash
hermes profile create <name>
hermes profile list
hermes profile switch <name>
hermes profile delete <name>
hermes profile export <name>
hermes profile import <fil