H繁中版
<!-- Source: https://hermesbible.com/docs/developer-guide/architecture -->

本頁是 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.  │  │ 70+ tools    │               │
│  │              │  │ anthropic    │  │ 28 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 — 核心對話迴圈(大型檔案)
├── cli.py                    # HermesCLI — 互動式終端機 UI(大型檔案)
├── model_tools.py            # 工具發現、schema 收集、dispatch
├── toolsets.py               # 工具群組與平台預設值
├── hermes_state.py           # SQLite 會話/狀態資料庫,含 FTS5
├── hermes_constants.py       # HERMES_HOME、profile-aware 路徑
├── batch_runner.py           # 批次軌跡產生
│
├── agent/                    # Agent 內部實作
│   ├── prompt_builder.py     # 系統提示組裝
│   ├── context_engine.py     # ContextEngine ABC(可插拔)
│   ├── context_compressor.py # 預設引擎 — 有損摘要
│   ├── prompt_caching.py     # Anthropic 提示快取
│   ├── auxiliary_client.py   # 輔助 LLM,處理副任務(視覺、摘要)
│   ├── model_metadata.py     # 模型上下文長度、token 估算
│   ├── models_dev.py         # models.dev 註冊表整合
│   ├── anthropic_adapter.py  # Anthropic Messages API 格式轉換
│   ├── display.py            # KawaiiSpinner、工具預覽格式化
│   ├── skill_commands.py     # Skill 斜線命令
│   ├── memory_manager.py    # Memory manager 協調
│   ├── memory_provider.py   # Memory provider ABC
│   └── trajectory.py         # 軌跡儲存輔助
│
├── hermes_cli/               # CLI 子命令與設定
│   ├── main.py               # 進入點 — 所有 `hermes` 子命令(大型檔案)
│   ├── config.py             # DEFAULT_CONFIG、OPTIONAL_ENV_VARS、遷移
│   ├── commands.py           # COMMAND_REGISTRY — 中央斜線命令定義
│   ├── auth.py               # PROVIDER_REGISTRY、憑證解析
│   ├── runtime_provider.py   # Provider → api_mode + credentials
│   ├── models.py             # 模型目錄、供應商模型列表
│   ├── model_switch.py       # /model 命令邏輯(CLI + gateway 共用)
│   ├── setup.py              # 互動式設定精靈(大型檔案)
│   ├── skin_engine.py        # CLI 主題引擎
│   ├── skills_config.py      # hermes skills — 依平台啟用/停用
│   ├── skills_hub.py         # /skills 斜線命令
│   ├── tools_config.py       # hermes tools — 依平台啟用/停用
│   ├── plugins.py            # PluginManager — 發現、載入、hooks
│   ├── callbacks.py          # 終端機回呼(clarify、sudo、approval)
│   └── gateway.py            # hermes gateway start/stop
│
├── tools/                    # 工具實作(每個工具一個檔案)
│   ├── registry.py           # 中央工具註冊表
│   ├── approval.py           # 危險指令偵測
│   ├── terminal_tool.py      # 終端機協調
│   ├── process_registry.py   # 背景程序管理
│   ├── file_tools.py         # read_file、write_file、patch、search_files
│   ├── web_tools.py          # web_search、web_extract
│   ├── browser_tool.py       # 10 個瀏覽器自動化工具
│   ├── code_execution_tool.py # execute_code 沙箱
│   ├── delegate_tool.py      # 子代理委派
│   ├── mcp_tool.py           # MCP 客戶端(大型檔案)
│   ├── credential_files.py   # 基於檔案的憑證傳遞
│   ├── env_passthrough.py    # 沙箱的環境變數傳遞
│   ├── ansi_strip.py         # ANSI 跳脫序列移除
│   └── environments/         # 終端機後端(local、docker、ssh、modal、daytona、singularity)
│
├── gateway/                  # 訊息平台閘道器
│   ├── run.py                # GatewayRunner — 訊息分派(大型檔案)
│   ├── session.py            # SessionStore — 對話持久化
│   ├── delivery.py           # 外發訊息遞送
│   ├── pairing.py            # DM 配對授權
│   ├── hooks.py              # Hook 發現與生命週期事件
│   ├── mirror.py             # 跨會話訊息鏡像
│   ├── status.py             # Token 鎖、profile 範圍的程序追蹤
│   ├── builtin_hooks/        # 永遠註冊的 hook 擴充點(目前無內建)
│   └── platforms/            # 20 個適配器:telegram、discord、slack、whatsapp、
│                             #   signal、matrix、mattermost、email、sms、
│                             #   dingtalk、feishu、wecom、wecom_callback、weixin、
│                             #   bluebubbles、qqbot、homeassistant、webhook、api_server、
│                             #   yuanbao
│
├── acp_adapter/              # ACP 伺服器(VS Code / Zed / JetBrains)
├── cron/                     # 排程器(jobs.py、scheduler.py)
├── plugins/memory/           # Memory provider 外掛
├── plugins/context_engine/   # Context engine 外掛
├── skills/                   # 內建技能(永遠可用)
├── optional-skills/          # 官方可選技能(需明確安裝)
├── website/                  # Docusaurus 文件網站
└── tests/                    # Pytest 測試套件(約 25,000 個測試,分佈在約 1,250 個檔案中)

