本页面是 Hermes Agent 内部结构的顶层地图. 使用它来了解代码库的整体结构,然后深入子系统文档获取实现细节。 如果你是首次接触此代码库: 1. 本页面 — 了解整体结构 2. Agent 循环内部机制 — AIAgent 如何工作 3. 提示词组装 — 系统提示词构建

架构

> 📖 本文档翻译自 Hermes Agent 官方文档 > 最后更新:2026-04-16


架构

本页面是 Hermes Agent 内部结构的顶层地图. 使用它来了解代码库的整体结构,然后深入子系统文档获取实现细节。

系统概述

┌─────────────────────────────────────────────────────────────────────┐
│                        Entry Points                                  │
│                                                                      │
│  CLI (cli.py)    Gateway (gateway/run.py)    ACP (acp_adapter/)     │
│  Batch Runner    API Server                  Python Library          │
└──────────┬──────────────┬───────────────────────┬───────────────────┘
           │              │                       │
           ▼              ▼                       ▼
┌─────────────────────────────────────────────────────────────────────┐
│                     AIAgent (run_agent.py)                           │
│                                                                      │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐                │
│  │ Prompt        │ │ Provider     │ │ Tool         │                │
│  │ Builder       │ │ Resolution   │ │ Dispatch     │                │
│  │ (prompt_      │ │ (runtime_    │ │ (model_      │                │
│  │  builder.py)  │ │  provider.py)│ │  tools.py)   │                │
│  └──────┬───────┘ └──────┬───────┘ └──────┬───────┘                │
│         │                │                │                          │
│  ┌──────┴───────┐ ┌──────┴───────┐ ┌──────┴───────┐                │
│  │ Compression  │ │ 3 API Modes  │ │ Tool Registry│                │
│  │ & Caching    │ │ chat_compl.  │ │ (registry.py)│                │
│  │              │ │ codex_resp.  │ │ 47 tools     │                │
│  │              │ │ anthropic    │ │ 19 toolsets  │                │
│  └──────────────┘ └──────────────┘ └──────────────┘                │
└─────────────────────────────────────────────────────────────────────┘
           │                                    │
           ▼                                    ▼
┌───────────────────┐              ┌──────────────────────┐
│ Session Storage   │              │ Tool Backends         │
│ (SQLite + FTS5)   │              │ Terminal (6 backends) │
│ hermes_state.py   │              │ Browser (5 backends)  │
│ gateway/session.py│              │ Web (4 backends)      │
└───────────────────┘              │ MCP (dynamic)         │
                                   │ File, Vision, etc.    │
                                   └──────────────────────┘

目录结构

