架构
本页是 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 会话
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
网关消息
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
推荐阅读顺序
如果你是初次接触该代码库,建议按以下顺序阅读:
- 本页 —— 快速建立整体认知
- Agent Loop 内部机制 —— 了解 AIAgent 的工作原理
- 提示词组装 —— 系统提示词的构建方式
- 提供者运行时解析 —— 提供者如何被选择
- 添加提供者 —— 实用指南:如何新增一个提供者
- 工具运行时 —— 工具注册表、调度机制与运行环境
- 会话存储 —— SQLite 模式、FTS5 全文搜索、会话传承关系
- 网关内部机制 —— 多平台消息网关实现
- 上下文压缩与提示词缓存 —— 上下文压缩与缓存策略
- ACP 内部机制 —— 集成开发环境(IDE)支持
- 环境、基准测试与数据生成 —— 强化学习训练相关功能
主要子系统
Agent Loop(代理循环)
同步编排引擎(AIAgent 在 run_agent.py 中)。负责提供者选择、提示词构造、工具执行、重试机制、降级处理、回调通知、上下文压缩及持久化。支持三种 API 模式以适配不同提供者后端。
提示词系统
在整个对话生命周期中对提示词进行构建与维护:
prompt_builder.py—— 从以下来源组装系统提示词:个性设定(SOUL.md)、记忆内容(MEMORY.md、USER.md)、技能配置、上下文文件(AGENTS.md、.hermes.md)、工具使用指引,以及模型特定指令prompt_caching.py—— 对 Anthropic 模型应用缓存断点(prefix caching)context_compressor.py—— 当上下文超过阈值时,自动对中间对话轮次进行摘要压缩
提供者解析
CLI、网关、定时任务、ACP 及辅助调用共用的运行时解析器。将 (provider, model) 元组映射为 (api_mode, api_key, base_url)。支持 18+ 种提供者,处理 OAuth 流程、凭证池管理、别名解析等功能。
→ 提供者运行时解析
工具系统
中央工具注册中心(tools/registry.py),包含 47 个已注册工具,覆盖 19 个工具集。每个工具文件在导入时自动注册。注册表负责收集 Schema、分发调用、检查可用性并封装错误。终端工具支持 6 种后端:本地、Docker、SSH、Daytona、Modal、Singularity。
→ 工具运行时
会话持久化
基于 SQLite 的会话存储,集成 FTS5 全文检索功能。支持会话传承追踪(压缩前后的父子关系)、各平台隔离,以及带竞争处理的原子写入。
→ 会话存储
消息网关
长期运行的服务进程,内置 18 个平台适配器,统一会话路由,用户授权(白名单 + 私聊配对),斜杠命令分发,钩子系统,定时触发(cron tick),后台维护任务。
→ 网关内部机制
插件系统
三种发现源:~/.hermes/plugins/(用户级)、.hermes/plugins/(项目级)和 pip 入口点。插件通过上下文 API 注册工具、钩子和 CLI 命令。存在两种专用插件类型:记忆提供者(plugins/memory/)和上下文引擎(plugins/context_engine/)。两者均为单选模式——同一时间只能启用一个,可通过 hermes plugins 或 config.yaml 配置。
定时任务(Cron)
第一类原生代理任务(非 shell 脚本任务)。任务以 JSON 格式存储,支持多种调度格式,可附加技能或脚本,并可投递至任意平台。
→ 定时任务内部机制
ACP 集成
通过标准输入/输出或 JSON-RPC 协议,将 Hermes 作为编辑器原生代理暴露给 VS Code、Zed 和 JetBrains 等 IDE。
→ ACP 内部机制
强化学习 / 环境 / 轨迹生成
完整的环境框架,用于评估与强化学习训练。与 Atropos 集成,支持多种工具调用解析器,并可生成 ShareGPT 格式的轨迹数据。
设计原则
| 原则 | 实际含义 |
|---|---|
| 提示词稳定性 | 对话过程中系统提示词不会意外变更。仅当用户显式操作(如 /model)时才允许破坏缓存的修改。 |
| 可观测执行 | 每一次工具调用都会通过回调向用户可见。CLI 中显示进度条(spinner),网关中发送聊天消息更新。 |
| 可中断性 | 用户输入或信号可随时中止正在进行的 API 调用或工具执行。 |
| 平台无关的核心 | 同一个 AIAgent 类同时服务于 CLI、网关、ACP、批处理任务和 API 服务器。平台差异仅存在于入口点,而非核心逻辑。 |
| 松耦合设计 | 可选子系统(如 MCP、插件、记忆提供者、RL 环境)采用注册表模式与 check_fn 门控机制,避免硬依赖。 |
| 配置文件隔离 | 每个配置文件(hermes -p <name>)拥有独立的 HERMES_HOME、配置、记忆、会话及网关 PID。多个配置文件可并发运行。 |
文件依赖链
tools/registry.py (no deps — imported by all tool files)
↑
tools/*.py (each calls registry.register() at import time)
↑
model_tools.py (imports tools/registry + triggers tool discovery)
↑
run_agent.py, cli.py, batch_runner.py, environments/
此依赖链意味着工具注册发生在导入阶段,早于任何 agent 实例创建。新增工具需在 model_tools.py 的 _discover_tools() 列表中添加导入项。