# Hermes Agent — 原始搜索结果 > 来源: `ant-backups/knowledge-base/工具篇/HERMES-COMPLETE-REFERENCE.md` (61,520行) > 提取日期: 2026-06-21 --- ## 一、基本信息 - **全称**: Hermes Agent - **开发方**: Nous Research - **开源协议**: MIT - **语言**: Python - **文档源**: `https://hermes-agent.nousresearch.com/docs` - **简短索引**: `https://hermes-agent.nousresearch.com/docs/llms.txt` --- ## 二、安装与配置 ### 安装方式 | 方式 | 命令 | 说明 | |------|------|------| | curl 安装 (Linux/macOS/WSL2/Android) | `curl -fsSL https://hermes-agent.nousresearch.com/install.sh \| bash` | 自动处理依赖 (Python, Node.js, ripgrep, ffmpeg) | | PowerShell (Windows) | `iex (irm https://hermes-agent.nousresearch.com/install.ps1)` | — | | pip 安装 | `pip install hermes-agent` | PyPI 发布版 | | 无浏览器安装 | `curl ... \| bash -s -- --skip-browser` | 跳过 Playwright | | 无技能安装 | `curl ... \| bash -s -- --no-skills` | 不预装 bundled skills | ### 安装目录 | 安装方式 | 代码位置 | hermes 命令 | 数据目录 | |----------|----------|------------|----------| | pip install | Python site-packages | `~/.local/bin/hermes` | `~/.hermes/` | | Per-user (git) | `~/.hermes/hermes-agent/` | `~/.local/bin/hermes` (symlink) | `~/.hermes/` | | Root-mode | `/usr/local/lib/hermes-agent/` | `/usr/local/bin/hermes` | `/root/.hermes/` | ### 配置存储 - **密钥/token** → `~/.hermes/.env` - **非密钥配置** → `~/.hermes/config.yaml` ### 核心配置命令 | 命令 | 用途 | |------|------| | `hermes model` | 选择 LLM 提供方和模型 | | `hermes setup` | 完整设置向导 | | `hermes setup --portal` | 一键 Nous Portal OAuth 设置 | | `hermes tools` | 配置工具启用/禁用 | | `hermes doctor` | 诊断问题 | | `hermes gateway setup` | 设置消息平台 | --- ## 三、支持的 LLM 提供方 | 提供方 | 环境变量 | 认证方式 | |--------|----------|----------| | **OpenRouter** | `OPENROUTER_API_KEY` | API Key — 推荐用于灵活性 | | **Nous Portal** | (自动) | OAuth — 推荐新用户 | | **OpenAI Codex** | `OPENAI_API_KEY` | OAuth 或 API Key | | **Anthropic (Claude)** | `ANTHROPIC_API_KEY` | OAuth (需 Max 计划+额外额度) 或 API Key | | **Google Gemini** | `GOOGLE_API_KEY` / `GEMINI_API_KEY` | API Key 或 OAuth | | **DeepSeek** | `DEEPSEEK_API_KEY` | API Key | | **Alibaba (Qwen)** | `DASHSCOPE_API_KEY` | API Key | | **z.ai / ZhipuAI** | `GLM_API_KEY` / `ZAI_API_KEY` / `Z_AI_API_KEY` | API Key | | **Kimi / Moonshot** | `KIMI_API_KEY` | API Key | | **MiniMax** | `MINIMAX_API_KEY` / `MINIMAX_CN_API_KEY` | API Key 或 OAuth | | **GitHub Copilot** | `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` | OAuth | | **xAI (Grok)** | `XAI_API_KEY` | API Key 或 OAuth | | **Hugging Face** | `HF_TOKEN` | 统一路由 20+ 开源模型 | | **AWS Bedrock** | `AWS_REGION` / `AWS_PROFILE` | IAM role 或 `aws configure` | | **Azure Foundry** | `AZURE_FOUNDRY_API_KEY` + `AZURE_FOUNDRY_BASE_URL` | API Key 或 Entra ID | | **NVIDIA NIM** | `NVIDIA_API_KEY` | API Key | | **Local (Ollama/vLLM/etc)** | (自定义) | 自定义 endpoint | | **Alibaba Coding Plan** | `ALIBABA_CODING_PLAN_API_KEY` | API Key | | **Arcee AI** | `ARCEEAI_API_KEY` | API Key | | **GMI Cloud** | `GMI_API_KEY` | API Key | | **StepFun** | `STEPFUN_API_KEY` | API Key | | **Xiaomi MiMo** | `XIAOMI_API_KEY` | API Key | | **Tencent TokenHub** | `TOKENHUB_API_KEY` | API Key | | **Ollama Cloud** | `OLLAMA_API_KEY` | API Key | | **LM Studio** | `LM_API_KEY` | API Key | | **NovitaAI** | `NOVITA_API_KEY` | API Key | | **Kilo Code** | `KILOCODE_API_KEY` | API Key | | **OpenCode Zen/Go** | `OPENCODE_ZEN_API_KEY` / `OPENCODE_GO_API_KEY` | API Key | | **Qwen OAuth** | `HERMES_QWEN_BASE_URL` | OAuth | | **Copilot ACP** | `HERMES_COPILOT_ACP_COMMAND` | CLI | **最低上下文要求**: 64K tokens --- ## 四、核心架构 ### 架构图 ``` 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 │ └────┬─────┘ └────┬─────┘ └────┬─────┘ ┌────┴─────┐ ┌────┴─────┐ ┌────┴─────┐ │Compress │ │3 API Modes│ │ Registry │ │& Caching │ │chat/ │ │70+ tools │ │ │ │codex/an- │ │28 toolsets│ │ │ │thropic │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ ▼ ▼ Session Storage Tool Backends (SQLite + FTS5) Terminal (6 backends) Browser (5 backends) Web (4 backends) MCP (dynamic) ``` ### 目录结构 ``` hermes-agent/ ├── run_agent.py # AIAgent — 核心对话循环 (~4,400行) ├── cli.py # HermesCLI — 交互式终端 UI ├── model_tools.py # 工具发现、schema集合、分发 ├── toolsets.py # 工具分组和平台预设 ├── hermes_state.py # SQLite 会话/状态数据库 (FTS5) ├── hermes_constants.py # HERMES_HOME, profile-aware paths ├── batch_runner.py # 批量轨迹生成 │ ├── agent/ # Agent 内部实现 │ ├── prompt_builder.py # System prompt 组装 │ ├── context_engine.py # ContextEngine ABC (可插拔) │ ├── context_compressor.py # 默认引擎 — 有损摘要 │ ├── prompt_caching.py # Anthropic prompt caching │ ├── auxiliary_client.py # 辅助 LLM (vision, summarization) │ ├── model_metadata.py # 模型上下文长度、token估算 │ ├── models_dev.py # models.dev registry │ ├── anthropic_adapter.py # Anthropic Messages API 格式转换 │ ├── display.py # KawaiiSpinner, 工具预览格式化 │ ├── skill_commands.py # Skill 斜杠命令 │ ├── memory_manager.py # 内存管理器 │ ├── memory_provider.py # 内存提供方 ABC │ └── trajectory.py # 轨迹保存辅助 │ ├── hermes_cli/ # CLI 子命令和设置 │ ├── main.py # 入口 — all `hermes` subcommands │ ├── config.py # DEFAULT_CONFIG, OPTIONAL_ENV_VARS │ ├── commands.py # COMMAND_REGISTRY — slash commands │ ├── auth.py # PROVIDER_REGISTRY, credential resolution │ ├── runtime_provider.py # Provider → api_mode + credentials │ ├── models.py # 模型目录, provider model lists │ ├── model_switch.py # /model 命令逻辑 │ ├── setup.py # 交互式设置向导 │ ├── skin_engine.py # CLI 主题引擎 │ ├── skills_config.py # skills enable/disable per platform │ ├── skills_hub.py # /skills 斜杠命令 │ ├── tools_config.py # tools enable/disable per platform │ ├── plugins.py # PluginManager │ ├── callbacks.py # Terminal callbacks │ └── gateway.py # hermes gateway start/stop │ ├── tools/ # 工具实现 (每工具一个文件) │ ├── registry.py # 中心工具注册表 │ ├── approval.py # 危险命令检测 │ ├── terminal_tool.py # Terminal 编排 │ ├── process_registry.py # 后台进程管理 │ ├── file_tools.py # read/write/patch/search files │ ├── web_tools.py # web_search, web_extract │ ├── browser_tool.py # 10 个浏览器自动化工具 │ ├── code_execution_tool.py # execute_code sandbox │ ├── delegate_tool.py # 子 agent 委托 │ ├── mcp_tool.py # MCP 客户端 │ ├── credential_files.py # 文件级凭据传递 │ ├── env_passthrough.py # 沙箱环境变量传递 │ ├── ansi_strip.py # ANSI 转义剥离 │ └── environments/ # Terminal 后端 (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/ # 扩展点 (无内置) │ └── 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/ # 内存提供方插件 ├── plugins/context_engine/ # 上下文引擎插件 ├── skills/ # Bundled skills (始终可用) ├── optional-skills/ # 官方可选 skills ├── website/ # Docusaurus 文档站 └── tests/ # Pytest (~25,000 tests / ~1,250 files) ``` ### 设计原则 | 原则 | 实际含义 | |------|----------| | **Prompt 稳定性** | System prompt 在对话中不变,除非显式 `/model` | | **可观察执行** | 每个工具调用通过回调对用户可见 | | **可打断** | API 调用和工具执行可由用户输入或信号取消 | | **平台无关核心** | 一个 AIAgent 服务 CLI/Gateway/ACP/Batch/API Server | | **松耦合** | 可选子系统通过 check_fn gating 而非硬依赖 | | **Profile 隔离** | 每个 profile 有独立 HERMES_HOME/config/memory/sessions | --- ## 五、Agent Loop (run_agent.py) ### 核心职责 - 组装 system prompt 和工具 schema (prompt_builder.py) - 选择正确的 provider/API mode - 可中断的模型调用 - 执行工具调用 (顺序或并发) - 维护 OpenAI 格式的对话历史 - 处理压缩、重试和 fallback 切换 - 跟踪迭代预算 (跨父/子 agent) - 在上下文丢失前刷新持久内存 ### 两种入口 ```python # 简单接口 — 返回最终响应字符串 response = agent.chat("Fix the bug in main.py") # 完整接口 — 返回 dict (messages, metadata, usage stats) result = agent.run_conversation( user_message="Fix the bug in main.py", system_message=None, conversation_history=None, task_id="task_abc123" ) ``` ### 三种 API Mode | API mode | 用于 | 客户端类型 | |----------|------|-----------| | `chat_completions` | OpenAI 兼容端点 (OpenRouter, 自定义, 大部分 provider) | `openai.OpenAI` | | `codex_responses` | OpenAI Codex / Responses API | `openai.OpenAI` (Responses 格式) | | `anthropic_messages` | 原生 Anthropic Messages API | `anthropic.Anthropic` (通过适配器) | ### 单轮生命周期 ``` run_conversation() 1. 生成 task_id (如未提供) 2. 追加用户消息到对话历史 3. 构建或复用缓存的 system prompt 4. 检查是否需要预压缩 (>50% 上下文) 5. 从对话历史构建 API 消息 6. 注入临时 prompt 层 (预算警告、上下文压力) 7. 对 Anthropic 应用 prompt caching 标记 8. 可中断的 API 调用 9. 解析响应: - 如含 tool_calls: 执行, 追加结果, 循环回步骤5 - 如为文本响应: 持久化会话, 刷新内存, 返回 ``` ### 消息格式 ```python {"role": "system", "content": "..."} {"role": "user", "content": "..."} {"role": "assistant", "content": "...", "tool_calls": [...]} {"role": "tool", "tool_call_id": "...", "content": "..."} ``` ### 消息交替规则 - System → User → Assistant → User → Assistant → ... - 工具调用时: Assistant (with tool_calls) → Tool → Tool → ... → Assistant - **不能**连续两个 assistant 消息 - **不能**连续两个 user 消息 - **仅** tool role 可以有连续条目 (并行工具结果) ### 可打断 API 调用 API 请求在后台线程执行,主线程等待响应/打断事件/超时。 打断时: API 线程被放弃 (响应丢弃),agent 处理新输入或清理关闭。 ### 工具执行 - **单个工具调用** → 主线程直接执行 - **多个工具调用** → 通过 ThreadPoolExecutor 并发执行 - 例外: `clarify` 等交互式工具强制顺序执行 - 结果按原始调用顺序插入 (无论完成顺序) 执行流程: ``` for each tool_call in response.tool_calls: 1. 从 registry.py 解析 handler 2. 触发 pre_tool_call 插件钩子 3. 检查是否危险命令 (approval.py) 4. 执行 handler (args + task_id) 5. 触发 post_tool_call 插件钩子 6. 追加 {"role": "tool", "content": result} 到历史 ``` ### Agent 级拦截工具 | 工具 | 拦截原因 | |------|----------| | `todo` | 读/写 agent 本地任务状态 | | `memory` | 写入持久内存文件 (有字符限制) | | `session_search` | 通过 agent 的会话 DB 查询历史 | | `delegate_task` | 生成子 agent (隔离上下文) | ### 回调表面 | 回调 | 触发时机 | 用途 | |------|----------|------| | `tool_progress_callback` | 每个工具执行前/后 | CLI spinner, gateway 进度消息 | | `thinking_callback` | 模型开始/停止思考 | CLI "thinking..." | | `reasoning_callback` | 模型返回推理内容 | CLI 推理显示 | | `clarify_callback` | 调用 clarify 工具时 | CLI 输入提示 | | `step_callback` | 每个完整 agent 轮次后 | Gateway 步骤追踪 | | `stream_delta_callback` | 每个流式 token | CLI 流式显示 | | `tool_gen_callback` | 从流解析到工具调用 | CLI 工具预览 | | `status_callback` | 状态变化 | ACP 状态更新 | ### 迭代预算 - 默认: 90 次迭代 (可通过 `agent.max_turns` 配置) - 子 agent 独立预算: `delegation.max_iterations` (默认 50) - 达到 100% 时停止并返回工作摘要 ### Fallback 行为 1. 检查 `fallback_providers` 列表 2. 按顺序尝试每个 fallback 3. 成功则继续对话 4. 401/403 时先尝试刷新凭据 --- ## 六、Prompt Assembly ### 三层缓存的 System Prompt 1. **stable (稳定层)** — 身份 (SOUL.md), 工具/模型指导, skills 提示, 环境提示, 平台提示 2. **context (上下文层)** — 调用方提供的 system_message + 项目上下文文件 3. **volatile (易变层)** — 内置内存快照 (MEMORY.md), 用户画像快照 (USER.md), 时间戳/会话/模型/provider 行 **拼接顺序**: `stable` → `context` → `volatile` ### 具体示例 ``` # Layer 1: Agent Identity (from ~/.hermes/SOUL.md) [SOUL.md 内容] # Layer 2: Tool-aware behavior guidance [工具使用指导] # Layer 3: Honcho static block (when active) [Honcho 个性/上下文] # Layer 4: Optional system message [用户配置的 system message] # Layer 5: Frozen MEMORY snapshot ## Persistent Memory - 记忆内容... # Layer 6: Frozen USER profile snapshot ## User Profile - 用户信息... # Layer 7: Skills index ## Skills (mandatory) [skills 列表] # Layer 8: Context files (from project) ## Project Context [项目上下文文件内容] # Layer 9: Timestamp + session Current time: ... Session: ... # Layer 10: Platform hint [平台提示] ``` ### SOUL.md - 路径: `~/.hermes/SOUL.md` - 作用: agent 身份 — system prompt 的第一部分 - 安全检查: 扫描 prompt 注入模式 - 截断: 20,000 字符上限 - 不存在时回退到 `DEFAULT_AGENT_IDENTITY` ### 上下文文件优先级 | 优先级 | 文件 | 搜索范围 | |--------|------|----------| | 1 | `.hermes.md`, `HERMES.md` | CWD 到 git root | | 2 | `AGENTS.md` | CWD 仅 | | 3 | `CLAUDE.md` | CWD 仅 | | 4 | `.cursorrules`, `.cursor/rules/*.mdc` | CWD 仅 | ### API 调用时仅追加的层 (不缓存) - `ephemeral_system_prompt` - prefill messages - gateway 派生的会话上下文覆盖 - Honcho/external recall (注入当前轮次 user message) --- ## 七、Context Compression & Caching ### 双压缩系统 ``` Incoming message → Gateway Session Hygiene (85% threshold, safety net) → Agent ContextCompressor (50% threshold, primary) ``` ### Gateway Session Hygiene (85%) - 位置: `gateway/run.py` - 阈值: 固定 85% 模型上下文长度 - token 来源: 优先使用 API 报告的 token 数 - 触发条件: `len(history) >= 4` 且压缩开启 ### Agent ContextCompressor (50%, 可配置) - 位置: `agent/context_compressor.py` - 默认阈值: 50% 上下文窗口 - 有准确的 API 报告的 token 计数 ### 配置 ```yaml compression: enabled: true threshold: 0.50 # 默认 50% target_ratio: 0.20 # 尾保留比例 protect_last_n: 20 # 最少保留的尾消息数 auxiliary: compression: model: null provider: auto base_url: null ``` ### 压缩参数 | 参数 | 默认值 | 范围 | 说明 | |------|--------|------|------| | `threshold` | 0.50 | 0.0-1.0 | 触发阈值 | | `target_ratio` | 0.20 | 0.10-0.80 | 尾保留 token 预算 | | `protect_last_n` | 20 | ≥1 | 最近消息保留数 | | `protect_first_n` | 3 | (硬编码) | system + 首次交换 | ### 压缩算法 4 阶段 1. **修剪旧工具结果** — 无需 LLM 调用,替换冗长输出 2. **确定边界** — 保护头部 + 中间摘要 + 保护尾部 3. **生成结构化摘要** — 使用辅助 LLM,格式: - ## Goal / ## Constraints & Preferences / ## Progress / ## Key Decisions / ## Relevant Files / ## Next Steps / ## Critical Context - 摘要预算: `content_tokens × 0.20`,最少 2,000,最多 `min(context_length × 0.05, 12,000)` 4. **组装压缩消息** — 头部 + 摘要 + 尾部,清理孤立的 tool_call/tool_result 对 **注意**: 摘要模型的上下文窗口必须 >= 主模型的上下文窗口 ### Prompt Caching (Anthropic) - 策略: "system_and_3" - 4 个 breakpoints: 1个system + 3个最近消息滚动窗口 - TTL: 默认 5m,可配置为 1h - 自动启用条件: Claude 模型 + 支持 cache_control 的 provider --- ## 八、Gateway 内部 ### 职责 - 管理 20+ 消息平台的适配器 - 统一会话路由 - 用户授权 (allowlist + DM pairing) - 斜杠命令分发 - Hook 系统 - Cron 调度 - 后台维护 ### 架构 ``` GatewayRunner ├── Telegram Adapter ├── Discord Adapter ├── Slack Adapter ├── ... (20+ platforms) │ └── 统一处理: ├── 用户授权 ├── 会话键解析 ├── AIAgent 创建 ├── 响应投递 └── Hook 事件 ``` ### 数据流 (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 ``` ### 关键文件 | 文件 | 用途 | |------|------| | `gateway/run.py` | GatewayRunner — 主循环, slash commands, 消息分发 | | `gateway/session.py` | SessionStore — 会话持久化和会话键构建 | | `gateway/delivery.py` | 出站消息投递 | | `gateway/pairing.py` | DM 配对流 | | `gateway/channel_directory.py` | 聊天 ID 到名称的映射 | | `gateway/hooks.py` | Hook 发现和生命周期事件分发 | | `gateway/mirror.py` | 跨会话消息镜像 | | `gateway/status.py` | Token 锁管理 | | `gateway/platforms/` | 平台适配器 | ### 消息流 (Gateway → adapter) ``` GatewayRunner → delivery.py → Platform adapter → platform-specific API (Telegram sendMessage, Discord send, etc.) ``` --- ## 九、Session Storage (hermes_state.py) ### 架构 ``` ~/.hermes/state.db (SQLite, WAL mode) ├── sessions — 会话元数据, token 计数, 计费 ├── messages — 完整消息历史 ├── messages_fts — FTS5 虚拟表 (内容搜索) ├── messages_fts_trigram — FTS5 trigram (CJK/子串搜索) ├── state_meta — 键/值元数据表 └── schema_version — 迁移状态追踪 ``` ### Sessions 表 ```sql CREATE TABLE IF NOT EXISTS sessions ( id TEXT PRIMARY KEY, source TEXT NOT NULL, user_id TEXT, model TEXT, model_config TEXT, system_prompt TEXT, parent_session_id TEXT, started_at REAL NOT NULL, ended_at REAL, end_reason TEXT, message_count INTEGER DEFAULT 0, tool_call_count INTEGER DEFAULT 0, input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0, cache_read_tokens INTEGER DEFAULT 0, cache_write_tokens INTEGER DEFAULT 0, reasoning_tokens INTEGER DEFAULT 0, billing_provider TEXT, billing_base_url TEXT, billing_mode TEXT, estimated_cost_usd REAL, actual_cost_usd REAL, cost_status TEXT, cost_source TEXT, pricing_version TEXT, title TEXT, api_call_count INTEGER DEFAULT 0, FOREIGN KEY (parent_session_id) REFERENCES sessions(id) ); ``` ### Messages 表 ```sql CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL REFERENCES sessions(id), role TEXT NOT NULL, content TEXT, tool_call_id TEXT, tool_calls TEXT, tool_name TEXT, timestamp REAL NOT NULL, token_count INTEGER, finish_reason TEXT, reasoning TEXT, reasoning_content TEXT, reasoning_details TEXT, codex_reasoning_items TEXT, codex_message_items TEXT ); ``` ### Schema 版本 当前版本: **11** (从 v1 递增至 v11,包括 billing 列、reasoning 列、FTS5 trigram、codex_message_items 等) ### 写冲突处理 - SQLite 超时: 1 秒 - 应用层重试: 随机抖动 20-150ms, 最多 15 次 - BEGIN IMMEDIATE 事务 - 每 50 次写入做 WAL checkpoint (PASSIVE mode) ### 会话谱系 (压缩触发分割) - `parent_session_id` 链追踪压缩触发的父子会话关系 - compression 会创建一个 "child" session ### FTS5 搜索语法 | 语法 | 示例 | 含义 | |------|------|------| | 关键词 | `docker deployment` | 同时匹配 (隐式 AND) | | 引号短语 | `"exact phrase"` | 精确短语 | | Boolean OR | `docker OR kubernetes` | 任一匹配 | | Boolean NOT | `python NOT java` | 排除 | | 前缀 | `deploy*` | 前缀匹配 | --- ## 十、Provider Runtime Resolution ### 解析优先级 1. 显式 CLI/runtime 请求 2. `config.yaml` model/provider 配置 3. 环境变量 4. Provider 特定默认值或自动解析 ### 支持 Provider 列表 OpenRouter, Nous Portal, OpenAI Codex, Copilot, Anthropic, Google/Gemini, Alibaba/DashScope, DeepSeek, Z.AI, Kimi/Moonshot, MiniMax, Kilo Code, Hugging Face, OpenCode Zen/Go, AWS Bedrock, Azure Foundry, NVIDIA NIM, xAI (Grok), Arcee, GMI Cloud, StepFun, Qwen OAuth, Xiaomi, Ollama Cloud, LM Studio, Tencent TokenHub, Custom, Named custom providers ### 解析输出 - `provider` - `api_mode` - `base_url` - `api_key` - `source` - provider-specific metadata (expiry/refresh) ### 辅助模型路由 辅助任务 (vision, web extraction, compression, skills hub, MCP, memory flushes) 可使用独立的 provider/model ### Fallback 机制 - 存储为 `(provider, model)` 列表 - 触发点: 无效 API 响应 / 客户端错误 (401,403,404) / 临时错误 (429,500,502,503) - 激活后原地替换: model, provider, base_url, api_mode, client - 子 agent 不继承 fallback 配置 - 辅助任务有独立的 fallback 链 --- ## 十一、工具系统 ### 可用工具类别 | 类别 | 示例 | 说明 | |------|------|------| | **Web** | `web_search`, `web_extract` | 网页搜索和内容提取 | | **X Search** | `x_search` | X (Twitter) 搜索 (需 xAI 凭证) | | **Terminal & Files** | `terminal`, `process`, `read_file`, `patch` | 命令执行和文件操作 | | **Browser** | `browser_navigate`, `browser_snapshot`, `browser_vision` | 浏览器自动化 | | **Media** | `vision_analyze`, `image_generate`, `text_to_speech` | 多模态分析和生成 | | **Agent orchestration** | `todo`, `clarify`, `execute_code`, `delegate_task` | 规划、澄清、代码执行、子 agent | | **Memory & recall** | `memory`, `session_search` | 持久内存和会话搜索 | | **Automation & delivery** | `cronjob`, `send_message` | 定时任务和消息投递 | | **Integrations** | `ha_*`, MCP server tools, `rl_*` | Home Assistant, MCP, RL training | ### 工具注册 - 每个工具文件在 `tools/` 目录下通过 `registry.register()` 自注册 - 自动发现 — 无需手动导入列表 - 添加工具只需: 1) `tools/your_tool.py` 2) `toolsets.py` 中添加到对应工具集 ### Terminal 后端 (6 种) | 后端 | 说明 | 用例 | |------|------|------| | `local` | 本机执行 | 开发、可信任务 | | `docker` | 隔离容器 | 安全、可重现 | | `ssh` | 远程服务器 | 沙箱、隔离 | | `singularity` | HPC 容器 | 集群计算、rootless | | `modal` | 云执行 | Serverless、扩展 | | `daytona` | 云沙箱 | 持久远程开发环境 | ### Docker 后端特性 - 一个持久容器,跨进程共享 - 工作目录更改、安装的包、写入的文件在工具调用间保留 (包括 `/new`、`/reset`、`delegate_task`) - 容器在关闭时停止并删除 ### 后台进程管理 ```python terminal(command="pytest -v tests/", background=true) # → {"session_id": "proc_abc123", "pid": 12345} process(action="list") # 显示所有运行中进程 process(action="poll", ...) # 检查状态 process(action="wait", ...) # 阻塞直到完成 process(action="log", ...) # 完整输出 process(action="kill", ...) # 终止 process(action="write", ...) # 发送输入 ``` --- ## 十二、Skill 系统 ### 位置 - 主目录: `~/.hermes/skills/` — 单一事实来源 - 外部目录: 通过 config.yaml 的 `skills.external_dirs` 配置 ### 目录结构 ``` ~/.hermes/skills/ ├── mlops/ │ ├── axolotl/ │ │ ├── SKILL.md │ │ ├── references/ │ │ ├── templates/ │ │ ├── scripts/ │ │ └── assets/ │ └── vllm/ │ └── SKILL.md ├── devops/ │ └── deploy-k8s/ │ └── SKILL.md ├── .hub/ │ ├── lock.json │ ├── quarantine/ │ └── audit.log └── .bundled_manifest ``` ### SKILL.md 格式 ```yaml --- name: my-skill description: Brief description version: 1.0.0 platforms: [macos, linux] metadata: hermes: tags: [python, automation] category: devops fallback_for_toolsets: [web] requires_toolsets: [terminal] config: - key: my.setting description: "What this controls" default: "value" prompt: "Prompt for setup" --- ``` ### 渐进式披露 ``` Level 0: skills_list() → [{name, description, category}, ...] (~3k tokens) Level 1: skill_view(name) → Full content + metadata (varies) Level 2: skill_view(name, path) → Specific reference file (varies) ``` ### 使用方式 - 自动注册为斜杠命令: `/gif-search`, `/plan`, `/my-skill` - 自然对话: `hermes chat --toolsets skills -q "What skills do you have?"` ### 条件激活 (Fallback Skills) | 字段 | 行为 | |------|------| | `fallback_for_toolsets: [web]` | 当 web 工具集不可用时显示 | | `requires_toolsets: [terminal]` | 当 terminal 可用时显示 | ### Skill Bundles 将多个 skills 归组到一个斜杠命令下: ```bash hermes bundles create backend-dev \ --skill github-code-review \ --skill test-driven-development ``` --- ## 十三、内存系统 ### 文件 | 文件 | 用途 | 字符限制 | |------|------|----------| | **MEMORY.md** | Agent 个人笔记 — 环境事实、约定、学到的知识 | 2,200 chars (~800 tokens) | | **USER.md** | 用户画像 — 偏好、沟通风格、期望 | 1,375 chars (~500 tokens) | 位置: `~/.hermes/memories/` ### 工具动作 - **add** — 添加新记忆 - **replace** — 替换已有记忆 (通过 substring 匹配 `old_text`) - **remove** — 移除记忆 (通过 substring 匹配) ### 功能对比: memory vs session_search | 特性 | 持久内存 | 会话搜索 | |------|----------|----------| | 容量 | ~1,300 tokens 总计 | 无限 (所有会话) | | 速度 | 即时 (在 system prompt 中) | ~20ms FTS5 查询 | | 成本 | 每次 prompt 的 token 成本 | 免费 — 无 LLM 调用 | | 用例 | 关键事实始终可用 | 查找特定过去对话 | | 管理 | 手动由 agent 维护 | 自动 — 所有会话存储 | ### 去重 自动拒绝完全重复的条目 ### 安全扫描 记忆条目在写入前扫描注入和泄露模式 --- ## 十四、委托 (Delegation) ### 单任务 ```python delegate_task( goal="Debug why tests fail", context="Error: assertion in test_foo.py line 42", toolsets=["terminal", "file"] ) ``` ### 并行批处理 最多 3 个子 agent 并发 (可配置): ```python delegate_task(tasks=[ {"goal": "Research topic A", "toolsets": ["web"]}, {"goal": "Research topic B", "toolsets": ["web"]}, {"goal": "Fix the build", "toolsets": ["terminal", "file"]} ]) ``` ### 关键: 子 Agent 零上下文 子 agent 完全不了解父 agent 的对话历史。必须在 `goal` 和 `context` 字段中传递所有需要的信息。 ### 限制 - 默认最大并发: 3 (可通过 `delegation.max_concurrent_children` 配置) - 默认迭代限制: 50 (`delegation.max_iterations`) - 子 agent 超时: 600 秒 (`delegation.child_timeout_seconds`) - 被阻止的工具: `delegation` (叶级子 agent), `clarify`, `memory`, `code_execution`, `send_message` ### 模型覆盖 ```yaml delegation: model: "google/gemini-flash-2.0" provider: "openrouter" ``` --- ## 十五、Cron 调度 ### 功能 - 一次性或重复任务 - 暂停、恢复、编辑、触发、移除 - 附加 0/1/多个 skills - 投递结果到来源聊天/本地文件/配置的平台 - Agent 模式 或 纯脚本模式 (no-agent, 零 LLM 调用) ### 创建方式 ```bash # 斜杠命令 /cron add 30m "Remind me to check the build" # CLI hermes cron create "every 2h" "Check server status" # 自然对话 "Every morning at 9am, check Hacker News for AI news and send me a summary on Telegram." ``` ### 禁止递归 Cron 运行中的会话不能递归创建 cron 作业 — 防止 runaway 调度循环 ### Workdir 支持 ```bash hermes cron create "every 1d at 09:00" \ "Audit open PRs" \ --workdir /home/me/projects/acme ``` ### Profile 支持 ```bash hermes cron create "every 1d at 03:00" \ "Tail the security log" \ --profile night-ops ``` ### 序列化 - 有 `workdir` 或 `profile` 的作业**顺序执行** (防止 cwd / HERMES_HOME 竞争) - 无 workdir/profile 的作业并行执行 --- ## 十六、Hook 系统 (3种) | 系统 | 注册方式 | 运行环境 | 用例 | |------|----------|----------|------| | **Gateway hooks** | `HOOK.yaml` + `handler.py` in `~/.hermes/hooks/` | Gateway 仅 | 日志、告警、webhook | | **Plugin hooks** | `ctx.register_hook()` in plugin | CLI + Gateway | 工具拦截、监控、护栏 | | **Shell hooks** | `hooks:` block in config.yaml | CLI + Gateway | 脚本嵌入 | ### Gateway Hook 事件 | 事件 | 触发时机 | 上下文键 | |------|----------|----------| | `gateway:startup` | Gateway 进程启动 | `platforms` | | `session:start` | 新消息会话创建 | `platform`, `user_id`, `session_id` | | `session:end` | 会话结束 (reset 前) | `platform`, `user_id`, `session_key` | | `session:reset` | 用户运行 `/new` 或 `/reset` | `platform`, `user_id`, `session_key` | | `agent:start` | Agent 开始处理消息 | `platform`, `user_id`, `session_id`, `message` | | `agent:step` | 每个工具调用循环迭代 | `platform`, `user_id`, `session_id`, `iteration`, `tool_names` | | `agent:end` | Agent 完成处理 | `platform`, `user_id`, `session_id`, `message`, `response` | | `command:*` | 任何斜杠命令执行 | `platform`, `user_id`, `command`, `args` | ### BOOT.md 模式 在 `~/.hermes/BOOT.md` 中编写启动检查清单,gateway 启动时自动运行 --- ## 十七、MCP (Model Context Protocol) ### 配置方式 ```yaml mcp_servers: filesystem: command: "npx" args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/projects"] github: command: "npx" args: ["-y", "@modelcontextprotocol/server-github"] env: GITHUB_PERSONAL_ACCESS_TOKEN: "***" remote_api: url: "https://mcp.example.com/mcp" headers: Authorization: "Bearer token" ``` ### 两种 MCP 服务器 | 类型 | 说明 | 用例 | |------|------|------| | **Stdio** | 本地子进程, stdin/stdout 通信 | 本地资源, 低延迟 | | **HTTP** | 远程端点 | 远程 API | ### 特性 - 自动工具发现和注册 (启动时) - 支持 MCP resources 和 prompts - 每服务器工具过滤 - 目录: 一键安装 Nous 审核过的 MCP (`hermes mcp install n8n`) - 安装时工具选择清单 - 运行时 `${ENV_VAR}` 替换 ### 目录命令 ```bash hermes mcp # 交互式选择器 hermes mcp catalog # 纯文本列表 hermes mcp install n8n # 按名安装 hermes mcp configure linear # 更新工具选择 ``` --- ## 十八、CLI 命令参考 ### 全局选项 | 选项 | 说明 | |------|------| | `--profile `, `-p ` | 选择 profile | | `--resume `, `-r ` | 按 ID 或标题恢复会话 | | `--continue [name]`, `-c [name]` | 恢复最近会话 | | `--worktree`, `-w` | 隔离 git worktree 模式 | | `--yolo` | 跳过危险命令确认 | | `--tui` | 启动 TUI | | `--cli` | 强制经典 CLI | | `--ignore-user-config` | 忽略 config.yaml (仍加载 .env) | | `--ignore-rules` | 跳过 AGENTS.md/SOUL.md/内存/skills | ### 顶级命令 | 命令 | 用途 | |------|------| | `hermes chat` | 交互式或一次性聊天 | | `hermes model` | 选择 provider 和 model | | `hermes fallback` | 管理 fallback provider | | `hermes gateway` | 管理消息网关 | | `hermes proxy` | 本地 OpenAI 兼容代理 | | `hermes setup` | 设置向导 | | `hermes auth` | 管理凭据 | | `hermes send` | 一次性消息发送 (无 LLM) | | `hermes secrets` | 管理外部密钥源 | | `hermes migrate` | 诊断和重写 config.yaml | | `hermes cron` | 检查和触发 cron | | `hermes kanban` | 多 profile 协作看板 | | `hermes webhook` | 管理动态 webhook 订阅 | | `hermes hooks` | 检查、批准、移除脚本钩子 | | `hermes doctor` | 诊断 | | `hermes security audit` | 供应链审计 | | `hermes config` | 查看、编辑、迁移配置 | | `hermes skills` | 浏览、安装、发布、审计 skills | | `hermes bundles` | 技能捆绑管理 | | `hermes curator` | 后台 skill 维护 | | `hermes memory` | 配置外部内存 provider | | `hermes acp` | ACP 服务器运行 | | `hermes mcp` | MCP 服务器配置 | | `hermes plugins` | 插件管理 | | `hermes portal` | Nous Portal 状态 | | `hermes tools` | 工具配置 | | `hermes sessions` | 会话管理 | | `hermes insights` | token/成本/活动分析 | | `hermes profile` | profile 管理 | | `hermes update` | 更新 | | `hermes uninstall` | 卸载 | | `hermes -z ` | 纯一次性输出 (无 banner, 无 spinner) | ### `hermes chat` 选项 | 选项 | 说明 | |------|------| | `-q`, `--query "..."` | 一次性非交互式 prompt | | `-m`, `--model ` | 覆盖 model | | `-t`, `--toolsets ` | 启用逗号分隔的工具集 | | `--provider ` | 强制 provider | | `-s`, `--skills ` | 预加载 skills | | `-v`, `--verbose` | 详细输出 | | `-Q`, `--quiet` | 程序模式 (无 banner/spinner) | | `--image ` | 附加本地图片 | | `--max-turns ` | 最大迭代次数 (默认 90) | --- ## 十九、消息平台支持 (20+) | 平台 | 适配器位置 | |------|-----------| | Telegram | `gateway/platforms/` | | Discord | `gateway/platforms/` | | Slack | `gateway/platforms/` | | WhatsApp | `gateway/platforms/` | | Signal | `gateway/platforms/` | | Matrix | `gateway/platforms/` | | Mattermost | `gateway/platforms/` | | Email | `gateway/platforms/` | | SMS | `gateway/platforms/` | | DingTalk | `gateway/platforms/` | | Feishu | `gateway/platforms/` | | WeCom | `gateway/platforms/` | | WeChat | `gateway/platforms/` | | BlueBubbles | `gateway/platforms/` | | QQ Bot | `gateway/platforms/` | | Home Assistant | `gateway/platforms/` | | Webhook | `gateway/platforms/` | | API Server | `gateway/platforms/` | | Yuanbao | `gateway/platforms/` | | Microsoft Teams | `gateway/platforms/` | --- ## 二十、环境变量参考 ### LLM 提供方 (完整列表已在第三节) 核心环境变量: - `HERMES_HOME` — 覆盖配置目录 (默认 `~/.hermes`) - `HERMES_MODEL` — 进程级 model 覆盖 - `HERMES_TIMEZONE` — IANA 时区覆盖 - `HERMES_PREFILL_MESSAGES_FILE` — prefill 消息 JSON 文件路径 ### 工具 API | 变量 | 服务 | |------|------| | `PARALLEL_API_KEY` | AI-native web search (parallel.ai) | | `FIRECRAWL_API_KEY` | Web scraping + cloud browser (firecrawl.dev) | | `TAVILY_API_KEY` | AI-native web search (tavily.com) | | `SEARXNG_URL` | 免费自托管搜索 (SearXNG) | | `EXA_API_KEY` | AI-native web search (exa.ai) | | `BROWSERBASE_API_KEY` | 浏览器自动化 (browserbase.com) | | `BROWSER_USE_API_KEY` | Browser Use cloud browser | | `FAL_KEY` | 图像生成 (fal.ai) | | `GROQ_API_KEY` | Groq Whisper STT | | `ELEVENLABS_API_KEY` | ElevenLabs TTS | | `GITHUB_TOKEN` | Skills Hub 访问 | ### Terminal 后端 | 变量 | 说明 | |------|------| | `TERMINAL_ENV` | 后端: local/docker/ssh/singularity/modal/daytona | | `HERMES_DOCKER_BINARY` | Docker 二进制覆盖 (如 podman) | | `TERMINAL_DOCKER_IMAGE` | Docker 镜像 | | `TERMINAL_DOCKER_FORWARD_ENV` | 转发到 Docker 的环境变量列表 | | `TERMINAL_DOCKER_VOLUMES` | 额外 volume 挂载 | | `TERMINAL_TIMEOUT` | 命令超时 (秒) | | `TERMINAL_LIFETIME_SECONDS` | 终端会话最大生命周期 | | `SUDO_PASSWORD` | 免交互 sudo | --- ## 二十一、常见故障 | 症状 | 可能原因 | 修复 | |------|----------|------| | Hermes 打开但返回空回复 | Provider auth 或 model 选择错误 | 运行 `hermes model` 重新配置 | | 自定义端点返回垃圾 | 错误的 base URL/model 名/不兼容 | 先在其他客户端验证 | | Gateway 启动但无人可发消息 | Bot token/allowlist/平台设置不完整 | 重新运行 `hermes gateway setup` | | `hermes --continue` 找不到旧会话 | 切换了 profile 或会话未保存 | 检查 `hermes sessions list` | | 模型不可用 / 异常的 fallback | Provider routing 或 fallback 太激进 | 稳定基础 provider 前关闭 routing | ### 恢复工具包 1. `hermes doctor` 2. `hermes model` 3. `hermes setup` 4. `hermes sessions list` 5. `hermes --continue` 6. `hermes gateway status` --- ## 二十二、Webhook 支持 ### 配置方式 在 messaging 平台配置中设置 webhook 端点,Hermes 可接收 webhook 事件并触发 agent 处理。 ```yaml # config.yaml messaging 配置中的 webhook 部分 ``` ### 动态 Webhook 订阅 `hermes webhook` 命令管理动态 webhook 订阅,用于事件驱动激活。 ### 特性 - 可作为 webhook 接收端 (接收外部 HTTP 请求并触发 agent) - 通过 gateway 的 webhook 适配器对外暴露端点 - 支持消息投递到配置的平台目标 --- ## 二十三、集成能力 ### API Server - 暴露 OpenAI 兼容的 HTTP 端点 - 可连接 Open WebUI, LobeChat, LibreChat 等 ### ACP (Agent Communication Protocol) - 在 VS Code, Zed, JetBrains 中使用 Hermes - 聊天、工具活动、文件 diff、终端命令在编辑器中渲染 ### Python Library ```python from run_agent import AIAgent agent = AIAgent(model="anthropic/claude-opus-4.7") response = agent.chat("Explain quantum computing briefly") ``` ### Batch Processing - 批量运行 Hermes agent - 生成结构化 ShareGPT 格式轨迹数据 - 用于训练数据生成或评估 --- ## 二十四、Plugin 系统 ### 发现源 - `~/.hermes/plugins/` (用户) - `.hermes/plugins/` (项目) - pip entry points ### 插件类型 | 类型 | 说明 | 选择方式 | |------|------|----------| | 通用插件 | 工具、钩子 | 可多个同时激活 | | 内存提供方 | 跨会话用户建模 | 单一选择 | | 上下文引擎 | 替代上下文管理 | 单一选择 | ### 内存提供方插件 - Honcho - OpenViking - Mem0 - Hindsight - Holographic - RetainDB - ByteRover - Supermemory --- ## 二十五、安全特性 ### 容器安全 - 只读根文件系统 (Docker) - 所有 Linux capabilities 已删除 - 无特权提升 - PID 限制 (256 进程) - 完整命名空间隔离 - 持久 workspace 通过 volumes 实现 ### 危险命令检测 `tools/approval.py` 检测危险命令,需要用户确认 (或 `--yolo` 模式跳过) ### 环境变量传递 - skill 声明的 `required_environment_variables` 自动传递到沙箱 - 非 skill 变量通过 `terminal.env_passthrough` 配置 --- ## 二十六、测试 - **数量**: ~25,000 个测试 - **文件数**: ~1,250 个测试文件 - **框架**: Pytest - **部署**: `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 ``` ### 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 ``` ### Cron 作业 ``` 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 ``` --- *提取完毕。共覆盖 61,520 行文档中的全部核心章节。*