hermes-agent/
├── run_agent.py              # AIAgent — core conversation loop (~10,700 lines)
├── cli.py                    # HermesCLI — interactive terminal UI (~10,000 lines)
├── model_tools.py            # Tool discovery, schema collection, dispatch
├── toolsets.py               # Tool groupings and platform presets
├── hermes_state.py           # SQLite session/state database with FTS5
├── hermes_constants.py       # HERMES_HOME, profile-aware paths
├── batch_runner.py           # Batch trajectory generation
│
├── agent/                    # Agent internals
│   ├── prompt_builder.py     # System prompt assembly
│   ├── context_engine.py     # ContextEngine ABC (pluggable)
│   ├── context_compressor.py # Default engine — lossy summarization
│   ├── prompt_caching.py     # Anthropic prompt caching
│   ├── auxiliary_client.py   # Auxiliary LLM for side tasks (vision, summarization)
│   ├── model_metadata.py     # Model context lengths, token estimation
│   ├── models_dev.py         # models.dev registry integration
│   ├── anthropic_adapter.py  # Anthropic Messages API format conversion
│   ├── display.py            # KawaiiSpinner, tool preview formatting
│   ├── skill_commands.py     # Skill slash commands
│   ├── memory_manager.py    # Memory manager orchestration
│   ├── memory_provider.py   # Memory provider ABC
│   └── trajectory.py         # Trajectory saving helpers
│
├── hermes_cli/               # CLI subcommands and setup
│   ├── main.py               # Entry point — all `hermes` subcommands (~6,000 lines)
│   ├── config.py             # DEFAULT_CONFIG, OPTIONAL_ENV_VARS, migration
│   ├── commands.py           # COMMAND_REGISTRY — central slash command definitions
│   ├── auth.py               # PROVIDER_REGISTRY, credential resolution
│   ├── runtime_provider.py   # Provider → api_mode + credentials
│   ├── models.py             # Model catalog, provider model lists
│   ├── model_switch.py       # /model command logic (CLI + gateway shared)
│   ├── setup.py              # Interactive setup wizard (~3,100 lines)
│   ├── skin_engine.py        # CLI theming engine
│   ├── skills_config.py      # hermes skills — enable/disable per platform
│   ├── skills_hub.py         # /skills slash command
│   ├── tools_config.py       # hermes tools — enable/disable per platform
│   ├── plugins.py            # PluginManager — discovery, loading, hooks
│   ├── callbacks.py          # Terminal callbacks (clarify, sudo, approval)
│   └── gateway.py            # hermes gateway start/stop
│
├── tools/                    # Tool implementations (one file per tool)
│   ├── registry.py           # Central tool registry
│   ├── approval.py           # Dangerous command detection
│   ├── terminal_tool.py      # Terminal orchestration
│   ├── process_registry.py   # Background process management
│   ├── file_tools.py         # read_file, write_file, patch, search_files
│   ├── web_tools.py          # web_search, web_extract
│   ├── browser_tool.py       # 10 browser automation tools
│   ├── code_execution_tool.py # execute_code sandbox
│   ├── delegate_tool.py      # Subagent delegation
│   ├── mcp_tool.py           # MCP client (~2,200 lines)
│   ├── credential_files.py   # File-based credential passthrough
│   ├── env_passthrough.py    # Env var passthrough for sandboxes
│   ├── ansi_strip.py         # ANSI escape stripping
│   └── environments/         # Terminal backends (local, docker, ssh, modal, daytona, singularity)
│
├── gateway/                  # Messaging platform gateway
│   ├── run.py                # GatewayRunner — message dispatch (~9,000 lines)
│   ├── session.py            # SessionStore — conversation persistence
│   ├── delivery.py           # Outbound message delivery
│   ├── pairing.py            # DM pairing authorization
│   ├── hooks.py              # Hook discovery and lifecycle events
│   ├── mirror.py             # Cross-session message mirroring
│   ├── status.py             # Token locks, profile-scoped process tracking
│   ├── builtin_hooks/        # Always-registered hooks
│   └── platforms/            # 18 adapters: telegram, discord, slack, whatsapp,
│                             #   signal, matrix, mattermost, email, sms,
│                             #   dingtalk, feishu, wecom, wecom_callback, weixin,
│                             #   bluebubbles, qqbot, homeassistant, webhook, api_server
│
├── acp_adapter/              # ACP server (VS Code / Zed / JetBrains)
├── cron/                     # Scheduler (jobs.py, scheduler.py)
├── plugins/memory/           # Memory provider plugins
├── plugins/context_engine/   # Context engine plugins
├── environments/             # RL training environments (Atropos)
├── skills/                   # Bundled skills (always available)
├── optional-skills/          # Official optional skills (install explicitly)
├── website/                  # Docusaurus documentation site
└── tests/                    # Pytest suite (~3,000+ tests)

数据流

CLI Session

User input → HermesCLI.process_input()
  → AIAgent.run_conversation()
    → prompt_builder.build_system_prompt()
    → runtime_provider.resolve_runtime_provider()
    → API call (chat_completions / codex_responses / anthropic_messages)
    → tool_calls? → model_tools.handle_function_call() → loop
    → final response → display → save to SessionDB

Gateway Message

Platform event → Adapter.on_message() → MessageEvent
  → GatewayRunner._handle_message()
    → authorize user
    → resolve session key
    → create AIAgent with session history
    → AIAgent.run_conversation()
    → deliver response back through adapter

Cron Job

Scheduler tick → load due jobs from jobs.json
  → create fresh AIAgent (no history)
  → inject attached skills as context
  → run job prompt
  → deliver response to target platform
  → update job state and next_run

推荐阅读顺序

如果你是首次接触此代码库:

  1. 本页面 — 了解整体结构
  2. Agent 循环内部机制 — AIAgent 如何工作
  3. 提示词组装 — 系统提示词构建
  4. Provider 运行时解析 — 如何选择 Provider
  5. 添加 Provider — 添加新 Provider 的实用指南
  6. 工具运行时 — 工具注册表、分发、环境
  7. 会话存储 — SQLite 模式、FTS5、会话世系
  8. 网关内部机制 — 消息平台网关
  9. 上下文压缩与提示词缓存 — 压缩和缓存
  10. ACP 内部机制 — IDE 集成
  11. 环境、基准测试与数据生成 — RL 训练

主要子系统

Agent 循环

同步编排引擎(run_agent.py 中的 AIAgent)。处理 Provider 选择、提示词构建、工具执行、重试、回退、回调、压缩和持久化。支持三种 API 模式以适配不同的 Provider 后端。

Agent 循环内部机制

提示词系统

对话生命周期中的提示词构建和维护:

  • prompt_builder.py — 从以下内容组装系统提示词:个性(SOUL.md)、记忆(MEMORY.md、USER.md)、技能、上下文文件(AGENTS.md、.hermes.md)、工具使用指导、模型特定指令
  • prompt_caching.py — 为前缀缓存应用 Anthropic 缓存断点
  • context_compressor.py — 当上下文超过阈值时摘要中间对话轮次

