[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AGTMW7WCE98JFMMKA258KB":3,"skill-same:01M7AGTMW7WCE98JFMMKA258KB":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7AGTMW7WCE98JFMMKA258KB","hermes-agent",null,"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.","Ablankpaper\u002Faera","Ablankpaper","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F316571397?v=4","01M79REMJ8VVQFYFWZ1FXNH5DG","Awhite","01M7AGTEMGQVY2JARVWGY1M2N3",0,"MIT","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fhermes-agent\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: hermes-agent\ndescription: 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.\n---\n\n# Hermes Agent - Complete Project Guide (A-Z)\n\n> **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.\n\n---\n\n## Table of Contents\n\n1. [Project Overview](#1-project-overview)\n2. [Key Features Summary](#2-key-features-summary)\n3. [Installation & Getting Started](#3-installation--getting-started)\n4. [Project Structure](#4-project-structure)\n5. [Core Architecture](#5-core-architecture)\n   - 5.1 [AIAgent Class (run_agent.py)](#51-aiagent-class-run_agentpy)\n   - 5.2 [Tool Orchestration (model_tools.py)](#52-tool-orchestration-model_toolspy)\n   - 5.3 [Toolset System (toolsets.py)](#53-toolset-system-toolsetspy)\n   - 5.4 [Tool Registry (tools\u002Fregistry.py)](#54-tool-registry-toolsregistrypy)\n   - 5.5 [Session Database (hermes_state.py)](#55-session-database-hermes_statepy)\n   - 5.6 [Constants & Home Directory (hermes_constants.py)](#56-constants--home-directory-hermes_constantspy)\n6. [CLI System](#6-cli-system)\n   - 6.1 [Interactive CLI (cli.py)](#61-interactive-cli-clipy)\n   - 6.2 [CLI Entry Point (hermes_cli\u002Fmain.py)](#62-cli-entry-point-hermes_climainpy)\n   - 6.3 [Configuration System (hermes_cli\u002Fconfig.py)](#63-configuration-system-hermes_cliconfigpy)\n   - 6.4 [Slash Command Registry (hermes_cli\u002Fcommands.py)](#64-slash-command-registry-hermes_clicommandspy)\n   - 6.5 [Setup Wizard (hermes_cli\u002Fsetup.py)](#65-setup-wizard-hermes_clisetupy)\n   - 6.6 [Model Catalog (hermes_cli\u002Fmodels.py)](#66-model-catalog-hermes_climodelspy)\n   - 6.7 [Skin\u002FTheme Engine (hermes_cli\u002Fskin_engine.py)](#67-skintheme-engine-hermes_cliskin_enginepy)\n7. [Tool System](#7-tool-system)\n   - 7.1 [Terminal Tool (tools\u002Fterminal_tool.py)](#71-terminal-tool-toolsterminal_toolpy)\n   - 7.2 [File Tools (tools\u002Ffile_tools.py)](#72-file-tools-toolsfile_toolspy)\n   - 7.3 [Web Tools (tools\u002Fweb_tools.py)](#73-web-tools-toolsweb_toolspy)\n   - 7.4 [Browser Tool (tools\u002Fbrowser_tool.py)](#74-browser-tool-toolsbrowser_toolpy)\n   - 7.5 [Delegate Tool (tools\u002Fdelegate_tool.py)](#75-delegate-tool-toolsdelegate_toolpy)\n   - 7.6 [MCP Tool (tools\u002Fmcp_tool.py)](#76-mcp-tool-toolsmcp_toolpy)\n   - 7.7 [Approval System (tools\u002Fapproval.py)](#77-approval-system-toolsapprovalpy)\n   - 7.8 [Terminal Backends (tools\u002Fenvironments\u002F)](#78-terminal-backends-toolsenvironments)\n8. [Agent Internals](#8-agent-internals)\n   - 8.1 [Prompt Builder (agent\u002Fprompt_builder.py)](#81-prompt-builder-agentprompt_builderpy)\n   - 8.2 [Context Compressor (agent\u002Fcontext_compressor.py)](#82-context-compressor-agentcontext_compressorpy)\n   - 8.3 [Prompt Caching (agent\u002Fprompt_caching.py)](#83-prompt-caching-agentprompt_cachingpy)\n   - 8.4 [Auxiliary Client (agent\u002Fauxiliary_client.py)](#84-auxiliary-client-agentauxiliary_clientpy)\n   - 8.5 [Display & Spinner (agent\u002Fdisplay.py)](#85-display--spinner-agentdisplaypy)\n   - 8.6 [Skill Commands (agent\u002Fskill_commands.py)](#86-skill-commands-agentskill_commandspy)\n9. [Messaging Gateway](#9-messaging-gateway)\n   - 9.1 [GatewayRunner (gateway\u002Frun.py)](#91-gatewayrunner-gatewayrunpy)\n   - 9.2 [Session Store (gateway\u002Fsession.py)](#92-session-store-gatewaysessionpy)\n   - 9.3 [Platform Adapters (gateway\u002Fplatforms\u002F)](#93-platform-adapters-gatewayplatforms)\n10. [Cron Scheduling](#10-cron-scheduling)\n11. [Skills System](#11-skills-system)\n12. [Plugin System](#12-plugin-system)\n13. [Memory System](#13-memory-system)\n14. [ACP Server (IDE Integration)](#14-acp-server-ide-integration)\n15. [API Server](#15-api-server)\n16. [MCP Server Mode](#16-mcp-server-mode)\n17. [RL Training Environments](#17-rl-training-environments)\n18. [Profiles (Multi-Instance)](#18-profiles-multi-instance)\n19. [Security Model](#19-security-model)\n20. [Provider & Model System](#20-provider--model-system)\n21. [Streaming & Reasoning](#21-streaming--reasoning)\n22. [Release History](#22-release-history)\n23. [File Dependency Chain](#23-file-dependency-chain)\n24. [Key Design Patterns](#24-key-design-patterns)\n25. [Configuration Reference](#25-configuration-reference)\n26. [Known Pitfalls](#26-known-pitfalls)\n\n---\n\n## 1. Project Overview\n\n**Hermes Agent** is a self-improving AI agent built by [Nous Research](https:\u002F\u002Fnousresearch.com). It is an open-source (MIT licensed), Python-based project that provides:\n\n- A **full interactive terminal UI** (CLI) for conversing with LLMs\n- A **messaging gateway** supporting 16+ platforms (Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, etc.)\n- 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\n- **40+ built-in tools** — terminal execution, file manipulation, web search, browser automation, code execution, image generation, TTS\u002FSTT, and more\n- **Any LLM provider** — OpenRouter (200+ models), Nous Portal (400+ models), OpenAI, Anthropic, Hugging Face, GitHub Copilot, z.ai\u002FGLM, Kimi\u002FMoonshot, MiniMax, Alibaba\u002FDashScope, custom endpoints\n- **Six terminal backends** — local, Docker, SSH, Modal (serverless), Daytona (serverless), Singularity (HPC)\n- **Scheduled automations** via built-in cron scheduler\n- **IDE integration** via ACP (Agent Communication Protocol) for VS Code, Zed, JetBrains\n- **MCP integration** — both client (connect to any MCP server) and server (expose Hermes to MCP clients)\n- **RL training** via Atropos environments for training the next generation of tool-calling models\n\n**Tech Stack:**\n\n- Python 3.11+ (core agent, tools, gateway, cron)\n- Node.js (browser automation via agent-browser)\n- SQLite with WAL mode and FTS5 (session storage, full-text search)\n- OpenAI-compatible API (primary inference interface)\n- Anthropic SDK (native Anthropic support)\n- Rich + prompt_toolkit (CLI rendering)\n\n**Repository:** `github.com\u002FNousResearch\u002Fhermes-agent`\n**Version:** 0.7.0 (as of April 2026)\n**License:** MIT\n\n---\n\n## 2. Key Features Summary\n\n| Feature                      | Description                                                                                                                                                                      |\n| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **Terminal UI**              | Full TUI with multiline editing, slash-command autocomplete, conversation history, interrupt-and-redirect, streaming tool output                                                 |\n| **Multi-Platform Messaging** | Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, Home Assistant, DingTalk, Feishu\u002FLark, WeCom, Mattermost, SMS, Webhook — all from a single gateway process            |\n| **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 |\n| **Scheduled Tasks**          | Built-in cron scheduler with delivery to any platform (daily reports, nightly backups, weekly audits)                                                                            |\n| **Subagent Delegation**      | Spawn isolated subagents for parallel workstreams with restricted toolsets                                                                                                       |\n| **Execute Code**             | Python scripts that call tools via RPC, collapsing multi-step pipelines into zero-context-cost turns                                                                             |\n| **Terminal Backends**        | Local, Docker, SSH, Modal, Daytona, Singularity — run on a $5 VPS or a GPU cluster                                                                                               |\n| **Skills**                   | 70+ bundled skills across 28 categories, Skills Hub for community discovery, agentskills.io compatibility                                                                        |\n| **Plugins**                  | Drop-in Python plugins with lifecycle hooks (pre_llm_call, post_llm_call, on_session_start, on_session_end)                                                                      |\n| **MCP**                      | Client (connect to MCP servers for extended tools) and Server (expose conversations to MCP clients)                                                                              |\n| **IDE Integration**          | VS Code, Zed, JetBrains via ACP server with session management and tool streaming                                                                                                |\n| **API Server**               | OpenAI-compatible `\u002Fv1\u002Fchat\u002Fcompletions` endpoint for headless integrations                                                                                                      |\n| **Profiles**                 | Multi-instance support — each profile gets isolated config, memory, sessions, skills, gateway                                                                                    |\n| **Security**                 | Command approval system, secret redaction, SSRF protection, PII redaction, injection detection, credential directory protection                                                  |\n| **RL Training**              | Atropos environments for batch trajectory generation and agent policy optimization                                                                                               |\n\n---\n\n## 3. Installation & Getting Started\n\n```bash\n# One-line install (Linux, macOS, WSL2)\ncurl -fsSL https:\u002F\u002Fraw.githubusercontent.com\u002FNousResearch\u002Fhermes-agent\u002Fmain\u002Fscripts\u002Finstall.sh | bash\n\n# After install\nsource ~\u002F.bashrc    # or: source ~\u002F.zshrc\nhermes              # start chatting\n\n# Key commands\nhermes model        # Choose LLM provider and model\nhermes tools        # Configure which tools are enabled\nhermes config set   # Set individual config values\nhermes gateway      # Start the messaging gateway\nhermes setup        # Run the full setup wizard\nhermes update       # Update to latest version\nhermes doctor       # Diagnose any issues\n```\n\n**For development:**\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent.git\ncd hermes-agent\ncurl -LsSf https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\nuv venv venv --python 3.11\nsource venv\u002Fbin\u002Factivate\nuv pip install -e \".[all,dev]\"\npython -m pytest tests\u002F -q    # ~3000 tests\n```\n\n---\n\n## 4. Project Structure\n\n```\nhermes-agent\u002F\n├── run_agent.py              # AIAgent class — core conversation loop\n├── model_tools.py            # Tool orchestration, _discover_tools(), handle_function_call()\n├── toolsets.py               # Toolset definitions, _HERMES_CORE_TOOLS list\n├── toolset_distributions.py  # Toolset sampling distributions for RL\n├── cli.py                    # HermesCLI class — interactive CLI orchestrator\n├── hermes_state.py           # SessionDB — SQLite session store (FTS5 search)\n├── hermes_constants.py       # Shared constants, get_hermes_home()\n├── hermes_time.py            # Timezone handling\n├── utils.py                  # Shared utility functions\n├── batch_runner.py           # Parallel batch processing\n├── trajectory_compressor.py  # Trajectory compression for RL training\n├── mcp_serve.py              # MCP server mode entry point\n├── mini_swe_runner.py        # Minimal SWE benchmark runner\n├── rl_cli.py                 # RL CLI commands\n│\n├── agent\u002F                    # Agent internals\n│   ├── prompt_builder.py         # System prompt assembly\n│   ├── context_compressor.py     # Auto context compression\n│   ├── prompt_caching.py         # Anthropic prompt caching\n│   ├── auxiliary_client.py       # Auxiliary LLM client (vision, summarization)\n│   ├── model_metadata.py         # Model context lengths, token estimation\n│   ├── models_dev.py             # models.dev registry integration\n│   ├── display.py                # KawaiiSpinner, tool preview formatting\n│   ├── skill_commands.py         # Skill slash commands (shared CLI\u002Fgateway)\n│   └── trajectory.py             # Trajectory saving helpers\n│\n├── hermes_cli\u002F               # CLI subcommands and setup\n│   ├── main.py               # Entry point — all `hermes` subcommands\n│   ├── config.py             # DEFAULT_CONFIG, OPTIONAL_ENV_VARS, migration\n│   ├── commands.py           # Slash command definitions + SlashCommandCompleter\n│   ├── callbacks.py          # Terminal callbacks (clarify, sudo, approval)\n│   ├── setup.py              # Interactive setup wizard\n│   ├── skin_engine.py        # Skin\u002Ftheme engine\n│   ├── skills_config.py      # `hermes skills` — skill management\n│   ├── tools_config.py       # `hermes tools` — tool management\n│   ├── skills_hub.py         # Skills Hub integration\n│   ├── models.py             # Model catalog, provider model lists\n│   ├── model_switch.py       # Shared \u002Fmodel switch pipeline\n│   └── auth.py               # Provider credential resolution\n│\n├── tools\u002F                    # Tool implementations (one file per tool)\n│   ├── registry.py           # Central tool registry\n│   ├── approval.py           # Dangerous command detection\n│   ├── terminal_tool.py      # Terminal\u002Fshell execution\n│   ├── process_registry.py   # Background process management\n│   ├── file_tools.py         # File read\u002Fwrite\u002Fsearch\u002Fpatch\n│   ├── web_tools.py          # Web search\u002Fextract\n│   ├── browser_tool.py       # Browser automation\n│   ├── code_execution_tool.py # execute_code sandbox\n│   ├── delegate_tool.py      # Subagent delegation\n│   ├── mcp_tool.py           # MCP client integration\n│   ├── skills_tool.py        # Skill management tool\n│   ├── todo_tool.py          # Todo\u002Ftask tracking tool\n│   ├── memory_tool.py        # Memory read\u002Fwrite tool\n│   ├── tts_tool.py           # Text-to-speech\n│   ├── vision_tool.py        # Image analysis\n│   ├── image_gen_tool.py     # Image generation\n│   └── environments\u002F         # Terminal backends\n│       ├── base.py               # BaseEnvironment ABC\n│       ├── local.py              # Local execution\n│       ├── docker.py             # Docker containers\n│       ├── ssh.py                # SSH remote execution\n│       ├── modal.py              # Modal serverless\n│       ├── managed_modal.py      # Nous-hosted Modal\n│       ├── daytona.py            # Daytona serverless\n│       ├── singularity.py        # Singularity HPC containers\n│       └── persistent_shell.py   # Persistent shell mixin\n│\n├── gateway\u002F                  # Messaging platform gateway\n│   ├── run.py                # GatewayRunner — main message loop\n│   ├── session.py            # SessionStore — conversation persistence\n│   ├── status.py             # Gateway status, token locks\n│   └── platforms\u002F            # 16 platform adapters\n│       ├── base.py               # BasePlatformAdapter ABC\n│       ├── telegram.py           # Telegram (polling + webhook)\n│       ├── discord.py            # Discord\n│       ├── slack.py              # Slack\n│       ├── whatsapp.py           # WhatsApp\n│       ├── matrix.py             # Matrix (E2EE)\n│       ├── signal.py             # Signal\n│       ├── email.py              # Email (IMAP\u002FSMTP)\n│       ├── homeassistant.py      # Home Assistant\n│       ├── sms.py                # SMS (Twilio)\n│       ├── mattermost.py         # Mattermost\n│       ├── dingtalk.py           # DingTalk\n│       ├── feishu.py             # Feishu\u002FLark\n│       ├── wecom.py              # WeCom (Enterprise WeChat)\n│       ├── webhook.py            # Generic webhook\n│       └── api_server.py         # OpenAI-compatible API server\n│\n├── acp_adapter\u002F              # ACP server (IDE integration)\n│   ├── server.py             # HermesACPAgent class\n│   ├── session.py            # SessionManager\n│   ├── events.py             # Streaming callbacks\n│   ├── permissions.py        # Approval callbacks\n│   └── entry.py              # Entry point\n│\n├── cron\u002F                     # Scheduler\n│   ├── scheduler.py          # tick() — job execution engine\n│   └── jobs.py               # Job storage and CRUD\n│\n├── plugins\u002F                  # Plugin system\n│   └── memory\u002F               # 8 memory provider plugins\n│       ├── openviking\u002F\n│       ├── mem0\u002F\n│       ├── hindsight\u002F\n│       ├── holographic\u002F\n│       ├── honcho\u002F\n│       ├── retaindb\u002F\n│       └── byterover\u002F\n│\n├── environments\u002F             # RL training environments (Atropos)\n│   ├── hermes_base_env.py    # Abstract base RL environment\n│   ├── agent_loop.py         # HermesAgentLoop — rollout execution\n│   ├── tool_context.py       # ToolContext — sandbox for RL\n│   ├── web_research_env.py   # Web research tasks\n│   └── agentic_opd_env.py    # Observation-Prediction-Demo env\n│\n├── skills\u002F                   # 70+ bundled skills across 28 categories\n├── optional-skills\u002F          # Additional optional skills\n├── tests\u002F                    # ~3000 pytest tests\n├── scripts\u002F                  # Install, update, packaging scripts\n├── docker\u002F                   # Docker build files\n├── docs\u002F                     # Documentation source (Docusaurus)\n├── website\u002F                  # Landing page\n├── desktop\u002F                  # Desktop app (Electron, separate repo)\n├── tinker-atropos\u002F           # RL submodule\n│\n├── pyproject.toml            # Python package config\n├── AGENTS.md                 # Developer guide for AI assistants\n├── RELEASE_v0.2.0.md → v0.7.0.md  # Release notes\n└── cli-config.yaml.example   # Example config\n```\n\n**User config directory:** `~\u002F.hermes\u002F`\n\n```\n~\u002F.hermes\u002F\n├── config.yaml           # User settings\n├── .env                  # API keys and secrets\n├── MEMORY.md             # Persistent agent memory\n├── USER.md               # User profile\n├── SOUL.md               # Agent personality\u002Fidentity\n├── sessions.db           # SQLite session database\n├── skills\u002F               # User-installed skills\n├── skins\u002F                # Custom CLI themes\n├── plugins\u002F              # User plugins\n├── cron\u002F                 # Cron jobs and output\n│   ├── jobs.json\n│   └── output\u002F\n├── cache\u002F                # Image\u002Faudio cache\n├── plans\u002F                # Generated plans\n├── profiles\u002F             # Multi-instance profiles\n└── mcp\u002F                  # MCP server configs\n```\n\n---\n\n## 5. Core Architecture\n\n### 5.1 AIAgent Class (run_agent.py)\n\nThe `AIAgent` class is the heart of the system — the core conversation loop that orchestrates LLM calls, tool execution, context management, and response delivery.\n\n**Constructor (~60 parameters):**\n\n```python\nclass AIAgent:\n    def __init__(self,\n        model: str = \"anthropic\u002Fclaude-opus-4.6\",\n        max_iterations: int = 90,\n        enabled_toolsets: list = None,\n        disabled_toolsets: list = None,\n        quiet_mode: bool = False,\n        save_trajectories: bool = False,\n        platform: str = None,            # \"cli\", \"telegram\", etc.\n        session_id: str = None,\n        session_db: SessionDB = None,\n        skip_context_files: bool = False,\n        skip_memory: bool = False,\n        base_url: str = None,\n        api_key: str = None,\n        provider: str = None,\n        api_mode: str = \"chat_completions\",  # or \"anthropic_messages\" or \"codex_responses\"\n        tool_progress_callback = None,\n        stream_delta_callback = None,\n        thinking_callback = None,\n        status_callback = None,\n        iteration_budget: IterationBudget = None,\n        credential_pool = None,\n        checkpoints_enabled: bool = False,\n        # ... plus provider, routing, callback params\n    )\n```\n\n**Main Methods:**\n\n| Method                                                                          | Returns  | Purpose                                                                            |\n| ------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------- |\n| `chat(message, stream_callback)`                                                | `str`    | Simple interface — returns final response text                                     |\n| `run_conversation(user_message, system_message, conversation_history, task_id)` | `dict`   | Full interface — returns `{final_response, messages, completed, api_calls, error}` |\n| `_interruptible_api_call(api_kwargs)`                                           | Response | Runs API request in background thread with interrupt support                       |\n| `_interruptible_streaming_api_call(api_kwargs, on_first_delta)`                 | Response | Streaming variant with delta callbacks                                             |\n\n**The Core Agent Loop** (inside `run_conversation()`):\n\n```python\nwhile api_call_count \u003C self.max_iterations and self.iteration_budget.remaining > 0:\n    response = client.chat.completions.create(\n        model=model, messages=messages, tools=tool_schemas\n    )\n    if response.tool_calls:\n        for tool_call in response.tool_calls:\n            result = handle_function_call(tool_call.name, tool_call.args, task_id)\n            messages.append(tool_result_message(result))\n        api_call_count += 1\n    else:\n        return response.content  # Final text response\n```\n\n**Key Behaviors:**\n\n- **Three API modes:** `chat_completions` (OpenAI-compatible), `anthropic_messages` (Anthropic SDK), `codex_responses` (OpenAI Codex)\n- **Parallel tool execution:** Independent tool calls run concurrently via ThreadPoolExecutor (unless they share file paths or are in the never-parallel list)\n- **Interrupt support:** Background threads allow interrupt detection without blocking on HTTP\n- **Error recovery:** Automatic fallback chain (primary → fallback model), retry with exponential backoff, context compression on token overflow\n- **Budget pressure:** Warnings at 70% (caution) and 90% (urgent) of iteration budget\n- **Oversized results:** Tool results >100K chars are saved to temp files with a preview\n- **Stale connection detection:** 90s timeout for streaming, 60s read timeout\n\n**IterationBudget** (thread-safe):\n\n```python\nclass IterationBudget:\n    def consume() -> bool    # Check and consume one iteration\n    def refund()             # Give back iteration (for execute_code turns)\n    @property remaining      # Remaining iterations\n```\n\n---\n\n### 5.2 Tool Orchestration (model_tools.py)\n\nBridges the agent and tool registry — handles discovery, schema generation, and dispatch.\n\n**Key Functions:**\n\n| Function                                                                                | Purpose                                                                   |\n| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |\n| `_discover_tools()`                                                                     | Imports all tool modules (each calls `registry.register()` on import)     |\n| `get_tool_definitions(enabled_toolsets, disabled_toolsets, quiet_mode)`                 | Returns OpenAI-format tool schemas filtered by toolset                    |\n| `handle_function_call(function_name, function_args, task_id, user_task, enabled_tools)` | Main dispatcher — routes calls to registry with arg coercion              |\n| `coerce_tool_args(tool_name, args)`                                                     | Type coercion for LLM-generated arguments (string→int, string→bool, etc.) |\n\n**Tool Discovery Order:**\n\n1. Static tools (web_tools, terminal_tool, file_tools, browser_tool, etc.)\n2. Optional tools (fal_client for image gen, honcho, etc.) — graceful fallback if missing\n3. Plugin-registered tools\n4. MCP server tools (dynamic, via tools\u002Flist_changed notifications)\n\n**Special Tool Handling:**\n\n- **Agent-level tools** (todo, memory, session_search, delegate_task): Intercepted by `run_agent.py` before `handle_function_call()`\n- **execute_code**: Passes `enabled_tools` for sandbox tool list\n- **Dynamic schema adjustments**: `browser_navigate` strips web_search reference if tools unavailable\n\n**Async Bridging:**\n\n- Persistent event loops (not `asyncio.run()`) to prevent \"Event loop is closed\" errors\n- Main thread uses shared loop; worker threads get per-thread loops\n- `_run_async()` detects running loop and spins up disposable thread if needed\n\n---\n\n### 5.3 Toolset System (toolsets.py)\n\nProvides flexible tool grouping and composition.\n\n**Core Toolsets:**\n\n| Toolset          | Tools Included                                                                                   |\n| ---------------- | ------------------------------------------------------------------------------------------------ |\n| `web`            | web_search, web_extract, web_crawl                                                               |\n| `terminal`       | terminal                                                                                         |\n| `file`           | read_file, write_file, edit_file, list_files, search_files                                       |\n| `browser`        | browser_navigate, browser_snapshot, browser_click, browser_type, browser_scroll, browser_extract |\n| `vision`         | analyze_image                                                                                    |\n| `image_gen`      | generate_image                                                                                   |\n| `tts`            | text_to_speech                                                                                   |\n| `todo`           | todo_read, todo_write                                                                            |\n| `memory`         | memory_read, memory_write                                                                        |\n| `session_search` | session_search                                                                                   |\n| `delegation`     | delegate_task                                                                                    |\n| `code_execution` | execute_code                                                                                     |\n| `cronjob`        | create_job, list_jobs, delete_job                                                                |\n| `messaging`      | send_message                                                                                     |\n| `homeassistant`  | ha_get_states, ha_call_service, ...                                                              |\n\n**Composite Toolsets:**\n\n- `hermes-cli` — All core tools for CLI platform\n- `hermes-telegram`, `hermes-discord`, etc. — Platform-specific tool sets\n- `hermes-gateway` — Union of all platform tools\n- `debugging` — terminal + file + web\n- `safe` — Everything except terminal\n\n**Resolution:**\n\n```python\nresolve_toolset(name, visited=None) → List[str]\n# Recursively resolves toolset to tool names\n# Handles composition (includes) and cycle detection\n# Special aliases: \"all\" or \"*\" = all tools\n```\n\n---\n\n### 5.4 Tool Registry (tools\u002Fregistry.py)\n\nSingleton managing all tool schemas and handlers. Circular-import safe — has no tool dependencies.\n\n**ToolEntry** (per-tool metadata):\n\n```python\n@dataclass(slots=True)\nclass ToolEntry:\n    name: str\n    toolset: str\n    schema: dict           # OpenAI-format tool definition\n    handler: Callable      # Sync or async handler function\n    check_fn: Callable     # Returns True if tool is available\n    requires_env: list     # Required environment variables\n    is_async: bool\n    description: str\n    emoji: str\n```\n\n**Key Methods:**\n\n```python\nregistry.register(name, toolset, schema, handler, check_fn, requires_env)\nregistry.get_definitions(tool_names, quiet)  # Returns filtered schemas\nregistry.dispatch(name, args, **kwargs)      # Execute with async bridging\nregistry.deregister(name)                    # Remove (for MCP tool refresh)\nregistry.check_tool_availability()           # Returns (available, unavailable)\n```\n\n---\n\n### 5.5 Session Database (hermes_state.py)\n\nSQLite-based persistent session storage with FTS5 full-text search.\n\n**Schema (v6):**\n\n```sql\n-- Sessions table\nsessions (\n    id TEXT PRIMARY KEY,\n    source TEXT, user_id TEXT, model TEXT, model_config TEXT,\n    system_prompt TEXT, parent_session_id TEXT,\n    started_at TEXT, ended_at TEXT, end_reason TEXT,\n    message_count INTEGER, tool_call_count INTEGER,\n    input_tokens INTEGER, output_tokens INTEGER,\n    cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER,\n    estimated_cost_usd REAL, actual_cost_usd REAL,\n    title TEXT  -- UNIQUE INDEX\n)\n\n-- Messages table\nmessages (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    session_id TEXT, role TEXT, content TEXT,\n    tool_call_id TEXT, tool_calls TEXT,  -- JSON\n    tool_name TEXT, timestamp TEXT,\n    token_count INTEGER, finish_reason TEXT,\n    reasoning TEXT, reasoning_details TEXT, codex_reasoning_items TEXT\n)\n\n-- FTS5 virtual table (auto-synced via triggers)\nmessages_fts (content)\n```\n\n**Concurrency Model:**\n\n- WAL (Write-Ahead Logging) for concurrent readers + single writer\n- `BEGIN IMMEDIATE` for write transactions (lock at start, not commit)\n- Jitter retry on lock: 20-150ms random backoff, max 15 retries\n- Periodic WAL checkpoint every 50 writes\n\n**Key Operations:**\n\n- `create_session()`, `end_session()`, `reopen_session()`\n- `add_message()`, `get_messages()`\n- `search_sessions(query)` — FTS5 full-text search\n- `update_token_counts()` — Supports both incremental (CLI) and absolute (gateway) modes\n\n---\n\n### 5.6 Constants & Home Directory (hermes_constants.py)\n\nImport-safe constants module with no circular dependencies.\n\n```python\nget_hermes_home() → Path          # HERMES_HOME env var or ~\u002F.hermes\ndisplay_hermes_home() → str       # User-friendly display: \"~\u002F.hermes\"\nget_optional_skills_dir() → Path  # HERMES_OPTIONAL_SKILLS env var\nparse_reasoning_effort(str) → Dict  # \"high\" → {\"enabled\": True, \"effort\": \"high\"}\n\n# Key constants\nOPENROUTER_BASE_URL = \"https:\u002F\u002Fopenrouter.ai\u002Fapi\u002Fv1\"\nNOUS_API_BASE_URL = \"https:\u002F\u002Finference-api.nousresearch.com\u002Fv1\"\nAI_GATEWAY_BASE_URL = \"https:\u002F\u002Fai-gateway.vercel.sh\u002Fv1\"\nVALID_REASONING_EFFORTS = (\"xhigh\", \"high\", \"medium\", \"low\", \"minimal\")\n```\n\n---\n\n## 6. CLI System\n\n### 6.1 Interactive CLI (cli.py)\n\nThe `HermesCLI` class provides the interactive terminal interface.\n\n**Features:**\n\n- **Rich** for banner\u002Fpanels, **prompt_toolkit** for input with autocomplete\n- **KawaiiSpinner** — animated faces during API calls, `┊` activity feed for tool results\n- Multiline editing with Shift+Enter\n- Slash-command autocomplete\n- Session history with up\u002Fdown arrow navigation\n- Clipboard image paste (Alt+V \u002F Ctrl+V)\n- Status bar showing model, provider, and token counts\n- Inline diff previews for file write\u002Fpatch operations\n\n**Configuration Loading:**\n\n```python\nload_cli_config() → dict\n# Loads from ~\u002F.hermes\u002Fconfig.yaml (or .\u002Fcli-config.yaml fallback)\n# Merges with hardcoded defaults\n# Expands ${ENV_VAR} references\n# Maps terminal config → env vars\n```\n\n---\n\n### 6.2 CLI Entry Point (hermes_cli\u002Fmain.py)\n\nAll `hermes` subcommands are dispatched from here:\n\n```\nhermes                    # Default: interactive chat\nhermes chat               # Explicit interactive mode\nhermes gateway start|stop|status|install|uninstall\nhermes setup              # Setup wizard\nhermes model              # Select model\u002Fprovider\nhermes tools              # Configure tools\nhermes skills             # Manage skills\nhermes config set|get     # Direct config manipulation\nhermes cron list|delete   # Cron job management\nhermes doctor             # Diagnose issues\nhermes sessions browse    # Session picker\nhermes profile create|list|switch|delete|export|import\nhermes mcp serve|add|remove  # MCP management\nhermes acp                # Start ACP server\nhermes update|uninstall|version\n```\n\n**Profile System:**\n\n- `_apply_profile_override()` runs BEFORE any imports to set `HERMES_HOME`\n- Pre-parses `--profile\u002F-p` from argv\n- Allows fully isolated agent instances with separate config, memory, sessions, skills\n\n---\n\n### 6.3 Configuration System (hermes_cli\u002Fconfig.py)\n\n**Key Configuration Sections:**\n\n```yaml\nmodel: \"anthropic\u002Fclaude-opus-4.6\" # or dict with provider\u002Fbase_url\u002Fapi_key\nproviders: {} # Provider-specific configs\nfallback_providers: [] # Ordered failover list\ncredential_pool: {} # Multiple API keys per provider\n\nagent:\n  max_turns: 90\n  gateway_timeout: 1800\n  tool_use_enforcement: \"auto\"\n\nterminal:\n  backend: \"local\" # local|docker|modal|daytona|ssh|singularity\n  timeout: 180\n  persistent_shell: true\n  docker_image: \"nikolaik\u002Fpython-nodejs:...\"\n\ncompression:\n  enabled: true\n  threshold: 0.50 # Compress when 50% of context used\n  target_ratio: 0.20 # Summary = 20% of compressed content\n  protect_last_n: 20\n\nauxiliary:\n  vision: { provider, model }\n  web_extract: { provider, model }\n  compression: { provider, model }\n\nmemory:\n  memory_enabled: true\n  provider: \"\" # \"\" | \"honcho\" | \"mem0\" | etc.\n  memory_char_limit: 2200\n\ndisplay:\n  personality: \"kawaii\"\n  show_reasoning: false\n  inline_diffs: true\n  skin: \"default\"\n  streaming: true\n\ntts:\n  provider: \"edge\" # edge|elevenlabs|openai|neutts\n\nstt:\n  enabled: true\n  provider: \"local\" # local|groq|openai\n\nprivacy:\n  redact_pii: false\n\nmcp_servers: {} # MCP server configurations\n\nskills:\n  external_dirs: [] # Additional skill directories\n\napprovals:\n  mode: \"smart\" # smart|always|off\n```\n\n**Config Files:**\n\n- `~\u002F.hermes\u002Fconfig.yaml` — User settings (authoritative)\n- `~\u002F.hermes\u002F.env` — API keys and secrets\n- Config version migration system (currently v5)\n\n---\n\n### 6.4 Slash Command Registry (hermes_cli\u002Fcommands.py)\n\nAll slash commands defined centrally in `COMMAND_REGISTRY`:\n\n```python\nCommandDef(name, description, category, aliases, args_hint, cli_only, gateway_only)\n```\n\n**Derived automatically by:**\n\n- CLI `process_command()` — dispatch on canonical name\n- Gateway dispatch + help\n- Telegram BotCommand menu\n- Slack `\u002Fhermes` subcommands\n- Autocomplete + help text\n\n**Key Commands:**\n\n| Command        | Aliases    | Description                   |\n| -------------- | ---------- | ----------------------------- |\n| `\u002Fnew`         | `\u002Freset`   | Start fresh conversation      |\n| `\u002Fmodel`       |            | Show\u002Fswitch model             |\n| `\u002Fpersonality` |            | Set agent personality         |\n| `\u002Fretry`       |            | Retry last turn               |\n| `\u002Fundo`        |            | Remove last turn              |\n| `\u002Fcompress`    | `\u002Fcompact` | Compress context              |\n| `\u002Fusage`       | `\u002Fcost`    | Show token usage              |\n| `\u002Finsights`    |            | Usage analytics               |\n| `\u002Fskills`      |            | Browse\u002Finstall skills         |\n| `\u002Fbackground`  | `\u002Fbg`      | Manage background processes   |\n| `\u002Fplan`        |            | Generate implementation plan  |\n| `\u002Frollback`    |            | Restore filesystem checkpoint |\n| `\u002Fverbose`     |            | Toggle debug output           |\n| `\u002Freasoning`   |            | Set reasoning effort          |\n| `\u002Fyolo`        |            | Toggle approval bypass        |\n| `\u002Fbtw`         |            | Ephemeral side question       |\n| `\u002Fstop`        |            | Kill current agent run        |\n| `\u002Fqueue`       |            | Queue next prompt             |\n| `\u002Fbrowser`     |            | Interactive browser session   |\n| `\u002Fhistory`     | `\u002Fresume`  | Session browser               |\n| `\u002Fskin`        |            | Switch CLI theme              |\n\n---\n\n### 6.5 Setup Wizard (hermes_cli\u002Fsetup.py)\n\nModular interactive wizard with independent sections:\n\n1. **Model & Provider** — Select AI provider, enter API keys, choose model\n2. **Terminal Backend** — Choose execution environment\n3. **Agent Settings** — Max iterations, compression, session policies\n4. **Messaging Platforms** — Configure Telegram, Discord, Slack, etc.\n5. **Tools** — TTS, STT, web search, image generation, browser\n\nFeatures:\n\n- Live credential validation\n- Real-time model list fetching from provider APIs\n- Automatic OpenClaw migration detection\n- Atomic config file writes\n\n---\n\n### 6.6 Model Catalog (hermes_cli\u002Fmodels.py)\n\nProvider-specific model lists:\n\n```python\n_PROVIDER_MODELS = {\n    \"nous\": [\"anthropic\u002Fclaude-opus-4.6\", \"anthropic\u002Fclaude-sonnet-4.6\", ...],  # 25+\n    \"openrouter\": [\"anthropic\u002Fclaude-opus-4.6\", \"google\u002Fgemini-3-flash\", ...],  # 30+\n    \"anthropic\": [\"claude-opus-4-6\", \"claude-sonnet-4-6\", ...],\n    \"openai\": [\"gpt-5\", \"gpt-5.4-mini\", \"gpt-4.1\", \"gpt-4o\", ...],\n    \"copilot\": [\"gpt-5.4\", \"gpt-5.4-mini\", \"gpt-5.3-codex\", ...],\n    \"huggingface\": [...],\n    \"minimax\": [...],\n    \"kimi-coding\": [...],\n    \"alibaba\": [...],\n    \"deepseek\": [...],\n    # ... more providers\n}\n```\n\nFeatures:\n\n- Dynamic fetching via provider `\u002Fmodels` endpoints\n- Curated lists used when live probe returns fewer models\n- Fuzzy matching for typo correction\n- Validation against provider catalog\n\n---\n\n### 6.7 Skin\u002FTheme Engine (hermes_cli\u002Fskin_engine.py)\n\nData-driven CLI visual customization — no code changes needed.\n\n**Customizable Elements:**\n\n| Element                          | Key                      | Used By           |\n| -------------------------------- | ------------------------ | ----------------- |\n| Banner border\u002Ftitle\u002Faccent       | `colors.*`               | banner.py         |\n| Response box border              | `colors.response_border` | cli.py            |\n| Spinner faces (waiting\u002Fthinking) | `spinner.*`              | display.py        |\n| Spinner verbs\u002Fwings              | `spinner.*`              | display.py        |\n| Tool output prefix               | `tool_prefix`            | display.py        |\n| Per-tool emojis                  | `tool_emojis`            | display.py        |\n| Agent name\u002Fwelcome\u002Fprompt        | `branding.*`             | banner.py, cli.py |\n\n**Built-in Skins:** default, ares, mono, slate, poseidon, sisyphus, charizard\n\n**User Skins:** Drop `~\u002F.hermes\u002Fskins\u002F\u003Cname>.yaml` and activate with `\u002Fskin \u003Cname>`\n\n---\n\n## 7. Tool System\n\n### 7.1 Terminal Tool (tools\u002Fterminal_tool.py)\n\nShell command execution across multiple backends.\n\n```python\ndef terminal_tool(\n    command: str,\n    background: bool = False,\n    timeout: Optional[int] = None,\n    task_id: Optional[str] = None,\n    force: bool = False,        # Skip approval for dangerous commands\n    workdir: Optional[str] = None,\n    check_interval: Optional[int] = None,  # Background task polling\n    pty: bool = False,\n) -> str  # JSON result\n```\n\n**Features:**\n\n- Multi-backend: Selects based on `TERMINAL_ENV` (local\u002Fdocker\u002Fssh\u002Fmodal\u002Fdaytona\u002Fsingularity)\n- Per-task_id sandboxes with thread-safe creation locks\n- Dangerous command routing through approval system\n- Background task support with file-based IPC\n- Interrupt handling — polls `is_interrupted()` during execution\n- Auto-cleanup daemon thread for idle environments (>300s)\n- Disk usage warnings at configurable threshold\n\n---\n\n### 7.2 File Tools (tools\u002Ffile_tools.py)\n\nSafe file operations with size guards and sensitive path protection.\n\n- `read_file_tool(path, offset, limit)` — Read with pagination (default 100K char limit)\n- `write_file_tool(path, content)` — Write with approval for sensitive paths\n- `edit_file_tool(path, old_text, new_text)` — String replacement editing\n- `list_files_tool(path)` — Directory listing\n- `search_files_tool(pattern, path)` — Glob\u002Fregex file search\n\n**Safety:**\n\n- Device path blocklist (`\u002Fdev\u002Fzero`, `\u002Fdev\u002Fstdin`, etc.)\n- Read dedup tracking — returns stub on re-read if mtime unchanged\n- Sensitive path blocking: `\u002Fetc\u002F`, `\u002Fboot\u002F`, `~\u002F.ssh` without approval\n- Prompt injection protection for known dangerous paths\n\n---\n\n### 7.3 Web Tools (tools\u002Fweb_tools.py)\n\nWeb search and content extraction.\n\n- `web_search_tool(query, limit)` — Search via configurable backend\n- `web_extract_tool(urls, format)` — Extract content from URLs\n- `web_crawl_tool(url, instructions)` — LLM-guided web crawling\n\n**Backends:** Firecrawl, Parallel Web, Tavily, Exa, DuckDuckGo\n\n- Fallback detection by highest-priority available API key\n- LLM processing via auxiliary client (Gemini 3 Flash) for intelligent extraction\n- SSRF protection and URL safety checks\n\n---\n\n### 7.4 Browser Tool (tools\u002Fbrowser_tool.py)\n\nHeadless browser automation with accessibility tree.\n\n```python\nbrowser_navigate(url, task_id) → str\nbrowser_snapshot(task_id, max_chars) → str\nbrowser_click(ref, task_id) → str      # Element refs like @e1, @e2\nbrowser_type(ref, text, task_id) → str\nbrowser_scroll(ref, direction, task_id) → str\nbrowser_extract(task, max_chars, task_id) → str\n```\n\n**Backends:**\n\n- **Local:** Headless Chromium via `agent-browser` CLI\n- **Cloud:** Browserbase (stealth, proxies, CAPTCHA solving)\n- **Camofox:** Anti-detection browser using Camoufox\n\n**Features:**\n\n- Accessibility tree for text-based snapshots (no vision required)\n- Session isolation per task_id with inactivity cleanup\n- API key detection in URLs (prevents exfiltration)\n- SSRF protection for private\u002Finternal addresses\n\n---\n\n### 7.5 Delegate Tool (tools\u002Fdelegate_tool.py)\n\nSpawn isolated subagents for parallel workstreams.\n\n```python\ndef delegate_task(\n    goal: str,\n    context: str = None,\n    toolsets: List[str] = None,       # Default: [\"terminal\", \"file\", \"web\"]\n    tasks: List[Dict] = None,          # Batch mode: up to 3 concurrent\n    max_iterations: int = 50,\n    parent_agent = None,\n) → str\n```\n\n**Isolation:**\n\n- Fresh conversation (no parent history)\n- Own task_id (separate terminal session, file ops)\n- Restricted toolset (configurable, blocked tools always stripped)\n- Focused system prompt from goal + context\n- Parent only sees delegation call and summary result\n\n**Blocked Tools:** delegate_task, clarify, memory, send_message, execute_code (no recursion, no user interaction)\n\n**Constraints:** MAX_DEPTH=2, MAX_CONCURRENT_CHILDREN=3\n\n---\n\n### 7.6 MCP Tool (tools\u002Fmcp_tool.py)\n\nModel Context Protocol client integration.\n\n**Configuration (config.yaml):**\n\n```yaml\nmcp_servers:\n  filesystem:\n    command: \"npx\"\n    args: [\"-y\", \"@modelcontextprotocol\u002Fserver-filesystem\", \"\u002Ftmp\"]\n    timeout: 120\n  remote_api:\n    url: \"https:\u002F\u002Fmy-mcp-server.example.com\u002Fmcp\"\n    headers:\n      Authorization: \"Bearer sk-...\"\n    sampling:\n      enabled: true\n      model: \"gemini-3-flash\"\n```\n\n**Features:**\n\n- **Transports:** Stdio (local processes) and HTTP\u002FStreamableHTTP (remote)\n- **Dynamic tool discovery:** Listens for `tools\u002Flist_changed` notifications\n- **Sampling support:** MCP servers can request LLM completions\n- **Automatic reconnection** with exponential backoff (5 retries)\n- Dedicated background event loop in daemon thread\n- Thread-safe via lock protecting server dict\n\n---\n\n### 7.7 Approval System (tools\u002Fapproval.py)\n\nDangerous command detection and approval flow.\n\n```python\ndetect_dangerous_command(command: str) → (is_dangerous, pattern_key, description)\n```\n\n**106 patterns covering:**\n\n- Destructive operations (`rm -r \u002F`, `mkfs`, `dd if=`)\n- Privilege escalation (`chmod 777`, `chown -R root`)\n- SQL injection (`DROP TABLE`, `DELETE FROM` without WHERE)\n- System targeting (`\u002Fetc\u002F` writes, `systemctl stop`, fork bombs)\n- Shell injection (pipe to sh, wget to sh, process substitution)\n- Network exfiltration (curl with embedded API keys)\n- Secret access (`cat ~\u002F.env`, `cat ~\u002F.netrc`)\n\n**Normalization:** Strips ANSI escapes, null bytes, normalizes Unicode\n\n**Approval Modes:**\n\n- `smart` — Learns which commands are safe based on user decisions\n- `always` — Always ask for dangerous commands\n- `off` — Never ask (or `\u002Fyolo` toggle)\n\n---\n\n### 7.8 Terminal Backends (tools\u002Fenvironments\u002F)\n\n| Backend           | File               | Features                                                                       |\n| ----------------- | ------------------ | ------------------------------------------------------------------------------ |\n| **Local**         | `local.py`         | Direct execution, interrupt support, non-blocking I\u002FO, persistent shell        |\n| **Docker**        | `docker.py`        | Sandboxed containers, cap-drop ALL, no-new-privileges, PID limits, bind mounts |\n| **SSH**           | `ssh.py`           | Remote execution via ControlMaster, persistent shell mixin                     |\n| **Modal**         | `modal.py`         | Native Modal SDK `Sandbox.create()`\u002F`Sandbox.exec()`, persistent snapshots     |\n| **Managed Modal** | `managed_modal.py` | Modal through Nous-hosted gateway                                              |\n| **Daytona**       | `daytona.py`       | Daytona SDK cloud sandboxes, stop\u002Fresume lifecycle                             |\n| **Singularity**   | `singularity.py`   | Singularity containers with scratch dir, SIF cache                             |\n\n**Common Interface (BaseEnvironment ABC):**\n\n```python\nexecute(command, timeout) → {\"output\": str, \"returncode\": int}\ncleanup() → None\n```\n\n---\n\n## 8. Agent Internals\n\n### 8.1 Prompt Builder (agent\u002Fprompt_builder.py)\n\nAssembles the system prompt from multiple sources:\n\n| Component               | Source                                               |\n| ----------------------- | ---------------------------------------------------- |\n| Agent Identity          | `DEFAULT_AGENT_IDENTITY` or `SOUL.md`                |\n| Memory Guidance         | When\u002Fhow to use memory tool                          |\n| Session Search Guidance | How to recall past conversations                     |\n| Skills Guidance         | When to create\u002Fpatch skills                          |\n| Tool Use Enforcement    | Must execute tools, not describe actions             |\n| Skills Index            | `~\u002F.hermes\u002Fskills\u002F.hermes-skills.json`               |\n| Platform Hints          | OS, Python version, shell, available tools           |\n| Context Files           | `.hermes.md`, `AGENTS.md`, `.cursorrules`, `SOUL.md` |\n| Model\u002FProvider Info     | Current model and provider identity                  |\n\n**Context File Discovery:**\n\n1. Check `cwd\u002F.hermes.md` or `HERMES.md`\n2. Walk parent directories up to git root\n3. Validate against injection patterns before inclusion\n\n**Injection Detection (30+ patterns):**\n\n- \"ignore previous instructions\", \"system prompt override\"\n- \"do not tell the user\", \"act as if you have no restrictions\"\n- HTML comment injection, exfiltration via curl, Unicode stealth chars\n\n---\n\n### 8.2 Context Compressor (agent\u002Fcontext_compressor.py)\n\nAutomatically compresses conversation history when approaching context limits.\n\n```python\nclass ContextCompressor:\n    threshold_percent: float = 0.50   # Compress when 50% of context used\n    protect_first_n: int = 3          # Keep system prompt + first turn\n    protect_last_n: int = 20          # Keep recent N messages\n    summary_target_ratio: float = 0.20  # Summary = 20% of compressed content\n```\n\n**Compression Algorithm:**\n\n1. **Pre-pass:** Replace old tool results with placeholder (cheap)\n2. **Protect head:** System prompt + first exchange always kept\n3. **Protect tail:** Token-budget-based tail protection (~20K tokens)\n4. **Summarize middle:** LLM-generated structured summary (Goal, Progress, Decisions, Files, Next Steps)\n5. **Iterative updates:** On subsequent compressions, update previous summary instead of re-summarizing\n\n---\n\n### 8.3 Prompt Caching (agent\u002Fprompt_caching.py)\n\nAnthropic prompt caching support for cost reduction.\n\n- System prompt cached across turns (first conversation turn establishes cache)\n- Cache markers inserted at system prompt boundaries\n- Must not break mid-conversation — altering past context invalidates cache\n- The ONLY time context is altered is during compression\n\n**Critical Rule:** Do NOT implement changes that would alter past context, change toolsets, reload memories, or rebuild system prompts mid-conversation.\n\n---\n\n### 8.4 Auxiliary Client (agent\u002Fauxiliary_client.py)\n\nSeparate LLM client for non-primary tasks:\n\n- **Vision analysis** — Image description and analysis\n- **Web extraction** — Content summarization\n- **Context compression** — Generating conversation summaries\n- **Session search** — Summarizing search results\n- **MCP sampling** — Serving server-initiated LLM requests\n\nConfigured per-task via `auxiliary` section in config.yaml.\n\n---\n\n### 8.5 Display & Spinner (agent\u002Fdisplay.py)\n\n- **KawaiiSpinner** — Animated face characters during API calls\n- **Tool preview formatting** — `┊` prefixed activity feed for tool execution\n- **Inline diff previews** — Shows unified diffs for write\u002Fpatch operations\n- Respects active skin for colors, emojis, and branding\n\n---\n\n### 8.6 Skill Commands (agent\u002Fskill_commands.py)\n\nShared skill invocation for CLI and gateway:\n\n- Skills loaded from `~\u002F.hermes\u002Fskills\u002F` and external directories\n- Injected as **user message** (not system prompt) to preserve prompt caching\n- `\u002Fplan` command generates implementation plans stored in `.hermes\u002Fplans\u002F`\n- Skill content includes setup instructions, tool options, usage examples\n\n---\n\n## 9. Messaging Gateway\n\n### 9.1 GatewayRunner (gateway\u002Frun.py)\n\nMain controller managing all platform adapters and routing messages.\n\n**Key Attributes:**\n\n- `adapters: Dict[Platform, BasePlatformAdapter]` — Active platform instances\n- `session_store: SessionStore` — Conversation persistence\n- `_running_agents: Dict[str, AIAgent]` — Per-session cached agents (preserves prompt caching)\n- `_pending_approvals: Dict[str, Dict]` — Dangerous command approval tracking\n- `pairing_store: PairingStore` — DM code-based user authorization\n\n**Message Flow:**\n\n1. Platform adapter queues `MessageEvent`\n2. GatewayRunner dequeues, calls `_handle_message()`\n3. Slash command? → dispatch to handler\n4. Regular message? → `_handle_message_with_agent()` (async, with per-session locking)\n5. Response delivered back via platform adapter\n\n**Features:**\n\n- Agent caching per session (preserves Anthropic prompt cache across turns)\n- Session reset policies (inactivity timeout, hard reset)\n- Per-session model overrides via `\u002Fmodel`\n- Background memory flush on session expiry\n- Approval routing (`\u002Fapprove`, `\u002Fdeny`) with interactive buttons (Discord)\n- 30+ slash command handlers\n\n---\n\n### 9.2 Session Store (gateway\u002Fsession.py)\n\n**SessionSource** — Where a message originated (platform, chat_id, user info)\n**SessionContext** — Full context for system prompt injection (platforms, home channels, metadata)\n**SessionStore** — Loads\u002Fsaves conversation transcripts as JSON files\n\n```\n~\u002F.hermes\u002Fsessions\u002F{session_key}.json\nFormat: [{role, content, timestamp}, ...]\n```\n\n**Features:**\n\n- Session key computed from platform + chat_id + thread_id (deterministic hash)\n- Inactivity timeout for session resets\n- PII redaction (phone numbers hashed)\n- Survives gateway restarts\n\n---\n\n### 9.3 Platform Adapters (gateway\u002Fplatforms\u002F)\n\n**16 adapters sharing `BasePlatformAdapter` interface:**\n\n| Platform           | Key Features                                                                                             |\n| ------------------ | -------------------------------------------------------------------------------------------------------- |\n| **Telegram**       | Polling + webhook mode, media handling, inline keyboards, forum topic isolation, group mention gating    |\n| **Discord**        | Server channels, threads, reactions (processing\u002Fdone\u002Ferror), button-based approval, @mention requirement |\n| **Slack**          | Multi-workspace OAuth, thread handling, app_mention, `\u002Fhermes` subcommands                               |\n| **WhatsApp**       | Group & DM support, media captions, LID↔phone alias resolution                                           |\n| **Matrix**         | E2EE room encryption, threaded messages, trusted device flow, native voice messages                      |\n| **Signal**         | Encrypted DMs, group membership, SSE keepalive, phone URL encoding                                       |\n| **Email**          | IMAP\u002FSMTP, multi-recipient, skip_attachments option                                                      |\n| **Home Assistant** | REST tools + WebSocket, service discovery, smart home automation                                         |\n| **SMS**            | Twilio integration                                                                                       |\n| **Mattermost**     | Self-hosted Slack alternative, configurable mention behavior                                             |\n| **DingTalk**       | Alibaba enterprise messaging                                                                             |\n| **Feishu\u002FLark**    | Enterprise messaging, message cards, approval workflows                                                  |\n| **WeCom**          | Enterprise WeChat, department management                                                                 |\n| **Webhook**        | Generic HTTP POST for custom integrations                                                                |\n| **API Server**     | OpenAI-compatible `\u002Fv1\u002Fchat\u002Fcompletions` endpoint                                                        |\n\n**Common Features:**\n\n- Image\u002Faudio caching for vision and STT tools\n- Rate limiting with exponential backoff\n- Session routing with authorization rules\n- Cross-platform conversation continuity\n\n---\n\n## 10. Cron Scheduling\n\nBuilt-in job scheduler running in the gateway background thread.\n\n**Schedule Types:**\n\n- `\"once in 5m\"` — One-shot after duration\n- `\"every 30m\"` — Recurring interval\n- `\"0 9 * * *\"` — Standard cron expression\n- `\"2026-04-06T14:00\"` — Absolute datetime\n\n**Job Storage:** `~\u002F.hermes\u002Fcron\u002Fjobs.json`\n\n**Execution Flow:**\n\n1. `tick()` called every 60s from gateway background thread\n2. Fetch due jobs past `next_run_at`\n3. Spawn `hermes` CLI subprocess with job prompt + skills\n4. Capture output → save to `~\u002F.hermes\u002Fcron\u002Foutput\u002F{job_id}\u002F{timestamp}.md`\n5. Deliver to target platform (or stay local)\n\n**Delivery Targets:**\n\n- `\"local\"` — Output saved locally only\n- `\"origin\"` — Send to originating chat\n- `\"telegram:\u003Cchat_id>\"` — Explicit platform\u002Fchat routing\n- `[SILENT]` prefix — Suppress delivery but keep logs\n\n**Grace Windows:** Based on schedule frequency (120s–2hrs) to handle missed jobs\n\n---\n\n## 11. Skills System\n\n**Skills are composable, agent-invokable knowledge units.**\n\n**Structure:**\n\n```\nskills\u002F\n├── creative\u002F              # ASCII art, diagrams, music\n├── software-development\u002F  # Debugging, testing, docs\n├── github\u002F                # Codebase inspection, PR workflow\n├── research\u002F              # Literature, web scraping\n├── productivity\u002F          # Task management\n├── media\u002F                 # Image, video, audio processing\n├── mlops\u002F                 # ML experiment tracking\n├── autonomous-ai-agents\u002F  # Multi-agent orchestration\n└── [20+ more categories]\n```\n\n**Per-Skill Structure:**\n\n```\nskill-name\u002F\n├── SKILL.md     # Metadata (YAML frontmatter) + implementation instructions\n└── [sub-skills]\u002F\n```\n\n**SKILL.md Example:**\n\n```yaml\n---\nname: ascii-art\ndescription: Generate ASCII art using multiple tools\nversion: 4.0.0\ndependencies: []\nmetadata:\n  hermes:\n    tags: [ASCII, Art, Banners, Creative]\n    related_skills: [excalidraw]\n---\n[Implementation instructions, tool options, examples...]\n```\n\n**Discovery:**\n\n- Auto-discovered from `~\u002F.hermes\u002Fskills\u002F` + external dirs\n- Skills index built at startup (`.hermes-skills.json`)\n- Loaded as user messages to preserve prompt caching\n- Per-platform enable\u002Fdisable via `hermes skills`\n- Skills Hub (`agentskills.io`) for community sharing\n\n---\n\n## 12. Plugin System\n\nDrop Python files into `~\u002F.hermes\u002Fplugins\u002F` to extend Hermes.\n\n**Plugin Capabilities:**\n\n- Register custom tools and toolsets\n- Inject messages into conversation\n- Lifecycle hooks: `pre_llm_call`, `post_llm_call`, `on_session_start`, `on_session_end`\n- Enable\u002Fdisable via `hermes plugins enable\u002Fdisable \u003Cname>`\n\n**Memory Provider Plugins (plugins\u002Fmemory\u002F):**\n8 implementations: openviking, mem0, hindsight, holographic, honcho, retaindb, byterover\n\nEach implements:\n\n```python\nclass MemoryProvider:\n    def is_available() → bool\n    def store(key, value)\n    def retrieve(query) → list\n    def clear()\n```\n\n---\n\n## 13. Memory System\n\nHermes has a pluggable memory provider interface:\n\n**Built-in Memory:**\n\n- `MEMORY.md` — Markdown file with persistent facts\n- `USER.md` — User profile information\n- Memory read\u002Fwrite tools called by agent during conversation\n- Periodic nudges prompt agent to save important information\n- FTS5 session search for cross-session recall\n\n**Honcho Integration:**\n\n- AI-native dialectic user modeling\n- Async memory writes\n- Profile-scoped host\u002Fpeer resolution\n- Multi-user isolation in gateway mode\n\n**Configuration:**\n\n```yaml\nmemory:\n  memory_enabled: true\n  provider: \"\" # \"\" for built-in, \"honcho\", \"mem0\", etc.\n  memory_char_limit: 2200\n```\n\n---\n\n## 14. ACP Server (IDE Integration)\n\nAgent Communication Protocol server for VS Code, Zed, JetBrains.\n\n**Entry:** `hermes acp` → `acp_adapter\u002Fserver.py`\n\n**HermesACPAgent Class:**\n\n```python\ninitialize()                    # Handshake with IDE client\nauthenticate(method_id)         # Validate credentials\nnew_session(cwd, mcp_servers)   # Create isolated session\nload_session(session_id)        # Resume session\nfork_session(session_id)        # Branch for parallel work\nlist_sessions()                 # Browse all sessions\ncancel(session_id)              # Interrupt running agent\n```\n\n**Features:**\n\n- Slash command support (`\u002Fmodel`, `\u002Ftools`, `\u002Freset`, `\u002Fcompact`)\n- Client-provided MCP servers (IDE's MCP ecosystem flows into agent)\n- Streaming callbacks for messages, thinking, tool progress\n- Dangerous command approval via IDE UI\n\n---\n\n## 15. API Server\n\nOpenAI-compatible API endpoint for headless integrations (e.g., Open WebUI).\n\n**Endpoint:** `POST \u002Fv1\u002Fchat\u002Fcompletions`\n\n**Features:**\n\n- `X-Hermes-Session-Id` header for persistent sessions\n- Tool progress streaming via SSE events\n- `\u002Fapi\u002Fjobs` REST API for cron management\n- Input limits, field whitelists, SQLite-backed response persistence\n- CORS origin protection\n\n---\n\n## 16. MCP Server Mode\n\nExpose Hermes conversations to MCP-compatible clients.\n\n**Entry:** `hermes mcp serve`\n\n**Features:**\n\n- Browse conversations and sessions\n- Read messages and search across sessions\n- Manage attachments\n- Supports both stdio and Streamable HTTP transports\n- Compatible with Claude Desktop, Cursor, VS Code, etc.\n\n---\n\n## 17. RL Training Environments\n\nAtropos-based RL training framework for agent policy optimization.\n\n**Base Class:** `HermesAgentBaseEnv` (extends `atroposlib.BaseEnv`)\n\n**Configuration:**\n\n```python\nHermesAgentEnvConfig:\n    enabled_toolsets: [\"terminal\", \"file\", \"web\"]\n    max_agent_turns: 30\n    agent_temperature: 1.0\n    terminal_backend: \"local\"  # or docker\u002Fmodal for isolation\n    dataset_name: str\n```\n\n**Subclass Requirements:**\n\n- `setup()` — Load dataset\n- `get_next_item()` — Return next task\n- `format_prompt()` — Convert item → user message\n- `compute_reward()` — Score rollout\n- `evaluate()` — Periodic eval on test set\n\n**Example Environments:**\n\n- `web_research_env.py` — Web research tasks\n- `agentic_opd_env.py` — Observation-Prediction-Demonstration\n- `hermes_swe_env.py` — Software engineering tasks\n\n**Supporting:**\n\n- `HermesAgentLoop` — Orchestrates step-by-step rollouts\n- `ToolContext` — Sandbox for tool execution, records side effects\n- `trajectory_compressor.py` — Compresses trajectories for training data\n\n---\n\n## 18. Profiles (Multi-Instance)\n\nRun multiple fully isolated Hermes instances from the same installation.\n\n**Commands:**\n\n```bash\nhermes profile create \u003Cname>\nhermes profile list\nhermes profile switch \u003Cname>\nhermes profile delete \u003Cname>\nhermes profile export \u003Cname>\nhermes profile import \u003Cfile>\nhermes -p \u003Cname>             # Launch with specific profile\n```\n\n**Each profile gets:**\n\n- Own `HERMES_HOME` directory (`~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F`)\n- Own config.yaml, .env, memory, sessions, skills, gateway service\n- Token-lock isolation (prevents two profiles sharing bot credentials)\n\n**Implementation:**\n\n- `_apply_profile_override()` sets `HERMES_HOME` env var before any imports\n- All 119+ references to `get_hermes_home()` automatically scope to active profile\n- Profile operations are HOME-anchored (`~\u002F.hermes\u002Fprofiles\u002F`) for cross-profile visibility\n\n---\n\n## 19. Security Model\n\n### Command Approval\n\n- 106 dangerous command patterns (destructive, privilege escalation, SQL, exfiltration)\n- Smart approval mode learns from user decisions\n- Session-based approval state (per-session tracking)\n- `--fuck-it-ship-it` flag or `\u002Fyolo` toggle to bypass\n\n### Secret Protection\n\n- Secret redaction in logs and tool output (API keys, tokens)\n- Browser URL scanning for embedded secrets\n- LLM response scanning for exfiltration attempts\n- Credential directory protection (`.docker`, `.azure`, `.config\u002Fgh`, `.ssh`)\n- `execute_code` sandbox output redaction\n\n### Input Safety\n\n- Prompt injection detection in context files (30+ patterns)\n- Unicode stealth character detection\n- ANSI escape sequence normalization\n- Device path blocklist for file reads\n- SSRF protection in web\u002Fbrowser tools\n\n### PII Handling\n\n- Optional `privacy.redact_pii` mode\n- Phone number hashing in session metadata\n- Sender ID anonymization in gateway logs\n\n### Supply Chain\n\n- All dependency version ranges pinned\n- `uv.lock` with hashes for reproducible builds\n- CI workflow scanning PRs for supply chain attack patterns\n- Compromised `litellm` dependency removed\n\n---\n\n## 20. Provider & Model System\n\n### Supported Providers\n\n| Provider              | API Mode           | Key Features                              |\n| --------------------- | ------------------ | ----------------------------------------- |\n| **Nous Portal**       | chat_completions   | 400+ models, first-class setup            |\n| **OpenRouter**        | chat_completions   | 200+ models, provider routing preferences |\n| **Anthropic**         | anthropic_messages | Native prompt caching, OAuth PKCE         |\n| **OpenAI**            | chat_completions   | GPT-5, Codex                              |\n| **GitHub Copilot**    | chat_completions   | OAuth, 400k context                       |\n| **Hugging Face**      | chat_completions   | Curated agentic model picker              |\n| **Google (Direct)**   | chat_completions   | Full Gemini context lengths               |\n| **z.ai\u002FGLM**          | chat_completions   | Chinese LLM models                        |\n| **Kimi\u002FMoonshot**     | chat_completions   | Kimi Code API                             |\n| **MiniMax**           | anthropic_messages | M2.7 models                               |\n| **Alibaba\u002FDashScope** | chat_completions   | Qwen models                               |\n| **DeepSeek**          | chat_completions   | V3 models                                 |\n| **Vercel AI Gateway** | chat_completions   | Routing through Vercel                    |\n| **Kilo Code**         | chat_completions   | Custom provider                           |\n| **OpenCode Zen\u002FGo**   | chat_completions   | Custom provider                           |\n| **Custom Endpoint**   | configurable       | Any OpenAI-compatible API                 |\n\n### Provider Features\n\n- **Ordered fallback chain:** Auto-failover across configured providers on errors\n- **Credential pools:** Multiple API keys per provider with `least_used` rotation\n- **Per-turn primary restoration:** After fallback use, restore primary on next turn\n- **Context length detection:** models.dev integration, provider-aware resolution, `\u002Fv1\u002Fprops` for llama.cpp\n- **Rate limit handling:** User-friendly 429 messages with Retry-After countdown\n- **Anthropic long-context tier:** Auto-reduces to 200k on tier limit 429\n\n---\n\n## 21. Streaming & Reasoning\n\n### Streaming\n\n- Enabled by default in CLI and gateway\n- Token-by-token delivery via `stream_delta_callback`\n- Proper spinner\u002Ftool progress display during streaming\n- Stale connection detection (90s timeout)\n- Fallback to non-streaming if provider doesn't support it\n\n### Reasoning\u002FThinking\n\n- Configurable effort: xhigh, high, medium, low, minimal, none\n- `\u002Freasoning` command to toggle display and effort level\n- Anthropic thinking blocks preserved across multi-turn conversations\n- `\u003Cthink>` tag extraction for compatible models\n- Reasoning persisted to SessionDB (v6 schema) for cross-session continuity\n- Thinking-budget exhaustion detection to skip useless continuation retries\n\n---\n\n## 22. Release History\n\n### v0.2.0 (March 12, 2026) — The Foundation Release\n\n> 216 merged PRs from 63 contributors, resolving 119 issues\n\n- Multi-platform messaging gateway (Telegram, Discord, Slack, WhatsApp, Signal, Email, Home Assistant)\n- MCP client support (stdio + HTTP)\n- 70+ skills across 15+ categories\n- Centralized provider router (`call_llm()` API)\n- ACP server for IDE integration\n- CLI skin\u002Ftheme engine\n- Git worktree isolation (`hermes -w`)\n- Filesystem checkpoints and `\u002Frollback`\n- 3,289 tests\n\n### v0.3.0 (March 17, 2026) — Streaming, Plugins, Providers\n\n- Unified streaming infrastructure (token-by-token delivery)\n- First-class plugin architecture (`~\u002F.hermes\u002Fplugins\u002F`)\n- Native Anthropic provider with prompt caching\n- Smart approvals + `\u002Fstop` command\n- Honcho memory integration\n- Voice mode (CLI push-to-talk, Telegram\u002FDiscord voice)\n- Concurrent tool execution (ThreadPoolExecutor)\n- PII redaction\n- `\u002Fbrowser connect` via Chrome DevTools Protocol\n- Vercel AI Gateway provider\n- Persistent shell mode for local\u002FSSH backends\n- Agentic On-Policy Distillation RL environment\n\n### v0.4.0 (March 23, 2026) — Platform Expansion\n\n- OpenAI-compatible API server (`\u002Fv1\u002Fchat\u002Fcompletions`)\n- 6 new messaging adapters (Signal rewrite, DingTalk, SMS, Mattermost, Matrix, Webhook)\n- `@file` and `@url` context references with tab completion\n- 4 new providers (GitHub Copilot, Alibaba, Kilo Code, OpenCode)\n- MCP server management CLI with OAuth 2.1 PKCE\n- Gateway prompt caching (dramatic cost reduction)\n- Context compression overhaul (structured summaries, iterative updates)\n- Streaming enabled by default\n- 200+ bug fixes\n\n### v0.5.0 (March 28, 2026) — Hardening\n\n- Nous Portal expanded to 400+ models\n- Hugging Face as first-class provider\n- Telegram Private Chat Topics\n- Native Modal SDK backend (replaced swe-rex)\n- Plugin lifecycle hooks activated\n- GPT model tool-use enforcement\n- Nix flake with NixOS module\n- Supply chain hardening (removed litellm, pinned deps, CI scanning)\n- Anthropic per-model output limits (128K for Opus 4.6)\n\n### v0.6.0 (March 30, 2026) — Multi-Instance\n\n> 95 PRs and 16 resolved issues in 2 days\n\n- Profiles for multiple isolated agent instances\n- MCP Server Mode (`hermes mcp serve`)\n- Official Docker container\n- Ordered fallback provider chain\n- Feishu\u002FLark platform adapter\n- WeCom (Enterprise WeChat) adapter\n- Slack multi-workspace OAuth\n- Telegram webhook mode + group controls\n- Exa search backend\n- Skills & credentials on remote backends\n\n### v0.7.0 (April 3, 2026) — Resilience\n\n> 168 PRs and 46 resolved issues\n\n- Pluggable memory provider interface (ABC-based plugin system)\n- Same-provider credential pools with automatic rotation\n- Camofox anti-detection browser backend\n- Inline diff previews in tool activity feed\n- API server session continuity + tool streaming\n- ACP client-provided MCP servers\n- Gateway hardening (race conditions, approval routing, compression death spirals)\n- Secret exfiltration blocking (URL scanning, base64 detection)\n\n---\n\n## 23. File Dependency Chain\n\n```\nhermes_constants.py  (no deps — imported by everything)\n       ↑\ntools\u002Fregistry.py  (no tool deps — imported by all tool files)\n       ↑\ntools\u002F*.py  (each calls registry.register() at import time)\n       ↑\nmodel_tools.py  (imports tools\u002Fregistry + triggers tool discovery)\n       ↑\nrun_agent.py (AIAgent), cli.py (HermesCLI), gateway\u002Frun.py (GatewayRunner)\n       ↑\nhermes_cli\u002Fmain.py  (entry point — dispatches to all subsystems)\n```\n\n**Key Principle:** `tools\u002Fregistry.py` is circular-import safe. It has no tool dependencies. Tool files import the registry; `model_tools.py` imports both.\n\n---\n\n## 24. Key Design Patterns\n\n| Pattern                        | Description                                                                                        |\n| ------------------------------ | -------------------------------------------------------------------------------------------------- |\n| **Registry-based Tool System** | Single source of truth; plugins register at import time; dynamic (MCP) and static tools coexist    |\n| **Toolset Composition**        | Recursive resolution with cycle detection; platform-specific composites                            |\n| **Iteration Budget**           | Thread-safe shared budget across parent + subagents                                                |\n| **Streaming First**            | Preferred over non-streaming for health checking (stale connection detection)                      |\n| **Prefix Caching**             | System prompt cached across turns (Anthropic optimization); context never altered mid-conversation |\n| **Proactive Compression**      | Triggered at 50% context usage; structured summaries with iterative updates                        |\n| **Async Bridging**             | Persistent event loops prevent \"Event loop is closed\"; per-thread loops for workers                |\n| **Profile Isolation**          | HERMES_HOME env var set before imports; all state functions route through `get_hermes_home()`      |\n| **Agent Caching**              | Gateway caches AIAgent per session to preserve prompt cache across turns                           |\n| **WAL Concurrency**            | SQLite WAL mode + jitter retry for concurrent readers + single writer                              |\n| **Plugin Architecture**        | Tools, toolsets, hooks, memory providers extensible via plugins                                    |\n| **Multi-Backend Execution**    | Pluggable terminal backends with unified BaseEnvironment interface                                 |\n| **Safety Layers**              | Approval system → sensitive path guards → injection detection → capability filtering               |\n\n---\n\n## 25. Configuration Reference\n\n### Environment Variables (key ones)\n\n| Variable              | Purpose                                                   |\n| --------------------- | --------------------------------------------------------- |\n| `HERMES_HOME`         | Override home directory (profiles set this automatically) |\n| `OPENROUTER_API_KEY`  | OpenRouter provider key                                   |\n| `ANTHROPIC_API_KEY`   | Anthropic provider key                                    |\n| `OPENAI_API_KEY`      | OpenAI provider key                                       |\n| `NOUS_API_KEY`        | Nous Portal key                                           |\n| `FIRECRAWL_API_KEY`   | Web search\u002Fextraction                                     |\n| `EXA_API_KEY`         | Exa search backend                                        |\n| `BROWSERBASE_API_KEY` | Cloud browser                                             |\n| `FAL_KEY`             | Image generation                                          |\n| `ELEVENLABS_API_KEY`  | Premium TTS                                               |\n| `HONCHO_API_KEY`      | Honcho memory                                             |\n| `TERMINAL_ENV`        | Terminal backend override                                 |\n| `TERMINAL_CWD`        | Terminal working directory                                |\n| `MESSAGING_CWD`       | Gateway working directory                                 |\n\n### Config File Locations\n\n| File                          | Purpose                          |\n| ----------------------------- | -------------------------------- |\n| `~\u002F.hermes\u002Fconfig.yaml`       | Main configuration (YAML)        |\n| `~\u002F.hermes\u002F.env`              | API keys and secrets             |\n| `~\u002F.hermes\u002FMEMORY.md`         | Persistent agent memory          |\n| `~\u002F.hermes\u002FUSER.md`           | User profile                     |\n| `~\u002F.hermes\u002FSOUL.md`           | Agent persona\u002Fidentity           |\n| `~\u002F.hermes\u002Fsessions.db`       | SQLite session database          |\n| `~\u002F.hermes\u002Fcron\u002Fjobs.json`    | Cron job definitions             |\n| `.hermes.md` (in project dir) | Per-project context file         |\n| `AGENTS.md` (in project dir)  | Developer instructions for agent |\n\n---\n\n## 26. Known Pitfalls\n\n1. **DO NOT hardcode `~\u002F.hermes` paths** — Use `get_hermes_home()` from `hermes_constants`. Hardcoding breaks profiles.\n\n2. **DO NOT use `simple_term_menu`** — Rendering bugs in tmux\u002FiTerm2 (ghosting). Use `curses` instead.\n\n3. **DO NOT use `\\033[K`** (ANSI erase-to-EOL) — Leaks as literal text under prompt_toolkit's `patch_stdout`. Use space-padding.\n\n4. **`_last_resolved_tool_names` is process-global** — Saved\u002Frestored around subagent execution in `delegate_tool.py`.\n\n5. **DO NOT hardcode cross-tool references in schemas** — Tool may be unavailable. Add dynamic references in `get_tool_definitions()`.\n\n6. **Tests must not write to `~\u002F.hermes\u002F`** — `_isolate_hermes_home` autouse fixture redirects to temp dir.\n\n7. **Prompt caching must not break** — Do NOT alter past context, change toolsets, reload memories, or rebuild system prompts mid-conversation.\n\n8. **Working directory behavior differs:** CLI uses `os.getcwd()`, gateway uses `MESSAGING_CWD` env var.\n\n9. **Config has three loaders:** `load_cli_config()` (CLI), `load_config()` (hermes tools\u002Fsetup), direct YAML (gateway). They have different merge behaviors.\n\n10. **Profile operations are HOME-anchored** — `_get_profiles_root()` returns `Path.home() \u002F \".hermes\" \u002F \"profiles\"`, NOT `get_hermes_home() \u002F \"profiles\"`. This is intentional for cross-profile visibility.\n\n---\n\n_This document covers Hermes Agent v0.7.0 as of April 2026. For the latest information, refer to the [official documentation](https:\u002F\u002Fhermes-agent.nousresearch.com\u002Fdocs\u002F) and the [GitHub repository](https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent)._\n","# Hermes Agent - Complete Project Guide (A-Z)\n\n> **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.\n\n---\n\n## Table of Contents\n\n1. [Project Overview](#1-project-overview)\n2. [Key Features Summary](#2-key-features-summary)\n3. [Installation & Getting Started](#3-installation--getting-started)\n4. [Project Structure](#4-project-structure)\n5. [Core Architecture](#5-core-architecture)\n   - 5.1 [AIAgent Class (run_agent.py)](#51-aiagent-class-run_agentpy)\n   - 5.2 [Tool Orchestration (model_tools.py)](#52-tool-orchestration-model_toolspy)\n   - 5.3 [Toolset System (toolsets.py)](#53-toolset-system-toolsetspy)\n   - 5.4 [Tool Registry (tools\u002Fregistry.py)](#54-tool-registry-toolsregistrypy)\n   - 5.5 [Session Database (hermes_state.py)](#55-session-database-hermes_statepy)\n   - 5.6 [Constants & Home Directory (hermes_constants.py)](#56-constants--home-directory-hermes_constantspy)\n6. [CLI System](#6-cli-system)\n   - 6.1 [Interactive CLI (cli.py)](#61-interactive-cli-clipy)\n   - 6.2 [CLI Entry Point (hermes_cli\u002Fmain.py)](#62-cli-entry-point-hermes_climainpy)\n   - 6.3 [Configuration System (hermes_cli\u002Fconfig.py)](#63-configuration-system-hermes_cliconfigpy)\n   - 6.4 [Slash Command Registry (hermes_cli\u002Fcommands.py)](#64-slash-command-registry-hermes_clicommandspy)\n   - 6.5 [Setup Wizard (hermes_cli\u002Fsetup.py)](#65-setup-wizard-hermes_clisetupy)\n   - 6.6 [Model Catalog (hermes_cli\u002Fmodels.py)](#66-model-catalog-hermes_climodelspy)\n   - 6.7 [Skin\u002FTheme Engine (hermes_cli\u002Fskin_engine.py)](#67-skintheme-engine-hermes_cliskin_enginepy)\n7. [Tool System](#7-tool-system)\n   - 7.1 [Terminal Tool (tools\u002Fterminal_tool.py)](#71-terminal-tool-toolsterminal_toolpy)\n   - 7.2 [File Tools (tools\u002Ffile_tools.py)](#72-file-tools-toolsfile_toolspy)\n   - 7.3 [Web Tools (tools\u002Fweb_tools.py)](#73-web-tools-toolsweb_toolspy)\n   - 7.4 [Browser Tool (tools\u002Fbrowser_tool.py)](#74-browser-tool-toolsbrowser_toolpy)\n   - 7.5 [Delegate Tool (tools\u002Fdelegate_tool.py)](#75-delegate-tool-toolsdelegate_toolpy)\n   - 7.6 [MCP Tool (tools\u002Fmcp_tool.py)](#76-mcp-tool-toolsmcp_toolpy)\n   - 7.7 [Approval System (tools\u002Fapproval.py)](#77-approval-system-toolsapprovalpy)\n   - 7.8 [Terminal Backends (tools\u002Fenvironments\u002F)](#78-terminal-backends-toolsenvironments)\n8. [Agent Internals](#8-agent-internals)\n   - 8.1 [Prompt Builder (agent\u002Fprompt_builder.py)](#81-prompt-builder-agentprompt_builderpy)\n   - 8.2 [Context Compressor (agent\u002Fcontext_compressor.py)](#82-context-compressor-agentcontext_compressorpy)\n   - 8.3 [Prompt Caching (agent\u002Fprompt_caching.py)](#83-prompt-caching-agentprompt_cachingpy)\n   - 8.4 [Auxiliary Client (agent\u002Fauxiliary_client.py)](#84-auxiliary-client-agentauxiliary_clientpy)\n   - 8.5 [Display & Spinner (agent\u002Fdisplay.py)](#85-display--spinner-agentdisplaypy)\n   - 8.6 [Skill Commands (agent\u002Fskill_commands.py)](#86-skill-commands-agentskill_commandspy)\n9. [Messaging Gateway](#9-messaging-gateway)\n   - 9.1 [GatewayRunner (gateway\u002Frun.py)](#91-gatewayrunner-gatewayrunpy)\n   - 9.2 [Session Store (gateway\u002Fsession.py)](#92-session-store-gatewaysessionpy)\n   - 9.3 [Platform Adapters (gateway\u002Fplatforms\u002F)](#93-platform-adapters-gatewayplatforms)\n10. [Cron Scheduling](#10-cron-scheduling)\n11. [Skills System](#11-skills-system)\n12. [Plugin System](#12-plugin-system)\n13. [Memory System](#13-memory-system)\n14. [ACP Server (IDE Integration)](#14-acp-server-ide-integration)\n15. [API Server](#15-api-server)\n16. [MCP Server Mode](#16-mcp-server-mode)\n17. [RL Training Environments](#17-rl-training-environments)\n18. [Profiles (Multi-Instance)](#18-profiles-multi-instance)\n19. [Security Model](#19-security-model)\n20. [Provider & Model System](#20-provider--model-system)\n21. [Streaming & Reasoning](#21-streaming--reasoning)\n22. [Release History](#22-release-history)\n23. [File Dependency Chain](#23-file-dependency-chain)\n24. [Key Design Patterns](#24-key-design-patterns)\n25. [Configuration Reference](#25-configuration-reference)\n26. [Known Pitfalls](#26-known-pitfalls)\n\n---\n\n## 1. Project Overview\n\n**Hermes Agent** is a self-improving AI agent built by [Nous Research](https:\u002F\u002Fnousresearch.com). It is an open-source (MIT licensed), Python-based project that provides:\n\n- A **full interactive terminal UI** (CLI) for conversing with LLMs\n- A **messaging gateway** supporting 16+ platforms (Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, etc.)\n- 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\n- **40+ built-in tools** — terminal execution, file manipulation, web search, browser automation, code execution, image generation, TTS\u002FSTT, and more\n- **Any LLM provider** — OpenRouter (200+ models), Nous Portal (400+ models), OpenAI, Anthropic, Hugging Face, GitHub Copilot, z.ai\u002FGLM, Kimi\u002FMoonshot, MiniMax, Alibaba\u002FDashScope, custom endpoints\n- **Six terminal backends** — local, Docker, SSH, Modal (serverless), Daytona (serverless), Singularity (HPC)\n- **Scheduled automations** via built-in cron scheduler\n- **IDE integration** via ACP (Agent Communication Protocol) for VS Code, Zed, JetBrains\n- **MCP integration** — both client (connect to any MCP server) and server (expose Hermes to MCP clients)\n- **RL training** via Atropos environments for training the next generation of tool-calling models\n\n**Tech Stack:**\n\n- Python 3.11+ (core agent, tools, gateway, cron)\n- Node.js (browser automation via agent-browser)\n- SQLite with WAL mode and FTS5 (session storage, full-text search)\n- OpenAI-compatible API (primary inference interface)\n- Anthropic SDK (native Anthropic support)\n- Rich + prompt_toolkit (CLI rendering)\n\n**Repository:** `github.com\u002FNousResearch\u002Fhermes-agent`\n**Version:** 0.7.0 (as of April 2026)\n**License:** MIT\n\n---\n\n## 2. Key Features Summary\n\n| Feature                      | Description                                                                                                                                                                      |\n| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **Terminal UI**              | Full TUI with multiline editing, slash-command autocomplete, conversation history, interrupt-and-redirect, streaming tool output                                                 |\n| **Multi-Platform Messaging** | Telegram, Discord, Slack, WhatsApp, Signal, Matrix, Email, Home Assistant, DingTalk, Feishu\u002FLark, WeCom, Mattermost, SMS, Webhook — all from a single gateway process            |\n| **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 |\n| **Scheduled Tasks**          | Built-in cron scheduler with delivery to any platform (daily reports, nightly backups, weekly audits)                                                                            |\n| **Subagent Delegation**      | Spawn isolated subagents for parallel workstreams with restricted toolsets                                                                                                       |\n| **Execute Code**             | Python scripts that call tools via RPC, collapsing multi-step pipelines into zero-context-cost turns                                                                             |\n| **Terminal Backends**        | Local, Docker, SSH, Modal, Daytona, Singularity — run on a $5 VPS or a GPU cluster                                                                                               |\n| **Skills**                   | 70+ bundled skills across 28 categories, Skills Hub for community discovery, agentskills.io compatibility                                                                        |\n| **Plugins**                  | Drop-in Python plugins with lifecycle hooks (pre_llm_call, post_llm_call, on_session_start, on_session_end)                                                                      |\n| **MCP**                      | Client (connect to MCP servers for extended tools) and Server (expose conversations to MCP clients)                                                                              |\n| **IDE Integration**          | VS Code, Zed, JetBrains via ACP server with session management and tool streaming                                                                                                |\n| **API Server**               | OpenAI-compatible `\u002Fv1\u002Fchat\u002Fcompletions` endpoint for headless integrations                                                                                                      |\n| **Profiles**                 | Multi-instance support — each profile gets isolated config, memory, sessions, skills, gateway                                                                                    |\n| **Security**                 | Command approval system, secret redaction, SSRF protection, PII redaction, injection detection, credential directory protection                                                  |\n| **RL Training**              | Atropos environments for batch trajectory generation and agent policy optimization                                                                                               |\n\n---\n\n## 3. Installation & Getting Started\n\n```bash\n# One-line install (Linux, macOS, WSL2)\ncurl -fsSL https:\u002F\u002Fraw.githubusercontent.com\u002FNousResearch\u002Fhermes-agent\u002Fmain\u002Fscripts\u002Finstall.sh | bash\n\n# After install\nsource ~\u002F.bashrc    # or: source ~\u002F.zshrc\nhermes              # start chatting\n\n# Key commands\nhermes model        # Choose LLM provider and model\nhermes tools        # Configure which tools are enabled\nhermes config set   # Set individual config values\nhermes gateway      # Start the messaging gateway\nhermes setup        # Run the full setup wizard\nhermes update       # Update to latest version\nhermes doctor       # Diagnose any issues\n```\n\n**For development:**\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent.git\ncd hermes-agent\ncurl -LsSf https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\nuv venv venv --python 3.11\nsource venv\u002Fbin\u002Factivate\nuv pip install -e \".[all,dev]\"\npython -m pytest tests\u002F -q    # ~3000 tests\n```\n\n---\n\n## 4. Project Structure\n\n```\nhermes-agent\u002F\n├── run_agent.py              # AIAgent class — core conversation loop\n├── model_tools.py            # Tool orchestration, _discover_tools(), handle_function_call()\n├── toolsets.py               # Toolset definitions, _HERMES_CORE_TOOLS list\n├── toolset_distributions.py  # Toolset sampling distributions for RL\n├── cli.py                    # HermesCLI class — interactive CLI orchestrator\n├── hermes_state.py           # SessionDB — SQLite session store (FTS5 search)\n├── hermes_constants.py       # Shared constants, get_hermes_home()\n├── hermes_time.py            # Timezone handling\n├── utils.py                  # Shared utility functions\n├── batch_runner.py           # Parallel batch processing\n├── trajectory_compressor.py  # Trajectory compression for RL training\n├── mcp_serve.py              # MCP server mode entry point\n├── mini_swe_runner.py        # Minimal SWE benchmark runner\n├── rl_cli.py                 # RL CLI commands\n│\n├── agent\u002F                    # Agent internals\n│   ├── prompt_builder.py         # System prompt assembly\n│   ├── context_compressor.py     # Auto context compression\n│   ├── prompt_caching.py         # Anthropic prompt caching\n│   ├── auxiliary_client.py       # Auxiliary LLM client (vision, summarization)\n│   ├── model_metadata.py         # Model context lengths, token estimation\n│   ├── models_dev.py             # models.dev registry integration\n│   ├── display.py                # KawaiiSpinner, tool preview formatting\n│   ├── skill_commands.py         # Skill slash commands (shared CLI\u002Fgateway)\n│   └── trajectory.py             # Trajectory saving helpers\n│\n├── hermes_cli\u002F               # CLI subcommands and setup\n│   ├── main.py               # Entry point — all `hermes` subcommands\n│   ├── config.py             # DEFAULT_CONFIG, OPTIONAL_ENV_VARS, migration\n│   ├── commands.py           # Slash command definitions + SlashCommandCompleter\n│   ├── callbacks.py          # Terminal callbacks (clarify, sudo, approval)\n│   ├── setup.py              # Interactive setup wizard\n│   ├── skin_engine.py        # Skin\u002Ftheme engine\n│   ├── skills_config.py      # `hermes skills` — skill management\n│   ├── tools_config.py       # `hermes tools` — tool management\n│   ├── skills_hub.py         # Skills Hub integration\n│   ├── models.py             # Model catalog, provider model lists\n│   ├── model_switch.py       # Shared \u002Fmodel switch pipeline\n│   └── auth.py               # Provider credential resolution\n│\n├── tools\u002F                    # Tool implementations (one file per tool)\n│   ├── registry.py           # Central tool registry\n│   ├── approval.py           # Dangerous command detection\n│   ├── terminal_tool.py      # Terminal\u002Fshell execution\n│   ├── process_registry.py   # Background process management\n│   ├── file_tools.py         # File read\u002Fwrite\u002Fsearch\u002Fpatch\n│   ├── web_tools.py          # Web search\u002Fextract\n│   ├── browser_tool.py       # Browser automation\n│   ├── code_execution_tool.py # execute_code sandbox\n│   ├── delegate_tool.py      # Subagent delegation\n│   ├── mcp_tool.py           # MCP client integration\n│   ├── skills_tool.py        # Skill management tool\n│   ├── todo_tool.py          # Todo\u002Ftask tracking tool\n│   ├── memory_tool.py        # Memory read\u002Fwrite tool\n│   ├── tts_tool.py           # Text-to-speech\n│   ├── vision_tool.py        # Image analysis\n│   ├── image_gen_tool.py     # Image generation\n│   └── environments\u002F         # Terminal backends\n│       ├── base.py               # BaseEnvironment ABC\n│       ├── local.py              # Local execution\n│       ├── docker.py             # Docker containers\n│       ├── ssh.py                # SSH remote execution\n│       ├── modal.py              # Modal serverless\n│       ├── managed_modal.py      # Nous-hosted Modal\n│       ├── daytona.py            # Daytona serverless\n│       ├── singularity.py        # Singularity HPC containers\n│       └── persistent_shell.py   # Persistent shell mixin\n│\n├── gateway\u002F                  # Messaging platform gateway\n│   ├── run.py                # GatewayRunner — main message loop\n│   ├── session.py            # SessionStore — conversation persistence\n│   ├── status.py             # Gateway status, token locks\n│   └── platforms\u002F            # 16 platform adapters\n│       ├── base.py               # BasePlatformAdapter ABC\n│       ├── telegram.py           # Telegram (polling + webhook)\n│       ├── discord.py            # Discord\n│       ├── slack.py              # Slack\n│       ├── whatsapp.py           # WhatsApp\n│       ├── matrix.py             # Matrix (E2EE)\n│       ├── signal.py             # Signal\n│       ├── email.py              # Email (IMAP\u002FSMTP)\n│       ├── homeassistant.py      # Home Assistant\n│       ├── sms.py                # SMS (Twilio)\n│       ├── mattermost.py         # Mattermost\n│       ├── dingtalk.py           # DingTalk\n│       ├── feishu.py             # Feishu\u002FLark\n│       ├── wecom.py              # WeCom (Enterprise WeChat)\n│       ├── webhook.py            # Generic webhook\n│       └── api_server.py         # OpenAI-compatible API server\n│\n├── acp_adapter\u002F              # ACP server (IDE integration)\n│   ├── server.py             # HermesACPAgent class\n│   ├── session.py            # SessionManager\n│   ├── events.py             # Streaming callbacks\n│   ├── permissions.py        # Approval callbacks\n│   └── entry.py              # Entry point\n│\n├── cron\u002F                     # Scheduler\n│   ├── scheduler.py          # tick() — job execution engine\n│   └── jobs.py               # Job storage and CRUD\n│\n├── plugins\u002F                  # Plugin system\n│   └── memory\u002F               # 8 memory provider plugins\n│       ├── openviking\u002F\n│       ├── mem0\u002F\n│       ├── hindsight\u002F\n│       ├── holographic\u002F\n│       ├── honcho\u002F\n│       ├── retaindb\u002F\n│       └── byterover\u002F\n│\n├── environments\u002F             # RL training environments (Atropos)\n│   ├── hermes_base_env.py    # Abstract base RL environment\n│   ├── agent_loop.py         # HermesAgentLoop — rollout execution\n│   ├── tool_context.py       # ToolContext — sandbox for RL\n│   ├── web_research_env.py   # Web research tasks\n│   └── agentic_opd_env.py    # Observation-Prediction-Demo env\n│\n├── skills\u002F                   # 70+ bundled skills across 28 categories\n├── optional-skills\u002F          # Additional optional skills\n├── tests\u002F                    # ~3000 pytest tests\n├── scripts\u002F                  # Install, update, packaging scripts\n├── docker\u002F                   # Docker build files\n├── docs\u002F                     # Documentation source (Docusaurus)\n├── website\u002F                  # Landing page\n├── desktop\u002F                  # Desktop app (Electron, separate repo)\n├── tinker-atropos\u002F           # RL submodule\n│\n├── pyproject.toml            # Python package config\n├── AGENTS.md                 # Developer guide for AI assistants\n├── RELEASE_v0.2.0.md → v0.7.0.md  # Release notes\n└── cli-config.yaml.example   # Example config\n```\n\n**User config directory:** `~\u002F.hermes\u002F`\n\n```\n~\u002F.hermes\u002F\n├── config.yaml           # User settings\n├── .env                  # API keys and secrets\n├── MEMORY.md             # Persistent agent memory\n├── USER.md               # User profile\n├── SOUL.md               # Agent personality\u002Fidentity\n├── sessions.db           # SQLite session database\n├── skills\u002F               # User-installed skills\n├── skins\u002F                # Custom CLI themes\n├── plugins\u002F              # User plugins\n├── cron\u002F                 # Cron jobs and output\n│   ├── jobs.json\n│   └── output\u002F\n├── cache\u002F                # Image\u002Faudio cache\n├── plans\u002F                # Generated plans\n├── profiles\u002F             # Multi-instance profiles\n└── mcp\u002F                  # MCP server configs\n```\n\n---\n\n## 5. Core Architecture\n\n### 5.1 AIAgent Class (run_agent.py)\n\nThe `AIAgent` class is the heart of the system — the core conversation loop that orchestrates LLM calls, tool execution, context management, and response delivery.\n\n**Constructor (~60 parameters):**\n\n```python\nclass AIAgent:\n    def __init__(self,\n        model: str = \"anthropic\u002Fclaude-opus-4.6\",\n        max_iterations: int = 90,\n        enabled_toolsets: list = None,\n        disabled_toolsets: list = None,\n        quiet_mode: bool = False,\n        save_trajectories: bool = False,\n        platform: str = None,            # \"cli\", \"telegram\", etc.\n        session_id: str = None,\n        session_db: SessionDB = None,\n        skip_context_files: bool = False,\n        skip_memory: bool = False,\n        base_url: str = None,\n        api_key: str = None,\n        provider: str = None,\n        api_mode: str = \"chat_completions\",  # or \"anthropic_messages\" or \"codex_responses\"\n        tool_progress_callback = None,\n        stream_delta_callback = None,\n        thinking_callback = None,\n        status_callback = None,\n        iteration_budget: IterationBudget = None,\n        credential_pool = None,\n        checkpoints_enabled: bool = False,\n        # ... plus provider, routing, callback params\n    )\n```\n\n**Main Methods:**\n\n| Method                                                                          | Returns  | Purpose                                                                            |\n| ------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------- |\n| `chat(message, stream_callback)`                                                | `str`    | Simple interface — returns final response text                                     |\n| `run_conversation(user_message, system_message, conversation_history, task_id)` | `dict`   | Full interface — returns `{final_response, messages, completed, api_calls, error}` |\n| `_interruptible_api_call(api_kwargs)`                                           | Response | Runs API request in background thread with interrupt support                       |\n| `_interruptible_streaming_api_call(api_kwargs, on_first_delta)`                 | Response | Streaming variant with delta callbacks                                             |\n\n**The Core Agent Loop** (inside `run_conversation()`):\n\n```python\nwhile api_call_count \u003C self.max_iterations and self.iteration_budget.remaining > 0:\n    response = client.chat.completions.create(\n        model=model, messages=messages, tools=tool_schemas\n    )\n    if response.tool_calls:\n        for tool_call in response.tool_calls:\n            result = handle_function_call(tool_call.name, tool_call.args, task_id)\n            messages.append(tool_result_message(result))\n        api_call_count += 1\n    else:\n        return response.content  # Final text response\n```\n\n**Key Behaviors:**\n\n- **Three API modes:** `chat_completions` (OpenAI-compatible), `anthropic_messages` (Anthropic SDK), `codex_responses` (OpenAI Codex)\n- **Parallel tool execution:** Independent tool calls run concurrently via ThreadPoolExecutor (unless they share file paths or are in the never-parallel list)\n- **Interrupt support:** Background threads allow interrupt detection without blocking on HTTP\n- **Error recovery:** Automatic fallback chain (primary → fallback model), retry with exponential backoff, context compression on token overflow\n- **Budget pressure:** Warnings at 70% (caution) and 90% (urgent) of iteration budget\n- **Oversized results:** Tool results >100K chars are saved to temp files with a preview\n- **Stale connection detection:** 90s timeout for streaming, 60s read timeout\n\n**IterationBudget** (thread-safe):\n\n```python\nclass IterationBudget:\n    def consume() -> bool    # Check and consume one iteration\n    def refund()             # Give back iteration (for execute_code turns)\n    @property remaining      # Remaining iterations\n```\n\n---\n\n### 5.2 Tool Orchestration (model_tools.py)\n\nBridges the agent and tool registry — handles discovery, schema generation, and dispatch.\n\n**Key Functions:**\n\n| Function                                                                                | Purpose                                                                   |\n| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |\n| `_discover_tools()`                                                                     | Imports all tool modules (each calls `registry.register()` on import)     |\n| `get_tool_definitions(enabled_toolsets, disabled_toolsets, quiet_mode)`                 | Returns OpenAI-format tool schemas filtered by toolset                    |\n| `handle_function_call(function_name, function_args, task_id, user_task, enabled_tools)` | Main dispatcher — routes calls to registry with arg coercion              |\n| `coerce_tool_args(tool_name, args)`                                                     | Type coercion for LLM-generated arguments (string→int, string→bool, etc.) |\n\n**Tool Discovery Order:**\n\n1. Static tools (web_tools, terminal_tool, file_tools, browser_tool, etc.)\n2. Optional tools (fal_client for image gen, honcho, etc.) — graceful fallback if missing\n3. Plugin-registered tools\n4. MCP server tools (dynamic, via tools\u002Flist_changed notifications)\n\n**Special Tool Handling:**\n\n- **Agent-level tools** (todo, memory, session_search, delegate_task): Intercepted by `run_agent.py` before `handle_function_call()`\n- **execute_code**: Passes `enabled_tools` for sandbox tool list\n- **Dynamic schema adjustments**: `browser_navigate` strips web_search reference if tools unavailable\n\n**Async Bridging:**\n\n- Persistent event loops (not `asyncio.run()`) to prevent \"Event loop is closed\" errors\n- Main thread uses shared loop; worker threads get per-thread loops\n- `_run_async()` detects running loop and spins up disposable thread if needed\n\n---\n\n### 5.3 Toolset System (toolsets.py)\n\nProvides flexible tool grouping and composition.\n\n**Core Toolsets:**\n\n| Toolset          | Tools Included                                                                                   |\n| ---------------- | ------------------------------------------------------------------------------------------------ |\n| `web`            | web_search, web_extract, web_crawl                                                               |\n| `terminal`       | terminal                                                                                         |\n| `file`           | read_file, write_file, edit_file, list_files, search_files                                       |\n| `browser`        | browser_navigate, browser_snapshot, browser_click, browser_type, browser_scroll, browser_extract |\n| `vision`         | analyze_image                                                                                    |\n| `image_gen`      | generate_image                                                                                   |\n| `tts`            | text_to_speech                                                                                   |\n| `todo`           | todo_read, todo_write                                                                            |\n| `memory`         | memory_read, memory_write                                                                        |\n| `session_search` | session_search                                                                                   |\n| `delegation`     | delegate_task                                                                                    |\n| `code_execution` | execute_code                                                                                     |\n| `cronjob`        | create_job, list_jobs, delete_job                                                                |\n| `messaging`      | send_message                                                                                     |\n| `homeassistant`  | ha_get_states, ha_call_service, ...                                                              |\n\n**Composite Toolsets:**\n\n- `hermes-cli` — All core tools for CLI platform\n- `hermes-telegram`, `hermes-discord`, etc. — Platform-specific tool sets\n- `hermes-gateway` — Union of all platform tools\n- `debugging` — terminal + file + web\n- `safe` — Everything except terminal\n\n**Resolution:**\n\n```python\nresolve_toolset(name, visited=None) → List[str]\n# Recursively resolves toolset to tool names\n# Handles composition (includes) and cycle detection\n# Special aliases: \"all\" or \"*\" = all tools\n```\n\n---\n\n### 5.4 Tool Registry (tools\u002Fregistry.py)\n\nSingleton managing all tool schemas and handlers. Circular-import safe — has no tool dependencies.\n\n**ToolEntry** (per-tool metadata):\n\n```python\n@dataclass(slots=True)\nclass ToolEntry:\n    name: str\n    toolset: str\n    schema: dict           # OpenAI-format tool definition\n    handler: Callable      # Sync or async handler function\n    check_fn: Callable     # Returns True if tool is available\n    requires_env: list     # Required environment variables\n    is_async: bool\n    description: str\n    emoji: str\n```\n\n**Key Methods:**\n\n```python\nregistry.register(name, toolset, schema, handler, check_fn, requires_env)\nregistry.get_definitions(tool_names, quiet)  # Returns filtered schemas\nregistry.dispatch(name, args, **kwargs)      # Execute with async bridging\nregistry.deregister(name)                    # Remove (for MCP tool refresh)\nregistry.check_tool_availability()           # Returns (available, unavailable)\n```\n\n---\n\n### 5.5 Session Database (hermes_state.py)\n\nSQLite-based persistent session storage with FTS5 full-text search.\n\n**Schema (v6):**\n\n```sql\n-- Sessions table\nsessions (\n    id TEXT PRIMARY KEY,\n    source TEXT, user_id TEXT, model TEXT, model_config TEXT,\n    system_prompt TEXT, parent_session_id TEXT,\n    started_at TEXT, ended_at TEXT, end_reason TEXT,\n    message_count INTEGER, tool_call_count INTEGER,\n    input_tokens INTEGER, output_tokens INTEGER,\n    cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER,\n    estimated_cost_usd REAL, actual_cost_usd REAL,\n    title TEXT  -- UNIQUE INDEX\n)\n\n-- Messages table\nmessages (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    session_id TEXT, role TEXT, content TEXT,\n    tool_call_id TEXT, tool_calls TEXT,  -- JSON\n    tool_name TEXT, timestamp TEXT,\n    token_count INTEGER, finish_reason TEXT,\n    reasoning TEXT, reasoning_details TEXT, codex_reasoning_items TEXT\n)\n\n-- FTS5 virtual table (auto-synced via triggers)\nmessages_fts (content)\n```\n\n**Concurrency Model:**\n\n- WAL (Write-Ahead Logging) for concurrent readers + single writer\n- `BEGIN IMMEDIATE` for write transactions (lock at start, not commit)\n- Jitter retry on lock: 20-150ms random backoff, max 15 retries\n- Periodic WAL checkpoint every 50 writes\n\n**Key Operations:**\n\n- `create_session()`, `end_session()`, `reopen_session()`\n- `add_message()`, `get_messages()`\n- `search_sessions(query)` — FTS5 full-text search\n- `update_token_counts()` — Supports both incremental (CLI) and absolute (gateway) modes\n\n---\n\n### 5.6 Constants & Home Directory (hermes_constants.py)\n\nImport-safe constants module with no circular dependencies.\n\n```python\nget_hermes_home() → Path          # HERMES_HOME env var or ~\u002F.hermes\ndisplay_hermes_home() → str       # User-friendly display: \"~\u002F.hermes\"\nget_optional_skills_dir() → Path  # HERMES_OPTIONAL_SKILLS env var\nparse_reasoning_effort(str) → Dict  # \"high\" → {\"enabled\": True, \"effort\": \"high\"}\n\n# Key constants\nOPENROUTER_BASE_URL = \"https:\u002F\u002Fopenrouter.ai\u002Fapi\u002Fv1\"\nNOUS_API_BASE_URL = \"https:\u002F\u002Finference-api.nousresearch.com\u002Fv1\"\nAI_GATEWAY_BASE_URL = \"https:\u002F\u002Fai-gateway.vercel.sh\u002Fv1\"\nVALID_REASONING_EFFORTS = (\"xhigh\", \"high\", \"medium\", \"low\", \"minimal\")\n```\n\n---\n\n## 6. CLI System\n\n### 6.1 Interactive CLI (cli.py)\n\nThe `HermesCLI` class provides the interactive terminal interface.\n\n**Features:**\n\n- **Rich** for banner\u002Fpanels, **prompt_toolkit** for input with autocomplete\n- **KawaiiSpinner** — animated faces during API calls, `┊` activity feed for tool results\n- Multiline editing with Shift+Enter\n- Slash-command autocomplete\n- Session history with up\u002Fdown arrow navigation\n- Clipboard image paste (Alt+V \u002F Ctrl+V)\n- Status bar showing model, provider, and token counts\n- Inline diff previews for file write\u002Fpatch operations\n\n**Configuration Loading:**\n\n```python\nload_cli_config() → dict\n# Loads from ~\u002F.hermes\u002Fconfig.yaml (or .\u002Fcli-config.yaml fallback)\n# Merges with hardcoded defaults\n# Expands ${ENV_VAR} references\n# Maps terminal config → env vars\n```\n\n---\n\n### 6.2 CLI Entry Point (hermes_cli\u002Fmain.py)\n\nAll `hermes` subcommands are dispatched from here:\n\n```\nhermes                    # Default: interactive chat\nhermes chat               # Explicit interactive mode\nhermes gateway start|stop|status|install|uninstall\nhermes setup              # Setup wizard\nhermes model              # Select model\u002Fprovider\nhermes tools              # Configure tools\nhermes skills             # Manage skills\nhermes config set|get     # Direct config manipulation\nhermes cron list|delete   # Cron job management\nhermes doctor             # Diagnose issues\nhermes sessions browse    # Session picker\nhermes profile create|list|switch|delete|export|import\nhermes mcp serve|add|remove  # MCP management\nhermes acp                # Start ACP server\nhermes update|uninstall|version\n```\n\n**Profile System:**\n\n- `_apply_profile_override()` runs BEFORE any imports to set `HERMES_HOME`\n- Pre-parses `--profile\u002F-p` from argv\n- Allows fully isolated agent instances with separate config, memory, sessions, skills\n\n---\n\n### 6.3 Configuration System (hermes_cli\u002Fconfig.py)\n\n**Key Configuration Sections:**\n\n```yaml\nmodel: \"anthropic\u002Fclaude-opus-4.6\" # or dict with provider\u002Fbase_url\u002Fapi_key\nproviders: {} # Provider-specific configs\nfallback_providers: [] # Ordered failover list\ncredential_pool: {} # Multiple API keys per provider\n\nagent:\n  max_turns: 90\n  gateway_timeout: 1800\n  tool_use_enforcement: \"auto\"\n\nterminal:\n  backend: \"local\" # local|docker|modal|daytona|ssh|singularity\n  timeout: 180\n  persistent_shell: true\n  docker_image: \"nikolaik\u002Fpython-nodejs:...\"\n\ncompression:\n  enabled: true\n  threshold: 0.50 # Compress when 50% of context used\n  target_ratio: 0.20 # Summary = 20% of compressed content\n  protect_last_n: 20\n\nauxiliary:\n  vision: { provider, model }\n  web_extract: { provider, model }\n  compression: { provider, model }\n\nmemory:\n  memory_enabled: true\n  provider: \"\" # \"\" | \"honcho\" | \"mem0\" | etc.\n  memory_char_limit: 2200\n\ndisplay:\n  personality: \"kawaii\"\n  show_reasoning: false\n  inline_diffs: true\n  skin: \"default\"\n  streaming: true\n\ntts:\n  provider: \"edge\" # edge|elevenlabs|openai|neutts\n\nstt:\n  enabled: true\n  provider: \"local\" # local|groq|openai\n\nprivacy:\n  redact_pii: false\n\nmcp_servers: {} # MCP server configurations\n\nskills:\n  external_dirs: [] # Additional skill directories\n\napprovals:\n  mode: \"smart\" # smart|always|off\n```\n\n**Config Files:**\n\n- `~\u002F.hermes\u002Fconfig.yaml` — User settings (authoritative)\n- `~\u002F.hermes\u002F.env` — API keys and secrets\n- Config version migration system (currently v5)\n\n---\n\n### 6.4 Slash Command Registry (hermes_cli\u002Fcommands.py)\n\nAll slash commands defined centrally in `COMMAND_REGISTRY`:\n\n```python\nCommandDef(name, description, category, aliases, args_hint, cli_only, gateway_only)\n```\n\n**Derived automatically by:**\n\n- CLI `process_command()` — dispatch on canonical name\n- Gateway dispatch + help\n- Telegram BotCommand menu\n- Slack `\u002Fhermes` subcommands\n- Autocomplete + help text\n\n**Key Commands:**\n\n| Command        | Aliases    | Description                   |\n| -------------- | ---------- | ----------------------------- |\n| `\u002Fnew`         | `\u002Freset`   | Start fresh conversation      |\n| `\u002Fmodel`       |            | Show\u002Fswitch model             |\n| `\u002Fpersonality` |            | Set agent personality         |\n| `\u002Fretry`       |            | Retry last turn               |\n| `\u002Fundo`        |            | Remove last turn              |\n| `\u002Fcompress`    | `\u002Fcompact` | Compress context              |\n| `\u002Fusage`       | `\u002Fcost`    | Show token usage              |\n| `\u002Finsights`    |            | Usage analytics               |\n| `\u002Fskills`      |            | Browse\u002Finstall skills         |\n| `\u002Fbackground`  | `\u002Fbg`      | Manage background processes   |\n| `\u002Fplan`        |            | Generate implementation plan  |\n| `\u002Frollback`    |            | Restore filesystem checkpoint |\n| `\u002Fverbose`     |            | Toggle debug output           |\n| `\u002Freasoning`   |            | Set reasoning effort          |\n| `\u002Fyolo`        |            | Toggle approval bypass        |\n| `\u002Fbtw`         |            | Ephemeral side question       |\n| `\u002Fstop`        |            | Kill current agent run        |\n| `\u002Fqueue`       |            | Queue next prompt             |\n| `\u002Fbrowser`     |            | Interactive browser session   |\n| `\u002Fhistory`     | `\u002Fresume`  | Session browser               |\n| `\u002Fskin`        |            | Switch CLI theme              |\n\n---\n\n### 6.5 Setup Wizard (hermes_cli\u002Fsetup.py)\n\nModular interactive wizard with independent sections:\n\n1. **Model & Provider** — Select AI provider, enter API keys, choose model\n2. **Terminal Backend** — Choose execution environment\n3. **Agent Settings** — Max iterations, compression, session policies\n4. **Messaging Platforms** — Configure Telegram, Discord, Slack, etc.\n5. **Tools** — TTS, STT, web search, image generation, browser\n\nFeatures:\n\n- Live credential validation\n- Real-time model list fetching from provider APIs\n- Automatic OpenClaw migration detection\n- Atomic config file writes\n\n---\n\n### 6.6 Model Catalog (hermes_cli\u002Fmodels.py)\n\nProvider-specific model lists:\n\n```python\n_PROVIDER_MODELS = {\n    \"nous\": [\"anthropic\u002Fclaude-opus-4.6\", \"anthropic\u002Fclaude-sonnet-4.6\", ...],  # 25+\n    \"openrouter\": [\"anthropic\u002Fclaude-opus-4.6\", \"google\u002Fgemini-3-flash\", ...],  # 30+\n    \"anthropic\": [\"claude-opus-4-6\", \"claude-sonnet-4-6\", ...],\n    \"openai\": [\"gpt-5\", \"gpt-5.4-mini\", \"gpt-4.1\", \"gpt-4o\", ...],\n    \"copilot\": [\"gpt-5.4\", \"gpt-5.4-mini\", \"gpt-5.3-codex\", ...],\n    \"huggingface\": [...],\n    \"minimax\": [...],\n    \"kimi-coding\": [...],\n    \"alibaba\": [...],\n    \"deepseek\": [...],\n    # ... more providers\n}\n```\n\nFeatures:\n\n- Dynamic fetching via provider `\u002Fmodels` endpoints\n- Curated lists used when live probe returns fewer models\n- Fuzzy matching for typo correction\n- Validation against provider catalog\n\n---\n\n### 6.7 Skin\u002FTheme Engine (hermes_cli\u002Fskin_engine.py)\n\nData-driven CLI visual customization — no code changes needed.\n\n**Customizable Elements:**\n\n| Element                          | Key                      | Used By           |\n| -------------------------------- | ------------------------ | ----------------- |\n| Banner border\u002Ftitle\u002Faccent       | `colors.*`               | banner.py         |\n| Response box border              | `colors.response_border` | cli.py            |\n| Spinner faces (waiting\u002Fthinking) | `spinner.*`              | display.py        |\n| Spinner verbs\u002Fwings              | `spinner.*`              | display.py        |\n| Tool output prefix               | `tool_prefix`            | display.py        |\n| Per-tool emojis                  | `tool_emojis`            | display.py        |\n| Agent name\u002Fwelcome\u002Fprompt        | `branding.*`             | banner.py, cli.py |\n\n**Built-in Skins:** default, ares, mono, slate, poseidon, sisyphus, charizard\n\n**User Skins:** Drop `~\u002F.hermes\u002Fskins\u002F\u003Cname>.yaml` and activate with `\u002Fskin \u003Cname>`\n\n---\n\n## 7. Tool System\n\n### 7.1 Terminal Tool (tools\u002Fterminal_tool.py)\n\nShell command execution across multiple backends.\n\n```python\ndef terminal_tool(\n    command: str,\n    background: bool = False,\n    timeout: Optional[int] = None,\n    task_id: Optional[str] = None,\n    force: bool = False,        # Skip approval for dangerous commands\n    workdir: Optional[str] = None,\n    check_interval: Optional[int] = None,  # Background task polling\n    pty: bool = False,\n) -> str  # JSON result\n```\n\n**Features:**\n\n- Multi-backend: Selects based on `TERMINAL_ENV` (local\u002Fdocker\u002Fssh\u002Fmodal\u002Fdaytona\u002Fsingularity)\n- Per-task_id sandboxes with thread-safe creation locks\n- Dangerous command routing through approval system\n- Background task support with file-based IPC\n- Interrupt handling — polls `is_interrupted()` during execution\n- Auto-cleanup daemon thread for idle environments (>300s)\n- Disk usage warnings at configurable threshold\n\n---\n\n### 7.2 File Tools (tools\u002Ffile_tools.py)\n\nSafe file operations with size guards and sensitive path protection.\n\n- `read_file_tool(path, offset, limit)` — Read with pagination (default 100K char limit)\n- `write_file_tool(path, content)` — Write with approval for sensitive paths\n- `edit_file_tool(path, old_text, new_text)` — String replacement editing\n- `list_files_tool(path)` — Directory listing\n- `search_files_tool(pattern, path)` — Glob\u002Fregex file search\n\n**Safety:**\n\n- Device path blocklist (`\u002Fdev\u002Fzero`, `\u002Fdev\u002Fstdin`, etc.)\n- Read dedup tracking — returns stub on re-read if mtime unchanged\n- Sensitive path blocking: `\u002Fetc\u002F`, `\u002Fboot\u002F`, `~\u002F.ssh` without approval\n- Prompt injection protection for known dangerous paths\n\n---\n\n### 7.3 Web Tools (tools\u002Fweb_tools.py)\n\nWeb search and content extraction.\n\n- `web_search_tool(query, limit)` — Search via configurable backend\n- `web_extract_tool(urls, format)` — Extract content from URLs\n- `web_crawl_tool(url, instructions)` — LLM-guided web crawling\n\n**Backends:** Firecrawl, Parallel Web, Tavily, Exa, DuckDuckGo\n\n- Fallback detection by highest-priority available API key\n- LLM processing via auxiliary client (Gemini 3 Flash) for intelligent extraction\n- SSRF protection and URL safety checks\n\n---\n\n### 7.4 Browser Tool (tools\u002Fbrowser_tool.py)\n\nHeadless browser automation with accessibility tree.\n\n```python\nbrowser_navigate(url, task_id) → str\nbrowser_snapshot(task_id, max_chars) → str\nbrowser_click(ref, task_id) → str      # Element refs like @e1, @e2\nbrowser_type(ref, text, task_id) → str\nbrowser_scroll(ref, direction, task_id) → str\nbrowser_extract(task, max_chars, task_id) → str\n```\n\n**Backends:**\n\n- **Local:** Headless Chromium via `agent-browser` CLI\n- **Cloud:** Browserbase (stealth, proxies, CAPTCHA solving)\n- **Camofox:** Anti-detection browser using Camoufox\n\n**Features:**\n\n- Accessibility tree for text-based snapshots (no vision required)\n- Session isolation per task_id with inactivity cleanup\n- API key detection in URLs (prevents exfiltration)\n- SSRF protection for private\u002Finternal addresses\n\n---\n\n### 7.5 Delegate Tool (tools\u002Fdelegate_tool.py)\n\nSpawn isolated subagents for parallel workstreams.\n\n```python\ndef delegate_task(\n    goal: str,\n    context: str = None,\n    toolsets: List[str] = None,       # Default: [\"terminal\", \"file\", \"web\"]\n    tasks: List[Dict] = None,          # Batch mode: up to 3 concurrent\n    max_iterations: int = 50,\n    parent_agent = None,\n) → str\n```\n\n**Isolation:**\n\n- Fresh conversation (no parent history)\n- Own task_id (separate terminal session, file ops)\n- Restricted toolset (configurable, blocked tools always stripped)\n- Focused system prompt from goal + context\n- Parent only sees delegation call and summary result\n\n**Blocked Tools:** delegate_task, clarify, memory, send_message, execute_code (no recursion, no user interaction)\n\n**Constraints:** MAX_DEPTH=2, MAX_CONCURRENT_CHILDREN=3\n\n---\n\n### 7.6 MCP Tool (tools\u002Fmcp_tool.py)\n\nModel Context Protocol client integration.\n\n**Configuration (config.yaml):**\n\n```yaml\nmcp_servers:\n  filesystem:\n    command: \"npx\"\n    args: [\"-y\", \"@modelcontextprotocol\u002Fserver-filesystem\", \"\u002Ftmp\"]\n    timeout: 120\n  remote_api:\n    url: \"https:\u002F\u002Fmy-mcp-server.example.com\u002Fmcp\"\n    headers:\n      Authorization: \"Bearer sk-...\"\n    sampling:\n      enabled: true\n      model: \"gemini-3-flash\"\n```\n\n**Features:**\n\n- **Transports:** Stdio (local processes) and HTTP\u002FStreamableHTTP (remote)\n- **Dynamic tool discovery:** Listens for `tools\u002Flist_changed` notifications\n- **Sampling support:** MCP servers can request LLM completions\n- **Automatic reconnection** with exponential backoff (5 retries)\n- Dedicated background event loop in daemon thread\n- Thread-safe via lock protecting server dict\n\n---\n\n### 7.7 Approval System (tools\u002Fapproval.py)\n\nDangerous command detection and approval flow.\n\n```python\ndetect_dangerous_command(command: str) → (is_dangerous, pattern_key, description)\n```\n\n**106 patterns covering:**\n\n- Destructive operations (`rm -r \u002F`, `mkfs`, `dd if=`)\n- Privilege escalation (`chmod 777`, `chown -R root`)\n- SQL injection (`DROP TABLE`, `DELETE FROM` without WHERE)\n- System targeting (`\u002Fetc\u002F` writes, `systemctl stop`, fork bombs)\n- Shell injection (pipe to sh, wget to sh, process substitution)\n- Network exfiltration (curl with embedded API keys)\n- Secret access (`cat ~\u002F.env`, `cat ~\u002F.netrc`)\n\n**Normalization:** Strips ANSI escapes, null bytes, normalizes Unicode\n\n**Approval Modes:**\n\n- `smart` — Learns which commands are safe based on user decisions\n- `always` — Always ask for dangerous commands\n- `off` — Never ask (or `\u002Fyolo` toggle)\n\n---\n\n### 7.8 Terminal Backends (tools\u002Fenvironments\u002F)\n\n| Backend           | File               | Features                                                                       |\n| ----------------- | ------------------ | ------------------------------------------------------------------------------ |\n| **Local**         | `local.py`         | Direct execution, interrupt support, non-blocking I\u002FO, persistent shell        |\n| **Docker**        | `docker.py`        | Sandboxed containers, cap-drop ALL, no-new-privileges, PID limits, bind mounts |\n| **SSH**           | `ssh.py`           | Remote execution via ControlMaster, persistent shell mixin                     |\n| **Modal**         | `modal.py`         | Native Modal SDK `Sandbox.create()`\u002F`Sandbox.exec()`, persistent snapshots     |\n| **Managed Modal** | `managed_modal.py` | Modal through Nous-hosted gateway                                              |\n| **Daytona**       | `daytona.py`       | Daytona SDK cloud sandboxes, stop\u002Fresume lifecycle                             |\n| **Singularity**   | `singularity.py`   | Singularity containers with scratch dir, SIF cache                             |\n\n**Common Interface (BaseEnvironment ABC):**\n\n```python\nexecute(command, timeout) → {\"output\": str, \"returncode\": int}\ncleanup() → None\n```\n\n---\n\n## 8. Agent Internals\n\n### 8.1 Prompt Builder (agent\u002Fprompt_builder.py)\n\nAssembles the system prompt from multiple sources:\n\n| Component               | Source                                               |\n| ----------------------- | ---------------------------------------------------- |\n| Agent Identity          | `DEFAULT_AGENT_IDENTITY` or `SOUL.md`                |\n| Memory Guidance         | When\u002Fhow to use memory tool                          |\n| Session Search Guidance | How to recall past conversations                     |\n| Skills Guidance         | When to create\u002Fpatch skills                          |\n| Tool Use Enforcement    | Must execute tools, not describe actions             |\n| Skills Index            | `~\u002F.hermes\u002Fskills\u002F.hermes-skills.json`               |\n| Platform Hints          | OS, Python version, shell, available tools           |\n| Context Files           | `.hermes.md`, `AGENTS.md`, `.cursorrules`, `SOUL.md` |\n| Model\u002FProvider Info     | Current model and provider identity                  |\n\n**Context File Discovery:**\n\n1. Check `cwd\u002F.hermes.md` or `HERMES.md`\n2. Walk parent directories up to git root\n3. Validate against injection patterns before inclusion\n\n**Injection Detection (30+ patterns):**\n\n- \"ignore previous instructions\", \"system prompt override\"\n- \"do not tell the user\", \"act as if you have no restrictions\"\n- HTML comment injection, exfiltration via curl, Unicode stealth chars\n\n---\n\n### 8.2 Context Compressor (agent\u002Fcontext_compressor.py)\n\nAutomatically compresses conversation history when approaching context limits.\n\n```python\nclass ContextCompressor:\n    threshold_percent: float = 0.50   # Compress when 50% of context used\n    protect_first_n: int = 3          # Keep system prompt + first turn\n    protect_last_n: int = 20          # Keep recent N messages\n    summary_target_ratio: float = 0.20  # Summary = 20% of compressed content\n```\n\n**Compression Algorithm:**\n\n1. **Pre-pass:** Replace old tool results with placeholder (cheap)\n2. **Protect head:** System prompt + first exchange always kept\n3. **Protect tail:** Token-budget-based tail protection (~20K tokens)\n4. **Summarize middle:** LLM-generated structured summary (Goal, Progress, Decisions, Files, Next Steps)\n5. **Iterative updates:** On subsequent compressions, update previous summary instead of re-summarizing\n\n---\n\n### 8.3 Prompt Caching (agent\u002Fprompt_caching.py)\n\nAnthropic prompt caching support for cost reduction.\n\n- System prompt cached across turns (first conversation turn establishes cache)\n- Cache markers inserted at system prompt boundaries\n- Must not break mid-conversation — altering past context invalidates cache\n- The ONLY time context is altered is during compression\n\n**Critical Rule:** Do NOT implement changes that would alter past context, change toolsets, reload memories, or rebuild system prompts mid-conversation.\n\n---\n\n### 8.4 Auxiliary Client (agent\u002Fauxiliary_client.py)\n\nSeparate LLM client for non-primary tasks:\n\n- **Vision analysis** — Image description and analysis\n- **Web extraction** — Content summarization\n- **Context compression** — Generating conversation summaries\n- **Session search** — Summarizing search results\n- **MCP sampling** — Serving server-initiated LLM requests\n\nConfigured per-task via `auxiliary` section in config.yaml.\n\n---\n\n### 8.5 Display & Spinner (agent\u002Fdisplay.py)\n\n- **KawaiiSpinner** — Animated face characters during API calls\n- **Tool preview formatting** — `┊` prefixed activity feed for tool execution\n- **Inline diff previews** — Shows unified diffs for write\u002Fpatch operations\n- Respects active skin for colors, emojis, and branding\n\n---\n\n### 8.6 Skill Commands (agent\u002Fskill_commands.py)\n\nShared skill invocation for CLI and gateway:\n\n- Skills loaded from `~\u002F.hermes\u002Fskills\u002F` and external directories\n- Injected as **user message** (not system prompt) to preserve prompt caching\n- `\u002Fplan` command generates implementation plans stored in `.hermes\u002Fplans\u002F`\n- Skill content includes setup instructions, tool options, usage examples\n\n---\n\n## 9. Messaging Gateway\n\n### 9.1 GatewayRunner (gateway\u002Frun.py)\n\nMain controller managing all platform adapters and routing messages.\n\n**Key Attributes:**\n\n- `adapters: Dict[Platform, BasePlatformAdapter]` — Active platform instances\n- `session_store: SessionStore` — Conversation persistence\n- `_running_agents: Dict[str, AIAgent]` — Per-session cached agents (preserves prompt caching)\n- `_pending_approvals: Dict[str, Dict]` — Dangerous command approval tracking\n- `pairing_store: PairingStore` — DM code-based user authorization\n\n**Message Flow:**\n\n1. Platform adapter queues `MessageEvent`\n2. GatewayRunner dequeues, calls `_handle_message()`\n3. Slash command? → dispatch to handler\n4. Regular message? → `_handle_message_with_agent()` (async, with per-session locking)\n5. Response delivered back via platform adapter\n\n**Features:**\n\n- Agent caching per session (preserves Anthropic prompt cache across turns)\n- Session reset policies (inactivity timeout, hard reset)\n- Per-session model overrides via `\u002Fmodel`\n- Background memory flush on session expiry\n- Approval routing (`\u002Fapprove`, `\u002Fdeny`) with interactive buttons (Discord)\n- 30+ slash command handlers\n\n---\n\n### 9.2 Session Store (gateway\u002Fsession.py)\n\n**SessionSource** — Where a message originated (platform, chat_id, user info)\n**SessionContext** — Full context for system prompt injection (platforms, home channels, metadata)\n**SessionStore** — Loads\u002Fsaves conversation transcripts as JSON files\n\n```\n~\u002F.hermes\u002Fsessions\u002F{session_key}.json\nFormat: [{role, content, timestamp}, ...]\n```\n\n**Features:**\n\n- Session key computed from platform + chat_id + thread_id (deterministic hash)\n- Inactivity timeout for session resets\n- PII redaction (phone numbers hashed)\n- Survives gateway restarts\n\n---\n\n### 9.3 Platform Adapters (gateway\u002Fplatforms\u002F)\n\n**16 adapters sharing `BasePlatformAdapter` interface:**\n\n| Platform           | Key Features                                                                                             |\n| ------------------ | -------------------------------------------------------------------------------------------------------- |\n| **Telegram**       | Polling + webhook mode, media handling, inline keyboards, forum topic isolation, group mention gating    |\n| **Discord**        | Server channels, threads, reactions (processing\u002Fdone\u002Ferror), button-based approval, @mention requirement |\n| **Slack**          | Multi-workspace OAuth, thread handling, app_mention, `\u002Fhermes` subcommands                               |\n| **WhatsApp**       | Group & DM support, media captions, LID↔phone alias resolution                                           |\n| **Matrix**         | E2EE room encryption, threaded messages, trusted device flow, native voice messages                      |\n| **Signal**         | Encrypted DMs, group membership, SSE keepalive, phone URL encoding                                       |\n| **Email**          | IMAP\u002FSMTP, multi-recipient, skip_attachments option                                                      |\n| **Home Assistant** | REST tools + WebSocket, service discovery, smart home automation                                         |\n| **SMS**            | Twilio integration                                                                                       |\n| **Mattermost**     | Self-hosted Slack alternative, configurable mention behavior                                             |\n| **DingTalk**       | Alibaba enterprise messaging                                                                             |\n| **Feishu\u002FLark**    | Enterprise messaging, message cards, approval workflows                                                  |\n| **WeCom**          | Enterprise WeChat, department management                                                                 |\n| **Webhook**        | Generic HTTP POST for custom integrations                                                                |\n| **API Server**     | OpenAI-compatible `\u002Fv1\u002Fchat\u002Fcompletions` endpoint                                                        |\n\n**Common Features:**\n\n- Image\u002Faudio caching for vision and STT tools\n- Rate limiting with exponential backoff\n- Session routing with authorization rules\n- Cross-platform conversation continuity\n\n---\n\n## 10. Cron Scheduling\n\nBuilt-in job scheduler running in the gateway background thread.\n\n**Schedule Types:**\n\n- `\"once in 5m\"` — One-shot after duration\n- `\"every 30m\"` — Recurring interval\n- `\"0 9 * * *\"` — Standard cron expression\n- `\"2026-04-06T14:00\"` — Absolute datetime\n\n**Job Storage:** `~\u002F.hermes\u002Fcron\u002Fjobs.json`\n\n**Execution Flow:**\n\n1. `tick()` called every 60s from gateway background thread\n2. Fetch due jobs past `next_run_at`\n3. Spawn `hermes` CLI subprocess with job prompt + skills\n4. Capture output → save to `~\u002F.hermes\u002Fcron\u002Foutput\u002F{job_id}\u002F{timestamp}.md`\n5. Deliver to target platform (or stay local)\n\n**Delivery Targets:**\n\n- `\"local\"` — Output saved locally only\n- `\"origin\"` — Send to originating chat\n- `\"telegram:\u003Cchat_id>\"` — Explicit platform\u002Fchat routing\n- `[SILENT]` prefix — Suppress delivery but keep logs\n\n**Grace Windows:** Based on schedule frequency (120s–2hrs) to handle missed jobs\n\n---\n\n## 11. Skills System\n\n**Skills are composable, agent-invokable knowledge units.**\n\n**Structure:**\n\n```\nskills\u002F\n├── creative\u002F              # ASCII art, diagrams, music\n├── software-development\u002F  # Debugging, testing, docs\n├── github\u002F                # Codebase inspection, PR workflow\n├── research\u002F              # Literature, web scraping\n├── productivity\u002F          # Task management\n├── media\u002F                 # Image, video, audio processing\n├── mlops\u002F                 # ML experiment tracking\n├── autonomous-ai-agents\u002F  # Multi-agent orchestration\n└── [20+ more categories]\n```\n\n**Per-Skill Structure:**\n\n```\nskill-name\u002F\n├── SKILL.md     # Metadata (YAML frontmatter) + implementation instructions\n└── [sub-skills]\u002F\n```\n\n**SKILL.md Example:**\n\n```yaml\n---\nname: ascii-art\ndescription: Generate ASCII art using multiple tools\nversion: 4.0.0\ndependencies: []\nmetadata:\n  hermes:\n    tags: [ASCII, Art, Banners, Creative]\n    related_skills: [excalidraw]\n---\n[Implementation instructions, tool options, examples...]\n```\n\n**Discovery:**\n\n- Auto-discovered from `~\u002F.hermes\u002Fskills\u002F` + external dirs\n- Skills index built at startup (`.hermes-skills.json`)\n- Loaded as user messages to preserve prompt caching\n- Per-platform enable\u002Fdisable via `hermes skills`\n- Skills Hub (`agentskills.io`) for community sharing\n\n---\n\n## 12. Plugin System\n\nDrop Python files into `~\u002F.hermes\u002Fplugins\u002F` to extend Hermes.\n\n**Plugin Capabilities:**\n\n- Register custom tools and toolsets\n- Inject messages into conversation\n- Lifecycle hooks: `pre_llm_call`, `post_llm_call`, `on_session_start`, `on_session_end`\n- Enable\u002Fdisable via `hermes plugins enable\u002Fdisable \u003Cname>`\n\n**Memory Provider Plugins (plugins\u002Fmemory\u002F):**\n8 implementations: openviking, mem0, hindsight, holographic, honcho, retaindb, byterover\n\nEach implements:\n\n```python\nclass MemoryProvider:\n    def is_available() → bool\n    def store(key, value)\n    def retrieve(query) → list\n    def clear()\n```\n\n---\n\n## 13. Memory System\n\nHermes has a pluggable memory provider interface:\n\n**Built-in Memory:**\n\n- `MEMORY.md` — Markdown file with persistent facts\n- `USER.md` — User profile information\n- Memory read\u002Fwrite tools called by agent during conversation\n- Periodic nudges prompt agent to save important information\n- FTS5 session search for cross-session recall\n\n**Honcho Integration:**\n\n- AI-native dialectic user modeling\n- Async memory writes\n- Profile-scoped host\u002Fpeer resolution\n- Multi-user isolation in gateway mode\n\n**Configuration:**\n\n```yaml\nmemory:\n  memory_enabled: true\n  provider: \"\" # \"\" for built-in, \"honcho\", \"mem0\", etc.\n  memory_char_limit: 2200\n```\n\n---\n\n## 14. ACP Server (IDE Integration)\n\nAgent Communication Protocol server for VS Code, Zed, JetBrains.\n\n**Entry:** `hermes acp` → `acp_adapter\u002Fserver.py`\n\n**HermesACPAgent Class:**\n\n```python\ninitialize()                    # Handshake with IDE client\nauthenticate(method_id)         # Validate credentials\nnew_session(cwd, mcp_servers)   # Create isolated session\nload_session(session_id)        # Resume session\nfork_session(session_id)        # Branch for parallel work\nlist_sessions()                 # Browse all sessions\ncancel(session_id)              # Interrupt running agent\n```\n\n**Features:**\n\n- Slash command support (`\u002Fmodel`, `\u002Ftools`, `\u002Freset`, `\u002Fcompact`)\n- Client-provided MCP servers (IDE's MCP ecosystem flows into agent)\n- Streaming callbacks for messages, thinking, tool progress\n- Dangerous command approval via IDE UI\n\n---\n\n## 15. API Server\n\nOpenAI-compatible API endpoint for headless integrations (e.g., Open WebUI).\n\n**Endpoint:** `POST \u002Fv1\u002Fchat\u002Fcompletions`\n\n**Features:**\n\n- `X-Hermes-Session-Id` header for persistent sessions\n- Tool progress streaming via SSE events\n- `\u002Fapi\u002Fjobs` REST API for cron management\n- Input limits, field whitelists, SQLite-backed response persistence\n- CORS origin protection\n\n---\n\n## 16. MCP Server Mode\n\nExpose Hermes conversations to MCP-compatible clients.\n\n**Entry:** `hermes mcp serve`\n\n**Features:**\n\n- Browse conversations and sessions\n- Read messages and search across sessions\n- Manage attachments\n- Supports both stdio and Streamable HTTP transports\n- Compatible with Claude Desktop, Cursor, VS Code, etc.\n\n---\n\n## 17. RL Training Environments\n\nAtropos-based RL training framework for agent policy optimization.\n\n**Base Class:** `HermesAgentBaseEnv` (extends `atroposlib.BaseEnv`)\n\n**Configuration:**\n\n```python\nHermesAgentEnvConfig:\n    enabled_toolsets: [\"terminal\", \"file\", \"web\"]\n    max_agent_turns: 30\n    agent_temperature: 1.0\n    terminal_backend: \"local\"  # or docker\u002Fmodal for isolation\n    dataset_name: str\n```\n\n**Subclass Requirements:**\n\n- `setup()` — Load dataset\n- `get_next_item()` — Return next task\n- `format_prompt()` — Convert item → user message\n- `compute_reward()` — Score rollout\n- `evaluate()` — Periodic eval on test set\n\n**Example Environments:**\n\n- `web_research_env.py` — Web research tasks\n- `agentic_opd_env.py` — Observation-Prediction-Demonstration\n- `hermes_swe_env.py` — Software engineering tasks\n\n**Supporting:**\n\n- `HermesAgentLoop` — Orchestrates step-by-step rollouts\n- `ToolContext` — Sandbox for tool execution, records side effects\n- `trajectory_compressor.py` — Compresses trajectories for training data\n\n---\n\n## 18. Profiles (Multi-Instance)\n\nRun multiple fully isolated Hermes instances from the same installation.\n\n**Commands:**\n\n```bash\nhermes profile create \u003Cname>\nhermes profile list\nhermes profile switch \u003Cname>\nhermes profile delete \u003Cname>\nhermes profile export \u003Cname>\nhermes profile import \u003Cfile>\nhermes -p \u003Cname>             # Launch with specific profile\n```\n\n**Each profile gets:**\n\n- Own `HERMES_HOME` directory (`~\u002F.hermes\u002Fprofiles\u002F\u003Cname>\u002F`)\n- Own config.yaml, .env, memory, sessions, skills, gateway service\n- Token-lock isolation (prevents two profiles sharing bot credentials)\n\n**Implementation:**\n\n- `_apply_profile_override()` sets `HERMES_HOME` env var before any imports\n- All 119+ references to `get_hermes_home()` automatically scope to active profile\n- Profile operations are HOME-anchored (`~\u002F.hermes\u002Fprofiles\u002F`) for cross-profile visibility\n\n---\n\n## 19. Security Model\n\n### Command Approval\n\n- 106 dangerous command patterns (destructive, privilege escalation, SQL, exfiltration)\n- Smart approval mode learns from user decisions\n- Session-based approval state (per-session tracking)\n- `--fuck-it-ship-it` flag or `\u002Fyolo` toggle to bypass\n\n### Secret Protection\n\n- Secret redaction in logs and tool output (API keys, tokens)\n- Browser URL scanning for embedded secrets\n- LLM response scanning for exfiltration attempts\n- Credential directory protection (`.docker`, `.azure`, `.config\u002Fgh`, `.ssh`)\n- `execute_code` sandbox output redaction\n\n### Input Safety\n\n- Prompt injection detection in context files (30+ patterns)\n- Unicode stealth character detection\n- ANSI escape sequence normalization\n- Device path blocklist for file reads\n- SSRF protection in web\u002Fbrowser tools\n\n### PII Handling\n\n- Optional `privacy.redact_pii` mode\n- Phone number hashing in session metadata\n- Sender ID anonymization in gateway logs\n\n### Supply Chain\n\n- All dependency version ranges pinned\n- `uv.lock` with hashes for reproducible builds\n- CI workflow scanning PRs for supply chain attack patterns\n- Compromised `litellm` dependency removed\n\n---\n\n## 20. Provider & Model System\n\n### Supported Providers\n\n| Provider              | API Mode           | Key Features                              |\n| --------------------- | ------------------ | ----------------------------------------- |\n| **Nous Portal**       | chat_completions   | 400+ models, first-class setup            |\n| **OpenRouter**        | chat_completions   | 200+ models, provider routing preferences |\n| **Anthropic**         | anthropic_messages | Native prompt caching, OAuth PKCE         |\n| **OpenAI**            | chat_completions   | GPT-5, Codex                              |\n| **GitHub Copilot**    | chat_completions   | OAuth, 400k context                       |\n| **Hugging Face**      | chat_completions   | Curated agentic model picker              |\n| **Google (Direct)**   | chat_completions   | Full Gemini context lengths               |\n| **z.ai\u002FGLM**          | chat_completions   | Chinese LLM models                        |\n| **Kimi\u002FMoonshot**     | chat_completions   | Kimi Code API                             |\n| **MiniMax**           | anthropic_messages | M2.7 models                               |\n| **Alibaba\u002FDashScope** | chat_completions   | Qwen models                               |\n| **DeepSeek**          | chat_completions   | V3 models                                 |\n| **Vercel AI Gateway** | chat_completions   | Routing through Vercel                    |\n| **Kilo Code**         | chat_completions   | Custom provider                           |\n| **OpenCode Zen\u002FGo**   | chat_completions   | Custom provider                           |\n| **Custom Endpoint**   | configurable       | Any OpenAI-compatible API                 |\n\n### Provider Features\n\n- **Ordered fallback chain:** Auto-failover across configured providers on errors\n- **Credential pools:** Multiple API keys per provider with `least_used` rotation\n- **Per-turn primary restoration:** After fallback use, restore primary on next turn\n- **Context length detection:** models.dev integration, provider-aware resolution, `\u002Fv1\u002Fprops` for llama.cpp\n- **Rate limit handling:** User-friendly 429 messages with Retry-After countdown\n- **Anthropic long-context tier:** Auto-reduces to 200k on tier limit 429\n\n---\n\n## 21. Streaming & Reasoning\n\n### Streaming\n\n- Enabled by default in CLI and gateway\n- Token-by-token delivery via `stream_delta_callback`\n- Proper spinner\u002Ftool progress display during streaming\n- Stale connection detection (90s timeout)\n- Fallback to non-streaming if provider doesn't support it\n\n### Reasoning\u002FThinking\n\n- Configurable effort: xhigh, high, medium, low, minimal, none\n- `\u002Freasoning` command to toggle display and effort level\n- Anthropic thinking blocks preserved across multi-turn conversations\n- `\u003Cthink>` tag extraction for compatible models\n- Reasoning persisted to SessionDB (v6 schema) for cross-session continuity\n- Thinking-budget exhaustion detection to skip useless continuation retries\n\n---\n\n## 22. Release History\n\n### v0.2.0 (March 12, 2026) — The Foundation Release\n\n> 216 merged PRs from 63 contributors, resolving 119 issues\n\n- Multi-platform messaging gateway (Telegram, Discord, Slack, WhatsApp, Signal, Email, Home Assistant)\n- MCP client support (stdio + HTTP)\n- 70+ skills across 15+ categories\n- Centralized provider router (`call_llm()` API)\n- ACP server for IDE integration\n- CLI skin\u002Ftheme engine\n- Git worktree isolation (`hermes -w`)\n- Filesystem checkpoints and `\u002Frollback`\n- 3,289 tests\n\n### v0.3.0 (March 17, 2026) — Streaming, Plugins, Providers\n\n- Unified streaming infrastructure (token-by-token delivery)\n- First-class plugin architecture (`~\u002F.hermes\u002Fplugins\u002F`)\n- Native Anthropic provider with prompt caching\n- Smart approvals + `\u002Fstop` command\n- Honcho memory integration\n- Voice mode (CLI push-to-talk, Telegram\u002FDiscord voice)\n- Concurrent tool execution (ThreadPoolExecutor)\n- PII redaction\n- `\u002Fbrowser connect` via Chrome DevTools Protocol\n- Vercel AI Gateway provider\n- Persistent shell mode for local\u002FSSH backends\n- Agentic On-Policy Distillation RL environment\n\n### v0.4.0 (March 23, 2026) — Platform Expansion\n\n- OpenAI-compatible API server (`\u002Fv1\u002Fchat\u002Fcompletions`)\n- 6 new messaging adapters (Signal rewrite, DingTalk, SMS, Mattermost, Matrix, Webhook)\n- `@file` and `@url` context references with tab completion\n- 4 new providers (GitHub Copilot, Alibaba, Kilo Code, OpenCode)\n- MCP server management CLI with OAuth 2.1 PKCE\n- Gateway prompt caching (dramatic cost reduction)\n- Context compression overhaul (structured summaries, iterative updates)\n- Streaming enabled by default\n- 200+ bug fixes\n\n### v0.5.0 (March 28, 2026) — Hardening\n\n- Nous Portal expanded to 400+ models\n- Hugging Face as first-class provider\n- Telegram Private Chat Topics\n- Native Modal SDK backend (replaced swe-rex)\n- Plugin lifecycle hooks activated\n- GPT model tool-use enforcement\n- Nix flake with NixOS module\n- Supply chain hardening (removed litellm, pinned deps, CI scanning)\n- Anthropic per-model output limits (128K for Opus 4.6)\n\n### v0.6.0 (March 30, 2026) — Multi-Instance\n\n> 95 PRs and 16 resolved issues in 2 days\n\n- Profiles for multiple isolated agent instances\n- MCP Server Mode (`hermes mcp serve`)\n- Official Docker container\n- Ordered fallback provider chain\n- Feishu\u002FLark platform adapter\n- WeCom (Enterprise WeChat) adapter\n- Slack multi-workspace OAuth\n- Telegram webhook mode + group controls\n- Exa search backend\n- Skills & credentials on remote backends\n\n### v0.7.0 (April 3, 2026) — Resilience\n\n> 168 PRs and 46 resolved issues\n\n- Pluggable memory provider interface (ABC-based plugin system)\n- Same-provider credential pools with automatic rotation\n- Camofox anti-detection browser backend\n- Inline diff previews in tool activity feed\n- API server session continuity + tool streaming\n- ACP client-provided MCP servers\n- Gateway hardening (race conditions, approval routing, compression death spirals)\n- Secret exfiltration blocking (URL scanning, base64 detection)\n\n---\n\n## 23. File Dependency Chain\n\n```\nhermes_constants.py  (no deps — imported by everything)\n       ↑\ntools\u002Fregistry.py  (no tool deps — imported by all tool files)\n       ↑\ntools\u002F*.py  (each calls registry.register() at import time)\n       ↑\nmodel_tools.py  (imports tools\u002Fregistry + triggers tool discovery)\n       ↑\nrun_agent.py (AIAgent), cli.py (HermesCLI), gateway\u002Frun.py (GatewayRunner)\n       ↑\nhermes_cli\u002Fmain.py  (entry point — dispatches to all subsystems)\n```\n\n**Key Principle:** `tools\u002Fregistry.py` is circular-import safe. It has no tool dependencies. Tool files import the registry; `model_tools.py` imports both.\n\n---\n\n## 24. Key Design Patterns\n\n| Pattern                        | Description                                                                                        |\n| ------------------------------ | -------------------------------------------------------------------------------------------------- |\n| **Registry-based Tool System** | Single source of truth; plugins register at import time; dynamic (MCP) and static tools coexist    |\n| **Toolset Composition**        | Recursive resolution with cycle detection; platform-specific composites                            |\n| **Iteration Budget**           | Thread-safe shared budget across parent + subagents                                                |\n| **Streaming First**            | Preferred over non-streaming for health checking (stale connection detection)                      |\n| **Prefix Caching**             | System prompt cached across turns (Anthropic optimization); context never altered mid-conversation |\n| **Proactive Compression**      | Triggered at 50% context usage; structured summaries with iterative updates                        |\n| **Async Bridging**             | Persistent event loops prevent \"Event loop is closed\"; per-thread loops for workers                |\n| **Profile Isolation**          | HERMES_HOME env var set before imports; all state functions route through `get_hermes_home()`      |\n| **Agent Caching**              | Gateway caches AIAgent per session to preserve prompt cache across turns                           |\n| **WAL Concurrency**            | SQLite WAL mode + jitter retry for concurrent readers + single writer                              |\n| **Plugin Architecture**        | Tools, toolsets, hooks, memory providers extensible via plugins                                    |\n| **Multi-Backend Execution**    | Pluggable terminal backends with unified BaseEnvironment interface                                 |\n| **Safety Layers**              | Approval system → sensitive path guards → injection detection → capability filtering               |\n\n---\n\n## 25. Configuration Reference\n\n### Environment Variables (key ones)\n\n| Variable              | Purpose                                                   |\n| --------------------- | --------------------------------------------------------- |\n| `HERMES_HOME`         | Override home directory (profiles set this automatically) |\n| `OPENROUTER_API_KEY`  | OpenRouter provider key                                   |\n| `ANTHROPIC_API_KEY`   | Anthropic provider key                                    |\n| `OPENAI_API_KEY`      | OpenAI provider key                                       |\n| `NOUS_API_KEY`        | Nous Portal key                                           |\n| `FIRECRAWL_API_KEY`   | Web search\u002Fextraction                                     |\n| `EXA_API_KEY`         | Exa search backend                                        |\n| `BROWSERBASE_API_KEY` | Cloud browser                                             |\n| `FAL_KEY`             | Image generation                                          |\n| `ELEVENLABS_API_KEY`  | Premium TTS                                               |\n| `HONCHO_API_KEY`      | Honcho memory                                             |\n| `TERMINAL_ENV`        | Terminal backend override                                 |\n| `TERMINAL_CWD`        | Terminal working directory                                |\n| `MESSAGING_CWD`       | Gateway working directory                                 |\n\n### Config File Locations\n\n| File                          | Purpose                          |\n| ----------------------------- | -------------------------------- |\n| `~\u002F.hermes\u002Fconfig.yaml`       | Main configuration (YAML)        |\n| `~\u002F.hermes\u002F.env`              | API keys and secrets             |\n| `~\u002F.hermes\u002FMEMORY.md`         | Persistent agent memory          |\n| `~\u002F.hermes\u002FUSER.md`           | User profile                     |\n| `~\u002F.hermes\u002FSOUL.md`           | Agent persona\u002Fidentity           |\n| `~\u002F.hermes\u002Fsessions.db`       | SQLite session database          |\n| `~\u002F.hermes\u002Fcron\u002Fjobs.json`    | Cron job definitions             |\n| `.hermes.md` (in project dir) | Per-project context file         |\n| `AGENTS.md` (in project dir)  | Developer instructions for agent |\n\n---\n\n## 26. Known Pitfalls\n\n1. **DO NOT hardcode `~\u002F.hermes` paths** — Use `get_hermes_home()` from `hermes_constants`. Hardcoding breaks profiles.\n\n2. **DO NOT use `simple_term_menu`** — Rendering bugs in tmux\u002FiTerm2 (ghosting). Use `curses` instead.\n\n3. **DO NOT use `\\033[K`** (ANSI erase-to-EOL) — Leaks as literal text under prompt_toolkit's `patch_stdout`. Use space-padding.\n\n4. **`_last_resolved_tool_names` is process-global** — Saved\u002Frestored around subagent execution in `delegate_tool.py`.\n\n5. **DO NOT hardcode cross-tool references in schemas** — Tool may be unavailable. Add dynamic references in `get_tool_definitions()`.\n\n6. **Tests must not write to `~\u002F.hermes\u002F`** — `_isolate_hermes_home` autouse fixture redirects to temp dir.\n\n7. **Prompt caching must not break** — Do NOT alter past context, change toolsets, reload memories, or rebuild system prompts mid-conversation.\n\n8. **Working directory behavior differs:** CLI uses `os.getcwd()`, gateway uses `MESSAGING_CWD` env var.\n\n9. **Config has three loaders:** `load_cli_config()` (CLI), `load_config()` (hermes tools\u002Fsetup), direct YAML (gateway). They have different merge behaviors.\n\n10. **Profile operations are HOME-anchored** — `_get_profiles_root()` returns `Path.home() \u002F \".hermes\" \u002F \"profiles\"`, NOT `get_hermes_home() \u002F \"profiles\"`. This is intentional for cross-profile visibility.\n\n---\n\n_This document covers Hermes Agent v0.7.0 as of April 2026. For the latest information, refer to the [official documentation](https:\u002F\u002Fhermes-agent.nousresearch.com\u002Fdocs\u002F) and the [GitHub repository](https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent)._\n",{"name":5,"description":7},"main","93a5ec510a24f6470ff853b4268234a6dcec5e50",".agents\u002Fskills\u002Fhermes-agent","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera","https:\u002F\u002Fgithub.com\u002FAblankpaper","2026-09-01 01:53:48",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add Ablankpaper\u002Faera --skill hermes-agent",{"tool":36,"command":37},"bunx","bunx skills add Ablankpaper\u002Faera --skill hermes-agent",{"tool":39,"command":40},"pnpm","pnpm dlx skills add Ablankpaper\u002Faera --skill hermes-agent","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fhermes-agent\u002FSKILL.md",true,[],[45,52,59,64,71,76],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M7AGVH6Q3RWZM4XWJ272QG17","learned-fixture","Synthetic learned skill used by the immutable boundary test.","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fhermes-profile-boundary\u002Fskills\u002Flearned\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7AGVDYJGX2Q2N9ANRS478GW","lat-md","Writing and maintaining lat.md documentation files — structured markdown that describes a project's architecture, design decisions, and test specs. Use when creating, editing, or reviewing files in the lat.md\u002F directory.","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Flat-md\u002FSKILL.md",[],[],{"skillNo":60,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M7AGV5SEMY9ETC4Q09BB9ED0","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fhermes-agent\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7AGV1D328WQ8C3D2JWE0VX9","typescript-expert","TypeScript and JavaScript expert with deep knowledge of type-level programming, performance optimization, monorepo management, migration strategies, and modern tooling.","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftypescript-expert\u002FSKILL.md",[],[],{"skillNo":72,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7AGTXWC0TRNTA6S73YDTEVK","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Flat-md\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7AGTH69X631RT2S0EEFJPB2","electron-pro","Expert in building cross-platform desktop applications using web technologies (HTML\u002FCSS\u002FJS) with the Electron framework.","https:\u002F\u002Fgithub.com\u002FAblankpaper\u002Faera\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Felectron-pro\u002FSKILL.md",[],[]]