資料流程

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

Gateway 訊息

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

排程任務

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. 供應商執行時解析 — 供應商如何被選定
  5. 新增供應商 — 新增供應商的實務指南
  6. 工具執行環境 — 工具註冊表、分派、環境
  7. 會話儲存 — SQLite schema、FTS5、會話血緣
  8. 閘道器內部 — 訊息平台閘道器
  9. 上下文壓縮與提示快取 — 壓縮與快取
  10. ACP 內部 — IDE 整合

主要子系統

Agent 迴圈

同步協調引擎(run_agent.py 中的 AIAgent)。處理供應商選擇、提示建構、工具執行、重試、降級、回呼、壓縮與持久化。支援三種 API 模式以對應不同的供應商後端。

Agent 迴圈內部

提示系統

跨越對話生命週期的提示建構與維護:

  • system_prompt.py + prompt_builder.py — 組裝有序的系統提示層級(stablecontextvolatile):身分/工具指引/技能、上下文檔案,然後是記憶/個人檔案/時間戳區塊
  • prompt_caching.py — 套用 Anthropic 快取斷點以進行前綴快取
  • context_compressor.py — 當上下文超過閾值時,摘要中間對話輪次

提示組裝上下文壓縮與提示快取

供應商解析

CLI、閘道器、排程任務、ACP 和輔助呼叫共用的執行時解析器。將 (provider, model) 元組對映為 (api_mode, api_key, base_url)。處理 18 種以上的供應商、OAuth 流程、憑證池和別名解析。

供應商執行時解析

工具系統

中央工具註冊表(tools/registry.py),包含 70 多個已註冊工具,分佈在約 28 個工具集中。每個工具檔案在匯入時自動向註冊表報到。註冊表處理 schema 收集、分派、可用性檢查和錯誤包裝。終端機工具支援 6 種後端(local、Docker、SSH、Daytona、Modal、Singularity)。

工具執行環境

會話持久化

基於 SQLite 的會話儲存,搭配 FTS5 全文搜尋。會話具有血緣追蹤(壓縮產生的 parent/child 關係)、按平台隔離,以及帶有競爭處理的原子寫入。

會話儲存

訊息閘道器

長駐程序,具備 20 個平台適配器、統一的會話路由、使用者授權(允許清單 + DM 配對)、斜線命令分派、hook 系統、排程心跳與背景維護。

閘道器內部

外掛系統

三個發現來源:~/.hermes/plugins/(使用者)、.hermes/plugins/(專案)和 pip 入口點。外掛透過上下文 API 註冊工具、hook 和 CLI 命令。存在兩種特殊的外掛類型:memory provider(plugins/memory/)和 context engine(plugins/context_engine/)。兩者都是單選——同時只能啟用一個,透過 hermes pluginsconfig.yaml 設定。

外掛指南Memory Provider 外掛

排程任務

一等公民的 Agent 任務(非 shell 任務)。任務以 JSON 儲存,支援多種排程格式,可附加技能和腳本,並遞送到任意平台。

排程任務內部

ACP 整合

透過 stdio/JSON-RPC 將 Hermes 暴露為編輯器原生 Agent,支援 VS Code、Zed 和 JetBrains。

ACP 內部

軌跡

從 Agent 會話產生 ShareGPT 格式的軌跡,用於訓練資料生成。

軌跡與訓練格式

設計原則

原則實務意義
提示穩定性系統提示在對話過程中不會變動。除了使用者明確操作(/model)外,不會產生破壞快取的變更。
可觀察的執行每次工具呼叫都透過回呼對使用者可見。CLI 中有進度更新(旋轉器),閘道器中有聊天訊息。
可中斷API 呼叫和工具執行可被使用者輸入或訊號在中途取消。
平台無關的核心同一個 AIAgent 類別服務 CLI、閘道器、ACP、批次處理和 API 伺服器。平台差異存在於進入點中,而非 Agent 本身。
鬆散耦合可選子系統(MCP、外掛、memory provider、RL 環境)使用註冊表模式和 check_fn 閘控,而非硬性依賴。
Profile 隔離每個 profile(hermes -p <name>)擁有獨立的 HERMES_HOME、設定、記憶、會話和閘道器 PID。多個 profile 可同時運行。

檔案依賴鏈

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 檔案都會被自動發現——不需要手動匯入清單。



Agent 迴圈內部