提示词组装上下文压缩与提示词缓存

Provider 解析

CLI、网关、定时任务、ACP 和辅助调用使用的共享运行时解析器。将 (provider, model) 元组映射为 (api_mode, api_key, base_url)。处理 18+ 个 Provider、OAuth 流程、凭据池和别名解析。

Provider 运行时解析

工具系统

中央工具注册表(tools/registry.py)包含 47 个已注册工具,分布在 19 个工具集中。每个工具文件在导入时自注册。注册表处理 Schema 收集、分发、可用性检查和错误包装。终端工具支持 6 个后端(本地、Docker、SSH、Daytona、Modal、Singularity)。

工具运行时

会话持久化

基于 SQLite 的会话存储,支持 FTS5 全文搜索。会话具有世系跟踪(跨压缩的父/子关系)、按平台隔离、带争用处理的原子写入。

会话存储

消息网关

长运行进程,包含 18 个平台适配器、统一会话路由、用户授权(白名单 + DM 配对)、斜杠命令分发、钩子系统、定时任务驱动和后台维护。

网关内部机制

插件系统

三个发现来源:~/.hermes/plugins/(用户)、.hermes/plugins/(项目)和 pip 入口点。插件通过上下文 API 注册工具、钩子和 CLI 命令。两种专门的插件类型:内存 Provider(plugins/memory/)和上下文引擎(plugins/context_engine/)。两者都是单选——同时只能各激活一个,通过 hermes pluginsconfig.yaml 配置。

插件指南内存 Provider 插件

定时任务

一等公民 Agent 任务(非 Shell 任务)。作业存储在 JSON 中,支持多种调度格式,可以附加技能和脚本,并投递到任何平台。

定时任务内部机制

ACP 集成

通过 stdio/JSON-RPC 将 Hermes 作为编辑器原生 Agent 暴露给 VS Code、Zed 和 JetBrains。

ACP 内部机制

RL / 环境 / 轨迹

完整的评估和 RL 训练环境框架。与 Atropos 集成,支持多种工具调用解析器,并生成 ShareGPT 格式的轨迹。

环境、基准测试与数据生成轨迹与训练格式

设计原则

原则实际含义
提示词稳定性系统提示词在对话中途不会改变。除明确的用户操作(/model)外,没有破坏缓存的变更。
可观察执行每次工具调用通过回调对用户可见。CLI 中的进度更新(旋转器)和网关中的聊天消息。
可中断API 调用和工具执行可以在进行中被用户输入或信号取消。
平台无关核心一个 AIAgent 类服务 CLI、网关、ACP、批处理和 API 服务器。平台差异在入口点而非 Agent 中处理。
松耦合可选子系统(MCP、插件、内存 Provider、RL 环境)使用注册表模式和 check_fn 门控,而非硬依赖。
配置文件隔离每个配置文件(hermes -p <name>)拥有独立的 HERMES_HOME、配置、内存、会话和网关 PID。多个配置文件可同时运行。

文件依赖链

tools/registry.py  (无依赖 — 被所有工具文件导入)
       ↑
tools/*.py  (每个在导入时调用 registry.register())
       ↑
model_tools.py  (导入 tools/registry + 触发工具发现)
       ↑
run_agent.py, cli.py, batch_runner.py, environments/

这条链意味着工具注册在导入时、任何 Agent 实例创建之前完成。任何带有顶层 registry.register() 调用的 tools/*.py 文件都会被自动发现——不需要手动导入列表。

Continue Exploring

继续探索

这不是课程式的上一篇下一篇,而是从当前节点向外继续漫游。

开发者指南

Agent 循环内部机制

sidebar position: 3 title: "Agent 循环内部机制" description: "AIAgent 执行、API 模式、工具、回调和回退行为的详细解析" 核心编排引擎是 run agent.py 中的 AIAgent 类——大约 10,700 行代码,负责从 Prompt(提示词)组装到工具

开发者指南

提示词组装

sidebar position: 5 title: "提示词组装" description: "Hermes 如何构建系统提示词、保持缓存稳定性和注入临时层" Hermes 刻意将以下两者分离: - 缓存的系统提示词状态 - 临时的 API 调用时添加内容 这是项目中最关键的设计决策之一,因为它影响:

开发者指南

Provider 运行时解析

sidebar position: 4 title: "Provider 运行时解析" description: "Hermes 如何在运行时解析 Provider、凭据、API 模式和辅助模型" Hermes 有一个共享的 Provider 运行时解析器,在以下场景中使用: - CLI

开发者指南

添加 Provider

sidebar position: 5 title: "添加 Provider" description: "如何向 Hermes Agent 添加新的推理 Provider——认证、运行时解析、CLI 流程、适配器、测试和文档" Hermes 已经可以通过自定义 Provider 路径与任何 OpenAI 兼容端点通

开发者指南

工具运行时(Tools Runtime)

原文链接:Tools Runtime sidebar position: 9 title: "Tools Runtime" description: "Runtime behavior of the tool registry, toolsets, dispatch, and terminal environments

开发者指南

会话存储

Hermes Agent 使用 SQLite 数据库( /.hermes/state.db)来持久化会话元数据、完整消息历史和模型配置,覆盖 CLI 和网关会话。这取代了早期基于每个会话 JSONL 文件的方式。 源文件:hermes state.py 关键设计决策: - WAL 模式 用于并发读取 + 单个写入器(网

Developer Guide

开发者指南

面向二次开发者,解释架构、运行时、上下文引擎、插件、工具与扩展机制。

20 篇文档20 个节点

当前节点

架构

同主题继续探索

贡献指南

感谢你对 Hermes Agent 的贡献!本指南涵盖开发环境设置、理解代码库以及如何让你的 PR 被合并。 我们按以下顺序重视贡献: 1. Bug 修复 — 崩溃、不正确行为、数据丢失 2. 跨平台兼容性 — macOS、不同 Linux 发行版、WSL2 3. 安全加固 — Shell 注入、Prompt 注入、路

Agent 循环内部机制

sidebar position: 3 title: "Agent 循环内部机制" description: "AIAgent 执行、API 模式、工具、回调和回退行为的详细解析" 核心编排引擎是 run agent.py 中的 AIAgent 类——大约 10,700 行代码,负责从 Prompt(提示词)组装到工具

提示词组装

sidebar position: 5 title: "提示词组装" description: "Hermes 如何构建系统提示词、保持缓存稳定性和注入临时层" Hermes 刻意将以下两者分离: - 缓存的系统提示词状态 - 临时的 API 调用时添加内容 这是项目中最关键的设计决策之一,因为它影响:

上下文压缩与缓存

Hermes Agent 使用双重压缩系统和 Anthropic 提示词缓存,在长对话中高效管理上下文窗口的使用。 源文件:agent/context engine.py(ABC)、agent/context compressor.py(默认引擎)、agent/prompt caching.py、gateway/run

网关内部机制

sidebar position: 7 title: "网关内部机制" description: "消息网关如何启动、授权用户、路由会话和投递消息" 消息网关是一个长运行进程,通过统一架构将 Hermes 连接到 14+ 个外部消息平台。 当消息从任何平台到达时: 1. 平台适配器 接收原始事件,将其规范化为 Mess

会话存储

Hermes Agent 使用 SQLite 数据库( /.hermes/state.db)来持久化会话元数据、完整消息历史和模型配置,覆盖 CLI 和网关会话。这取代了早期基于每个会话 JSONL 文件的方式。 源文件:hermes state.py 关键设计决策: - WAL 模式 用于并发读取 + 单个写入器(网

相关节点

Agent 循环内部机制

sidebar position: 3 title: "Agent 循环内部机制" description: "AIAgent 执行、API 模式、工具、回调和回退行为的详细解析" 核心编排引擎是 run agent.py 中的 AIAgent 类——大约 10,700 行代码,负责从 Prompt(提示词)组装到工具

提示词组装

sidebar position: 5 title: "提示词组装" description: "Hermes 如何构建系统提示词、保持缓存稳定性和注入临时层" Hermes 刻意将以下两者分离: - 缓存的系统提示词状态 - 临时的 API 调用时添加内容 这是项目中最关键的设计决策之一,因为它影响:

Provider 运行时解析

sidebar position: 4 title: "Provider 运行时解析" description: "Hermes 如何在运行时解析 Provider、凭据、API 模式和辅助模型" Hermes 有一个共享的 Provider 运行时解析器,在以下场景中使用: - CLI

添加 Provider

sidebar position: 5 title: "添加 Provider" description: "如何向 Hermes Agent 添加新的推理 Provider——认证、运行时解析、CLI 流程、适配器、测试和文档" Hermes 已经可以通过自定义 Provider 路径与任何 OpenAI 兼容端点通

工具运行时(Tools Runtime)

原文链接:Tools Runtime sidebar position: 9 title: "Tools Runtime" description: "Runtime behavior of the tool registry, toolsets, dispatch, and terminal environments

会话存储

Hermes Agent 使用 SQLite 数据库( /.hermes/state.db)来持久化会话元数据、完整消息历史和模型配置,覆盖 CLI 和网关会话。这取代了早期基于每个会话 JSONL 文件的方式。 源文件:hermes state.py 关键设计决策: - WAL 模式 用于并发读取 + 单个写入器(网