{"id":"8fd8846f-1fc4-48f3-9c6b-204854462623","entityType":"agent","slug":"clawhub-wihy-hermes-agent-v2","name":"Hermes Agent Skill","canonicalUrl":"https://www.xpersona.co/agent/clawhub-wihy-hermes-agent-v2","canonicalPath":"/agent/clawhub-wihy-hermes-agent-v2","generatedAt":"2026-10-09T19:36:16.936Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":null},"description":"NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation... Skill: Hermes Agent Skill Owner: wihy Summary: NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation... Tags: agent:2.0.0, ai:2.0.0, delegation:2.0.0, hermes:2.0.0, latest:2.1.1, mcp:2.0.0, memory:2.0.0, self-improving:2.0.0 Version history: v2.1.1 | 2026-04-12T01:49:58.074Z | user - Major simplification: Documenta","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 4.5K downloads reported by the source. Last updated 10/9/2026.","installCommand":"clawhub skill install s17d3vb11h4b17n7dsra7epmv983hvy0:hermes-agent-v2","sourceUrl":"https://clawhub.ai/wihy/hermes-agent-v2","homepage":"https://clawhub.ai/wihy/skills/hermes-agent-v2","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/wihy/hermes-agent-v2","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/wihy/skills/hermes-agent-v2","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":56,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation..."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":null},"stars":null,"forks":null,"downloads":4523,"packageName":null,"latestVersion":"2.1.1","tractionLabel":"4.5K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":null},"lastUpdatedAt":"2026-10-09T05:15:48.051Z","lastCrawledAt":"2026-10-09T05:15:48.051Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-10T05:15:48.051Z","lastVerifiedAt":null,"highlights":[{"version":"2.1.1","createdAt":"2026-04-12T01:49:58.074Z","changelog":"- Major simplification: Documentation and scripts have been removed; only core hermes CLI integration remains. - All helper scripts and reference guides deleted; only essential usage and installation instructions are included. - Security and file access descriptions clarified: skill only calls hermes CLI and accesses ~/.hermes/. - LICENSE file added; documentation now focuses on basic usage and configuration.","fileCount":3,"zipByteSize":2407},{"version":"2.1.0","createdAt":"2026-04-12T01:46:24.736Z","changelog":"1、SKILL.md 添加 security 字段，明确文件访问范围 2、error_callback 改为仅输出到 stderr","fileCount":11,"zipByteSize":48109},{"version":"2.0.0","createdAt":"2026-04-12T01:26:23.386Z","changelog":"**Hermes Agent v2.0.0 – Major upgrade to portable, scriptable integration** - Rebuilt skill as a fully portable, script-driven Hermes Agent integration: no hardcoded paths, easy migration between Claw/WorkBuddy instances - Added detailed Chinese-language setup/configuration guide with automated install (`install_hermes.sh`), API key setup, and troubleshooting - Introduced wrapper and delegate CLI scripts for unified command handling and subagent delegation - Provided comprehensive CLI reference, best practices, and cost guidance - File structure and documentation now focused on CLI/multi-platform workflows; legacy workspace seeding/memory/promotion files removed","fileCount":11,"zipByteSize":48347}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17d3vb11h4b17n7dsra7epmv983hvy0:hermes-agent-v2","setupComplexity":"low","setupSteps":["Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.","Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-09T19:36:16.934Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-wihy-hermes-agent-v2/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":null},"readme":"Skill: Hermes Agent Skill\n\nOwner: wihy\n\nSummary: NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation...\n\nTags: agent:2.0.0, ai:2.0.0, delegation:2.0.0, hermes:2.0.0, latest:2.1.1, mcp:2.0.0, memory:2.0.0, self-improving:2.0.0\n\nVersion history:\n\nv2.1.1 | 2026-04-12T01:49:58.074Z | user\n\n- Major simplification: Documentation and scripts have been removed; only core hermes CLI integration remains.\n- All helper scripts and reference guides deleted; only essential usage and installation instructions are included.\n- Security and file access descriptions clarified: skill only calls hermes CLI and accesses ~/.hermes/.\n- LICENSE file added; documentation now focuses on basic usage and configuration.\n\nv2.1.0 | 2026-04-12T01:46:24.736Z | user\n\n1、SKILL.md 添加 security 字段，明确文件访问范围\n2、error_callback 改为仅输出到 stderr\n\nv2.0.0 | 2026-04-12T01:26:23.386Z | user\n\n**Hermes Agent v2.0.0 – Major upgrade to portable, scriptable integration**\n\n- Rebuilt skill as a fully portable, script-driven Hermes Agent integration: no hardcoded paths, easy migration between Claw/WorkBuddy instances\n- Added detailed Chinese-language setup/configuration guide with automated install (`install_hermes.sh`), API key setup, and troubleshooting\n- Introduced wrapper and delegate CLI scripts for unified command handling and subagent delegation\n- Provided comprehensive CLI reference, best practices, and cost guidance\n- File structure and documentation now focused on CLI/multi-platform workflows; legacy workspace seeding/memory/promotion files removed\n\nArchive index:\n\nArchive v2.1.1: 3 files, 2407 bytes\n\nFiles: _meta.json (134b), skill-card.md (2410b), SKILL.md (1782b)\n\nFile v2.1.1:SKILL.md\n\n---\nname: hermes-agent-v2\ndescription: |\n  NousResearch Hermes Agent CLI integration. Core capabilities:\n  - Self-improving skill system\n  - Persistent memory (FTS5 + LLM summaries)\n  - Sub-agent delegation\n  - MCP integration\n  - Browser automation\n  - Code execution\n\ntriggers:\n  - \"使用 hermes\"\n  - \"调用 hermes\"\n  - \"hermes agent\"\n  - \"hermes run\"\n  - \"hermes delegate\"\n  - \"hermes memory\"\n  - \"hermes skills\"\n\ncategory: ai-agents\nversion: 2.1.0\nrequires_approval: false\nsecurity: |\n  This skill only calls the hermes CLI command. It does not read, write, or modify\n  any files outside of standard hermes operations (~/.hermes/).\n  Hermes Agent source: https://github.com/NousResearch/hermes-agent\n---\n\n# Hermes Agent Skill\n\nCall [NousResearch Hermes Agent](https://github.com/NousResearch/hermes-agent) via CLI.\n\n## Prerequisites\n\nHermes CLI must be installed. See https://github.com/NousResearch/hermes-agent for installation.\n\n## Usage\n\n### Quick Q&A\n\n```bash\nhermes run \"your question\" --non-interactive --no-stream\n```\n\n### With Context\n\n```bash\nhermes run \"question\" --context-file ./ctx.md --non-interactive\n```\n\n### Sub-agent Delegation\n\n```bash\nhermes run \"use delegate_task to: research topic\" --non-interactive --no-stream\n```\n\n### Memory\n\n```bash\nhermes memory search \"keyword\"\nhermes memory notes list\nhermes memory notes add \"note content\"\n```\n\n### Skills\n\n```bash\nhermes skills list\nhermes skills create \"name\" --description \"desc\"\n```\n\n### Status\n\n```bash\nhermes status\nhermes doctor\n```\n\n## Configuration\n\nEdit `~/.hermes/.env` to set your LLM provider key.\nEdit `~/.hermes/config.yaml` to set model and provider.\n\n## File Access Scope\n\nThis skill only invokes hermes CLI commands. No direct file operations.\nHermes Agent operates within `~/.hermes/` only.\n\nFile v2.1.1:_meta.json\n\n{\n  \"ownerId\": \"kn75neczzxsdbx7djhh1kn544182nsbj\",\n  \"slug\": \"hermes-agent-v2\",\n  \"version\": \"2.1.1\",\n  \"publishedAt\": 1775958598074\n}\n\nFile v2.1.1:skill-card.md\n\n## Description:\n\nHermes Agent Skill integrates the NousResearch Hermes Agent CLI for agent workflows including persistent memory, sub-agent delegation, MCP integration, browser automation, and code execution.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[wihy](https://clawhub.ai/user/wihy)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and agent operators use this skill to call Hermes CLI from an agent session for Q&A, context-aware runs, delegation, memory operations, skill management, status checks, and configuration guidance.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Hermes CLI and its configured model provider may process prompts, context files, and delegated tasks outside this skill.\n\nMitigation: Use this skill only with a trusted Hermes CLI installation and trusted model provider configuration; avoid passing sensitive files with --context-file unless that processing is intended.\n\nRisk: Memory notes, created skills, and ~/.hermes configuration changes can persist beyond a single run.\n\nMitigation: Periodically review Hermes memory notes, created skills, and ~/.hermes configuration for stale, sensitive, or unexpected state.\n\nRisk: Broad Hermes agent capabilities, including delegation, browser automation, code execution, and MCP integration, may operate without clear approval boundaries.\n\nMitigation: Run Hermes in controlled workspaces, review commands before execution, and apply local sandbox or approval policies where available.\n\n## Reference(s):\n\n- [ClawHub Hermes Agent Skill](https://clawhub.ai/wihy/skills/hermes-agent-v2)\n- [NousResearch Hermes Agent documentation](https://github.com/NousResearch/hermes-agent)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown with inline bash code blocks]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May reference local Hermes configuration and persistent Hermes memory state.]\n\n## Skill Version(s):\n\n2.1.1 (source: server release metadata; artifact frontmatter and _meta.json list 2.1.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nArchive v2.1.0: 11 files, 48109 bytes\n\nFiles: _meta.json (134b), README.md (3046b), references/cli-commands.md (10824b), references/config-guide.md (13818b), references/mcp-integration.md (15176b), references/plugin-development.md (20512b), references/self-improving-integration.md (9223b), scripts/hermes_delegate.sh (16785b), scripts/hermes_wrapper.sh (15436b), scripts/install_hermes.sh (13310b), SKILL.md (9574b)\n\nFile v2.1.0:SKILL.md\n\n---\nname: hermes-agent\ndescription: |\n  NousResearch Hermes Agent 通用集成 Skill。通过 CLI 调用 Hermes Agent 的核心能力：\n  - 🚀 自改进技能系统（从任务中自动创建可复用技能）\n  - 🧠 持久化记忆（FTS5全文搜索 + LLM摘要）\n  - 🤖 子代理委托（任务隔离和并行处理）\n  - 🔌 MCP 双向集成\n  - 🌐 浏览器自动化\n  - 💻 代码执行\n  - 🔍 网页研究\n  - 📦 完全可移植，支持任意 Claw/WorkBuddy 实例一键安装\n\ntriggers:\n  - \"使用 hermes\"\n  - \"调用 hermes\"\n  - \"hermes agent\"\n  - \"子代理委托\"\n  - \"hermes run\"\n  - \"hermes delegate\"\n  - \"hermes memory\"\n  - \"hermes skills\"\n  - \"让 hermes 帮我\"\n  - \"用 hermes 分析\"\n  - \"安装 hermes\"\n\ncategory: ai-agents\nversion: 2.1.0\nrequires_approval: false\ncost_awareness: |\n  ⚠️ 每次 `hermes run` 调用都会产生 LLM Token 消耗。\n  - 单轮简单问答：约 $0.001-0.01\n  - 复杂任务（含子代理）：约 $0.05-0.50\n  - 建议对复杂任务先评估成本，或限制工具集减少调用次数\nsecurity: |\n  本 Skill 的文件和目录访问范围：\n  - 仅写入 ~/.local/hermes-agent/ (Hermes 源码) 和 ~/.hermes/ (配置)\n  - 不读取或写入任何其他代理软件的目录\n  - 不建立网络服务器或开放端口\n  - API Key 仅存储在用户本地的 ~/.hermes/.env 中\n  - 源码来自 NousResearch 官方仓库: https://github.com/NousResearch/hermes-agent\n  - 错误信息仅输出到 stderr，不写入外部文件\n---\n\n# Hermes Agent Skill v2.1\n\n## 概述\n\n本 Skill 封装了 [NousResearch Hermes Agent](https://github.com/NousResearch/hermes-agent) 的 CLI 调用能力，让 WorkBuddy/Claw 可以通过 Shell 命令利用 Hermes 的核心功能。\n\n**v2.1 改进：完全可移植，安全优化，无跨目录写入，通过 ClawHub 安全扫描。**\n\n---\n\n## 首次安装\n\n### 一键安装（推荐）\n\n当检测到 Hermes 未安装时，运行：\n\n```bash\n# 安装 Hermes Agent（自动克隆、创建虚拟环境、创建 CLI 入口）\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n\n# 或自定义安装目录\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh --prefix ~/custom/path\n```\n\n安装脚本会自动：\n1. ✅ 检测 Python 3.11+ 环境\n2. ✅ 克隆 Hermes Agent 源码\n3. ✅ 创建 Python 虚拟环境并安装依赖\n4. ✅ 创建 `~/.local/bin/hermes` CLI 入口\n5. ✅ 初始化 `~/.hermes/` 配置目录\n6. ✅ 生成默认 `.env` 配置模板\n\n### 安装后配置 API Key\n\n```bash\n# 编辑配置文件，填入你的 API Key\nnano ~/.hermes/.env\n```\n\n可选提供商（任选其一）：\n```bash\n# 智谱 AI（推荐国内用户）\nGLM_API_KEY=your-key-here\n\n# OpenRouter（支持多种模型）\nOPENROUTER_API_KEY=sk-or-v1-your-key-here\n\n# Anthropic\nANTHROPIC_API_KEY=sk-ant-your-key-here\n\n# OpenAI\nOPENAI_API_KEY=sk-your-key-here\n```\n\n### 验证安装\n\n```bash\n# 确认 PATH 包含 hermes\nexport PATH=\"$HOME/.local/bin:$PATH\"\nhermes --version\n\n# 运行诊断\nhermes doctor\n```\n\n---\n\n## 迁移到其他 Claw 实例\n\n将整个 Skill 目录复制到目标实例即可：\n\n```bash\n# 在目标实例上执行：\ncp -r /path/to/hermes-agent ~/.workbuddy/skills/hermes-agent\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n# 然后配置 API Key\n```\n\n---\n\n## 核心工作流\n\n### 1. 调用模式速查\n\n| 场景 | 命令 | 说明 |\n|------|------|------|\n| **快速问答** | `hermes run \"问题\" --non-interactive --no-stream` | 最简调用 |\n| **带上下文** | `hermes run \"问题\" --context-file ./ctx.md --non-interactive` | 注入项目上下文 |\n| **子代理委托** | 使用 `scripts/hermes_delegate.sh` | 复杂任务分解 |\n| **技能查询** | `hermes skills list` | 查看已学技能 |\n| **记忆搜索** | `hermes memory search \"关键词\"` | 检索历史知识 |\n| **状态检查** | `hermes status` 或 `hermes doctor` | 诊断安装状态 |\n\n### 2. CLI 命令完整参考\n\n#### 基础命令\n\n```bash\n# 启动交互式对话\nhermes\n\n# 单轮执行（WorkBuddy 集成首选）\nhermes run \"prompt\" [选项]\n\n# 非交互模式选项\n--non-interactive    # 关闭交互式 TUI（必需）\n--no-stream          # 禁用流式输出，返回完整结果\n--context-file PATH  # 注入上下文文件\n--toolset NAME       # 限制使用的工具集\n--model MODEL        # 指定模型\n--timeout SECONDS    # 超时时间（默认300秒）\n```\n\n#### 子代理委托\n\n```bash\n# 通过 wrapper 脚本调用（推荐）\n./scripts/hermes_delegate.sh \\\n  --task \"分析竞品A和B的产品特性\" \\\n  --tools \"web_search,browser,file_write\" \\\n  --timeout 300 \\\n  --output ./result.md\n\n# 直接在 hermes run 中使用 delegate_task 工具\nhermes run '使用delegate_task工具，任务是：分析XXX，工具限制：web_search,browser' \\\n  --non-interactive --no-stream\n```\n\n#### 记忆管理\n\n```bash\n# 搜索历史记忆\nhermes memory search \"关键词\"\n\n# 查看所有笔记\nhermes memory notes list\n\n# 添加手动笔记\nhermes memory notes add \"重要发现：...\"\n\n# 导出/导入记忆\nhermes memory export ./backup/\nhermes memory import ./backup/\n```\n\n#### 技能管理\n\n```bash\nhermes skills list                           # 列出所有技能\nhermes skills create my-skill --description \"描述\"  # 创建新技能\nhermes skills edit my-skill                  # 编辑技能\nhermes skills remove my-skill                # 删除技能\n```\n\n#### 插件管理\n\n```bash\nhermes plugins list                    # 列出插件\nhermes plugins install user/repo       # 安装插件\nhermes plugins enable/disable/update/remove plugin-name\n```\n\n#### 定时任务 (Cron)\n\n```bash\nhermes cron list                       # 列出定时任务\nhermes cron add --name \"日报\" --cron \"0 9 * * *\" --message \"生成总结\"\nhermes cron pause/resume/remove TASK_ID\n```\n\n#### MCP 集成\n\n```bash\nhermes mcp serve --port 8080           # 启动 MCP Server\nhermes mcp connect <server-config>     # 连接外部 MCP 服务\n```\n\n---\n\n## Wrapper 脚本\n\n### scripts/hermes_wrapper.sh\n\n统一的 CLI 封装脚本，提供 JSON 格式化输出和错误处理：\n\n```bash\n./scripts/hermes_wrapper.sh [命令] [参数...]\n\n# 示例\n./scripts/hermes_wrapper.sh run \"分析内容\" --timeout 60\n./scripts/hermes_wrapper.sh memory search \"关键词\"\n./scripts/hermes_wrapper.sh status\n```\n\n**输出格式**：JSON（包含 `success`, `output`, `error`, `duration_ms` 字段）\n\n### scripts/hermes_delegate.sh\n\n子代理委托专用脚本：\n\n```bash\n./scripts/hermes_delegate.sh --task \"任务描述\" [选项]\n\n# 可选选项\n--tools \"tool1,tool2\"      # 限制可用工具集\n--timeout 300              # 超时时间（秒）\n--output ./result.md        # 输出文件路径\n--max-concurrent 3         # 最大并发数（默认3）\n--context-file ./ctx.md     # 额外上下文文件\n-v                         # 详细输出\n```\n\n### scripts/install_hermes.sh\n\n一键安装脚本（详见上方「首次安装」章节）：\n\n```bash\nbash scripts/install_hermes.sh [--skip-deps] [--prefix DIR]\n```\n\n---\n\n## 模型配置\n\n运行交互式配置向导：\n\n```bash\nhermes model\n```\n\n或直接编辑 `~/.hermes/config.yaml`：\n\n```yaml\nmodel:\n  provider: zai           # 可选: openrouter, anthropic, openai, zai, gemini 等\n  default: \"glm-5\"        # 默认模型\n  base_url: \"https://api.z.ai/api/paas/v4\"  # 自定义 API 地址\n```\n\n**支持的提供商**：openrouter, anthropic, openai, gemini, zai, kimi-coding, nous, custom\n\n---\n\n## 最佳实践\n\n### ✅ 推荐做法\n\n1. **始终使用 `--non-interactive --no-stream`**：避免 TUI 阻塞\n2. **设置合理的超时时间**：简单任务 60s，复杂任务 300s\n3. **限制工具集**：用 `--toolset` 减少 Token 消耗\n4. **使用上下文文件**：将大段背景信息放入文件，而非 prompt 中\n5. **错误重试机制**：网络问题时自动重试 1-2 次\n\n### ⚠️ 注意事项\n\n1. **Token 成本**：每次调用都有成本\n2. **并发限制**：最多 3 个并发子代理\n3. **超时保护**：长时间运行的任务必须设置 timeout\n4. **API Key 安全**：不要在 Skill 文件中硬编码密钥\n5. **Python 版本**：确保使用 Python 3.11+\n\n---\n\n## 故障排除\n\n| 问题 | 解决方案 |\n|------|----------|\n| `command not found: hermes` | 运行 `export PATH=\"$HOME/.local/bin:$PATH\"` 或重新执行 `install_hermes.sh` |\n| `TypeError: unsupported operand` | 确保 Python 3.11+ |\n| API Key 错误 | 检查 `~/.hermes/.env` 配置 |\n| 连接超时 | 检查网络，或更换 LLM 提供商 |\n| 子代理失败 | 减少 `--max-concurrent` 或增加 `--timeout` |\n| 安装脚本失败 | 运行 `hermes doctor` 诊断 |\n\n---\n\n## 文件结构\n\n```\nhermes-agent/\n├── SKILL.md                    # 本文件（Skill 说明文档）\n├── _meta.json                  # Skill 元数据（可移植性声明）\n├── scripts/\n│   ├── install_hermes.sh       # 一键安装脚本（通用）\n│   ├── hermes_wrapper.sh       # 统一 CLI 封装（动态路径检测）\n│   └── hermes_delegate.sh      # 子代理委托脚本（动态路径检测）\n└── references/                 # 参考文档\n```\n\n---\n\n## 更新日志\n\n- **v2.1.0** (2026-04-12): 安全优化版 — 移除所有跨目录写入行为，精简凭证模板，通过 ClawHub 安全扫描\n- **v2.0.0** (2026-04-12): 完全可移植版 — 移除所有硬编码路径，添加一键安装脚本，支持任意 Claw 实例迁移\n- **v1.0.0** (2026-04-11): 初始版本，支持基础 CLI 调用、子代理委托、记忆/技能管理\n\nFile v2.1.0:README.md\n\n# Hermes Agent Skill 🏥\n\n> 通用可移植的 Hermes Agent 集成 Skill，适用于 WorkBuddy / Claude Code / Cursor 等 AI Agent 平台。\n\n[![Version](https://img.shields.io/badge/version-2.0.0-blue)]()\n[![License](https://img.shields.io/badge/license-MIT-green)]()\n[![Hermes](https://img.shields.io/badge/Hermes-v0.8.0-purple)]()\n\n## ✨ 功能特性\n\n- 🚀 **自改进技能系统** — 从任务中自动创建可复用技能\n- 🧠 **持久化记忆** — FTS5 全文搜索 + LLM 摘要\n- 🤖 **子代理委托** — 任务隔离和并行处理\n- 🔌 **MCP 双向集成** — Model Context Protocol 支持\n- 🌐 **浏览器自动化** — Web 页面交互\n- 💻 **代码执行** — 沙盒内安全执行\n- 🔍 **网页研究** — 信息检索与分析\n\n## 📦 安装\n\n### 方式一：一键安装（推荐）\n\n```bash\nnpx skills add chunhaixu/hermes-agent-skill@hermes-agent -g -y\n```\n\n### 方式二：手动安装\n\n```bash\n# 1. 克隆仓库\ngit clone https://github.com/chunhaixu/hermes-agent-skill.git\n\n# 2. 复制到 Skill 目录\ncp -r hermes-agent-skill ~/.workbuddy/skills/hermes-agent\n\n# 3. 运行安装脚本\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n\n# 4. 配置 API Key\nnano ~/.hermes/.env\n```\n\n## ⚙️ 配置\n\n### API Key 配置\n\n编辑 `~/.hermes/.env`，添加你的 LLM 提供商密钥：\n\n```bash\n# 智谱 AI（推荐）\nGLM_API_KEY=your_key_here\n\n# 或 OpenRouter\nOPENROUTER_API_KEY=your_key_here\n\n# 或 Anthropic\nANTHROPIC_API_KEY=your_key_here\n```\n\n### 模型配置\n\n编辑 `~/.hermes/config.yaml`：\n\n```yaml\nmodel:\n  default: \"glm-5\"          # 默认模型\n  provider: \"zai\"           # 提供商: zai / openrouter / anthropic / ...\n  base_url: \"https://api.z.ai/api/paas/v4\"\n```\n\n## 🔧 使用\n\n安装后，在 AI Agent 中使用以下触发词：\n\n| 触发词 | 说明 |\n|--------|------|\n| `使用 hermes` | 激活 Hermes Agent |\n| `hermes run \"任务\"` | 执行单轮任务 |\n| `hermes memory search \"关键词\"` | 搜索记忆 |\n| `hermes delegate \"复杂任务\"` | 子代理委托 |\n| `hermes skills list` | 查看已学技能 |\n\n## 🏗️ 项目结构\n\n```\nhermes-agent-skill/\n├── SKILL.md              # Skill 描述文件（Agent 自动加载）\n├── _meta.json            # 元数据（版本、依赖、触发词等）\n├── scripts/\n│   ├── install_hermes.sh    # 一键安装脚本\n│   ├── hermes_wrapper.sh    # CLI 统一封装\n│   └── hermes_delegate.sh   # 子代理委托脚本\n└── references/\n    ├── cli-commands.md           # CLI 命令参考\n    ├── config-guide.md           # 配置指南\n    ├── mcp-integration.md        # MCP 集成\n    ├── plugin-development.md     # 插件开发\n    └── self-improving-integration.md  # 自改进系统\n```\n\n## 🔗 相关链接\n\n- [Hermes Agent 官方仓库](https://github.com/NousResearch/hermes-agent)\n- [Skills.sh - Agent Skill 生态](https://skills.sh/)\n- [智谱 AI 开放平台](https://open.bigmodel.cn)\n\n## 📄 License\n\nMIT License\n\nFile v2.1.0:_meta.json\n\n{\n  \"ownerId\": \"kn75neczzxsdbx7djhh1kn544182nsbj\",\n  \"slug\": \"hermes-agent-v2\",\n  \"version\": \"2.1.0\",\n  \"publishedAt\": 1775958384736\n}\n\nFile v2.1.0:references/cli-commands.md\n\n# Hermes Agent CLI 完整命令手册\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [基础命令](#基础命令)\n2. [执行模式](#执行模式)\n3. [工具管理](#工具管理)\n4. [记忆系统](#记忆系统)\n5. [技能管理](#技能管理)\n6. [插件系统](#插件系统)\n7. [消息网关](#消息网关)\n8. [定时任务](#定时任务)\n9. [MCP 集成](#mcp-集成)\n10. [诊断与调试](#诊断与调试)\n\n---\n\n## 基础命令\n\n### 启动交互式会话\n\n```bash\nhermes\n```\n\n启动 TUI（终端用户界面）交互式对话。\n\n**快捷键**:\n- `Ctrl+C` - 中断当前生成\n- `Ctrl+D` - 退出\n- `Tab` - 自动补全\n- `↑/↓` - 历史记录\n\n### 查看版本信息\n\n```bash\nhermes --version\nhermes -v\n\n# 输出示例:\n# Hermes Agent v0.8.0 (2026.4.8)\n# Project: /path/to/hermes-agent\n# Python: 3.11.15\n# OpenAI SDK: 2.31.0\n```\n\n### 显示帮助信息\n\n```bash\nhermes --help\nhermes help <command>\n```\n\n---\n\n## 执行模式\n\n### 单轮执行 (run)\n\n```bash\nhermes run \"你的提示词\" [选项]\n```\n\n**核心选项**:\n\n| 选项 | 简写 | 默认值 | 说明 |\n|------|------|--------|------|\n| `--non-interactive` | 无 | false | 关闭 TUI，适合脚本调用 |\n| `--no-stream` | 无 | false | 禁用流式输出，返回完整结果 |\n| `--context-file` | `-c` | null | 注入上下文文件路径 |\n| `--toolset` | `-t` | null | 限制使用的工具集名称 |\n| `--model` | `-m` | 配置默认值 | 指定模型（覆盖配置） |\n| `--provider` | 无 | 配置默认值 | 指定 LLM 提供商 |\n| `--timeout` | 无 | 300 | 超时时间（秒） |\n| `--max-tokens` | 无 | 配置默认值 | 最大输出 Token 数 |\n| `--temperature` | 无 | 配置默认值 | 温度参数 (0.0-2.0) |\n\n**使用示例**:\n\n```bash\n# 最简单的单轮调用\nhermes run \"什么是机器学习？\" --non-interactive --no-stream\n\n# 带上下文文件\nhermes run \"分析这个项目的架构\" \\\n  --context-file ./AGENTS.md \\\n  --non-interactive --no-stream\n\n# 限制工具集\nhermes run \"搜索最新的 React 文档\" \\\n  --toolset web_search \\\n  --non-interactive --no-stream\n\n# 指定模型和超时\nhermes run \"写一个排序算法\" \\\n  --model gpt-4o \\\n  --temperature 0.2 \\\n  --timeout 60 \\\n  --non-interactive --no-stream\n```\n\n---\n\n## 工具管理\n\n### 列出所有可用工具\n\n```bash\nhermes tools list\nhermes tools list --all    # 包括未启用的\n```\n\n### 启用/禁用工具集\n\n```bash\n# 列出可用工具集\nhermes toolsets\n\n# 启用特定工具集\nhermes tools enable web_search browser file_operations\n\n# 禁用特定工具集\nhermes tools disable code_execution terminal\n```\n\n### 内置工具列表\n\n| 工具集 | 包含工具 | 用途 |\n|--------|----------|------|\n| `web_search` | search_web, firecrawl_scrape, brave_search, searxng_search | 网页搜索和抓取 |\n| `browser` | browser_navigate, browser_click, browser_type, browser_screenshot, browser_extract | 浏览器自动化 |\n| `file_operations` | read_file, write_file, edit_file, glob_files, list_directory | 文件读写操作 |\n| `terminal` | execute_command, bash, shell | 终端命令执行 |\n| `memory` | memory_search, memory_add_note, memory_list_notes | 记忆系统访问 |\n| `code_execution` | execute_code | 代码执行沙盒 |\n| `delegation` | delegate_task | 子代理委托 |\n| `skills` | skills_list, skills_create, skills_edit, skills_remove | 技能管理 |\n| `image_generation` | generate_image, upscale_image | AI 图像生成 |\n| `voice` | text_to_speech, transcribe_audio | 语音合成与识别 |\n\n---\n\n## 记忆系统\n\n### 搜索记忆\n\n```bash\nhermes memory search \"关键词\"\nhermes memory search \"用户偏好设置\" --limit 10\n```\n\n### 笔记管理\n\n```bash\n# 列出所有笔记\nhermes memory notes list\n\n# 添加新笔记\nhermes memory notes add \"重要发现：XXX\"\n\n# 搜索笔记内容\nhermes memory notes search \"查询内容\"\n```\n\n### 导入导出\n\n```bash\n# 导出所有记忆数据\nhermes memory export ./backup/\n\n# 从备份导入\nhermes memory import ./backup/\n```\n\n### 记忆后端切换\n\n```bash\n# 查看当前记忆后端\nhermes memory status\n\n# 切换到 Honcho 后端\nhermes memory setup honcho\n\n# 使用内置后端\nhermes memory setup built-in\n```\n\n**支持的记忆后端**:\n\n| 后端 | 特点 |\n|------|------|\n| `built-in` | 默认，SQLite + FTS5 全文搜索 |\n| `honcho` | AI 原生记忆，方言建模 |\n| `mem0` | 开源记忆服务 |\n| `openviking` | 高级向量检索 |\n| `hindsight` | 时间线记忆 |\n| `holographic` | 全息记忆系统 |\n| `retaindb` | 企业级记忆存储 |\n| `byte-rover` | 轻量级本地记忆 |\n\n---\n\n## 技能管理\n\n### 列出技能\n\n```bash\nhermes skills list\nhermes skills ls           # 短形式\n\n# 查看技能详情\nhermes skills show skill-name\n```\n\n### 创建技能\n\n```bash\n# 交互式创建\nhermes skills create my-skill\n\n# 带描述创建\nhermes skills create research-methodology \\\n  --description \"系统性网页研究方法论\"\n\n# 从模板创建\nhermes skills create code-review --template default\n```\n\n### 编辑技能\n\n```bash\nhermes skills edit my-skill\n# 打开默认编辑器编辑技能 Markdown 文件\n```\n\n### 删除技能\n\n```bash\nhermes skills remove my-skill\nhermes skills rm old-skill   # 短形式\n```\n\n### 技能格式规范\n\n每个技能是一个 Markdown 文件，位于 `~/.hermes/skills/<skill-name>/skill.md`：\n\n```markdown\n---\nname: my-skill\ndescription: 技能描述\ntriggers:\n  - \"触发词1\"\n  - \"触发词2\"\ntags:\n  - category1\n  - category2\n---\n\n# 技能名称\n\n## 步骤\n1. 第一步说明\n2. 第二步说明\n\n## 最佳实践\n- 注意事项\n- 推荐做法\n```\n\n---\n\n## 插件系统\n\n### 插件管理\n\n```bash\n# 列出已安装插件\nhermes plugins list\nhermes plugins ls\n\n# 安装插件（从 Git）\nhermes plugins install owner/repo\nhermes plugins install https://github.com/owner/repo.git\n\n# 更新插件\nhermes plugins update plugin-name\nhermes plugins update --all    # 更新所有\n\n# 卸载插件\nhermes plugins remove plugin-name\nhermes plugins rm plugin-name\n\n# 启用/禁用插件（保留安装但不加载）\nhermes plugins enable plugin-name\nhermes plugins disable plugin-name\n```\n\n### 插件类型\n\n```bash\n# 列出通用插件\nhermes plugins list --type general\n\n# 列出内存提供者\nhermes plugins list --type memory\n\n# 列出上下文引擎\nhermes plugins list --type context_engine\n```\n\n### 插件开发\n\n详见 [plugin-development.md](./plugin-development.md)\n\n---\n\n## 消息网关\n\n### 网关管理\n\n```bash\n# 设置向导\nhermes gateway setup\n\n# 列出已配置的网关\nhermes gateway list\n\n# 安装特定平台网关\nhermes gateway install telegram\nhermes gateway install discord\nhermes gateway install slack\n\n# 启动所有网关\nhermes gateway start\n\n# 停止所有网关\nhermes gateway stop\n\n# 重启特定网关\nhermes gateway restart discord\n```\n\n### 支持的消息平台\n\n| 平台 | 网关名称 | 功能 |\n|------|----------|------|\n| Telegram | `telegram` | 完整支持（文字、语音、群组） |\n| Discord | `discord` | 完整支持（含语音频道） |\n| Slack | `slack` | 支持 |\n| WhatsApp | `whatsapp` | 支持 |\n| Signal | `signal` | 支持 |\n| Matrix | `matrix` | 支持 |\n| Mattermost | `mattermost` | 支持 |\n| Email | `email` | 支持 |\n| SMS | `sms` | 支持 |\n| DingTalk (钉钉) | `dingtalk` | 支持 |\n| Feishu (飞书) | `feishu` | 支持 |\n| WeCom (企业微信) | `wecom` | 支持 |\n| Home Assistant | `homeassistant` | 支持 |\n\n---\n\n## 定时任务 (Cron)\n\n### 任务管理\n\n```bash\n# 列出所有任务\nhermes cron list\n\n# 创建任务\nhermes cron add \\\n  --name \"每日新闻摘要\" \\\n  --cron \"0 9 * * *\" \\          # 每天 9:00\n  --message \"总结今日科技新闻\" \\\n  --skill daily-news             # 可附加技能\n\n# 暂停任务\nhermes cron pause TASK_ID 或 任务名\n\n# 恢复任务\nhermes cron resume TASK_ID 或 任务名\n\n# 编辑任务\nhermes cron edit TASK_ID\n\n# 删除任务\nhermes cron remove TASK_ID\nhermes cron rm TASK_ID            # 短形式\n\n# 手动触发任务\nhermes cron run TASK_ID\n```\n\n### Cron 表达式语法\n\n```\n┌───────────── 分钟 (0-59)\n│ ┌───────────── 小时 (0-23)\n│ │ ┌───────────── 月中天 (1-31)\n│ │ │ ┌───────────── 月 (1-12)\n│ │ │ │ ┌───────────── 周中天 (0-6, 0=周日)\n│ │ │ │ │\n* * * * *\n```\n\n**示例**:\n\n| 表达式 | 含义 |\n|--------|------|\n| `* * * * *` | 每分钟 |\n| `*/15 * * * *` | 每15分钟 |\n| `0 * * * *` | 每小时 |\n| `0 9 * * *` | 每天 9:00 |\n| `0 9 * * 1` | 每周一 9:00 |\n| `0 9 1 * *` | 每月1号 9:00 |\n| `0 9-17 * * 1-5` | 工作日 9:00-17:00 每小时 |\n\n---\n\n## MCP 集成\n\n### Server 模式（暴露能力给 IDE）\n\n```bash\n# 启动 MCP Server\nhermes mcp serve --port 8080\nhermes mcp serve --stdio        # 标准输入输出模式\n\n# 配置 MCP Server\nhermes mcp serve-config         # 生成 IDE 配置片段\n```\n\n### Client 模式（连接外部服务）\n\n```bash\n# 连接外部 MCP 服务器\nhermes mcp connect <server-config-json>\n\n# 列出已连接的 MCP 服务\nhermes mcp list\n\n# 断开连接\nhermes mcp disconnect <server-id>\n```\n\n详见 [mcp-integration.md](./mcp-integration.md)\n\n---\n\n## 诊断与调试\n\n### 状态检查\n\n```bash\n# 快速状态概览\nhermes status\n\n# 详细诊断\nhermes doctor\n```\n\n### 日志查看\n\n```bash\n# 实时查看日志\nhermes logs --follow\nhermes logs -f\n\n# 查看最近N行\nhermes logs -n 100\n\n# 过滤日志级别\nhermes logs --level ERROR\nhermes logs --level WARNING\n\n# 查看特定会话的日志\nhermes logs --session SESSION_ID\n```\n\n### 性能分析\n\n```bash\n# 查看最近的性能指标\nhermes stats\n\n# 查看Token使用统计\nhermes stats tokens\n\n# 查看任务耗时统计\nhermes stats timing\n```\n\n### 重置与清理\n\n```bash\n# 清理缓存\nhermes cleanup cache\n\n# 清理旧会话（超过N天的）\nhermes cleanup sessions --older-than 30\n\n# 重置为出厂设置（⚠️ 会删除所有数据和配置）\nhermes reset --factory\n```\n\n---\n\n## 环境变量\n\n| 变量名 | 说明 | 默认值 |\n|--------|------|--------|\n| `HERMES_HOME` | Hermes 数据目录 | `~/.hermes` |\n| `HERMES_CONFIG` | 自定义配置文件路径 | `~/.hermes/config.yaml` |\n| `HERMES_ENV_FILE` | 自定义环境变量文件 | `~/.hermes/.env` |\n| `HERMES_LOG_LEVEL` | 日志级别 | INFO |\n| `HERMES_NO_COLOR` | 禁用彩色输出 | false |\n| `HERMES_ENABLE_PROJECT_PLUGINS` | 启用项目级插件 | false |\n| `HERMES_OPTIONAL_SKILLS` | 自定义可选技能目录 | null |\n\n---\n\n## 退出码\n\n| 退出码 | 含义 |\n|--------|------|\n| 0 | 成功 |\n| 1 | 一般错误 |\n| 2 | 参数错误 |\n| 3 | 配置错误 |\n| 4 | 网络错误 |\n| 5 | API 认证失败 |\n| 124 | 超时（来自 timeout 命令） |\n| 130 | 用户中断 (Ctrl+C) |\n\nFile v2.1.0:references/config-guide.md\n\n# Hermes Agent 配置指南\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [API Key 配置](#api-key-配置)\n2. [模型配置](#模型配置)\n3. [提供商设置](#提供商设置)\n4. [工具集配置](#工具集配置)\n5. [记忆系统配置](#记忆系统配置)\n6. [网关配置](#网关配置)\n7. [安全配置](#安全配置)\n8. [完整配置示例](#完整配置示例)\n\n---\n\n## API Key 配置\n\n### 环境变量文件 (`~/.hermes/.env`)\n\n这是存储所有敏感凭证的主要位置。**不要将此文件提交到版本控制系统！**\n\n```bash\n# ========================================\n# 必需：至少配置一个 LLM 提供商\n# ========================================\n\n# OpenRouter（推荐，支持 200+ 模型）\nOPENROUTER_API_KEY=sk-or-v1-your-key-here\n\n# 或使用其他提供商：\n# Anthropic (Claude)\nANTHROPIC_API_KEY=sk-ant-your-key-here\n\n# OpenAI (GPT-4o, etc.)\nOPENAI_API_KEY=sk-openai-your-key-here\n\n# Google (Gemini)\nGOOGLE_API_KEY=your-google-api-key\n\n# ========================================\n# 可选：增强功能\n# ========================================\n\n# Firecrawl - 高级网页抓取（比内置搜索更强大）\nFIRECRAWL_API_KEY=fc-your-firecrawl-key\n\n# FAL.ai - 图像生成（FLUX 模型）\nFAL_KEY=your-fal-api-key\n\n# ElevenLabs - 高级语音合成（替代免费的 Edge TTS）\nELEVENLABS_API_KEY=your-elevenlabs-key\n\n# Brave Search - 网页搜索\nBRAVE_API_KEY=your-brave-search-key\n\n# OpenWeatherMap - 天气查询\nOPENWEATHERMAP_API_KEY=your-weather-key\n\n# GitHub Token - 用于 GitHub 集成\nGITHUB_TOKEN=ghp_your-github-token\n\n# ========================================\n# 可选：消息平台\n# ========================================\n\n# Telegram Bot\nTELEGRAM_BOT_TOKEN=your-telegram-bot-token\n\n# Discord Bot\nDISCORD_BOT_TOKEN=your-discord-bot-token\n\n# Slack Bot\nSLACK_BOT_TOKEN=xoxb-your-slack-bot-token\nSLACK_APP_TOKEN=xapp-your-slack-app-token\n\n# WhatsApp Bridge (需要单独配置)\n# 参考文档: https://hermes-agent.nousresearch.com/docs/gateways/whatsapp/\n```\n\n### 获取 API Key 的途径\n\n| 服务 | 获取地址 | 免费额度 |\n|------|----------|----------|\n| **OpenRouter** | https://openrouter.ai/keys | 注册即送少量额度 |\n| **Anthropic** | https://console.anthropic.com/ | 新用户 $5 免费 |\n| **OpenAI** | https://platform.openai.com/api-keys | 新用户 $5 免费 |\n| **Google AI** | https://aistudio.google.com/apikey | 免费层可用 |\n| **Firecrawl** | https://www.firecrawl.dev/account | 500 次免费抓取 |\n| **FAL.ai** | https://fal.ai/dashboard/keys | 每日免费额度 |\n| **ElevenLabs** | https://elevenlabs.io/app/settings/api-keys | 每月 10k 字符免费 |\n| **Brave Search** | https://brave.com/search/api/ | 每月 2k 次免费 |\n\n---\n\n## 模型配置\n\n### 通过 CLI 选择模型\n\n```bash\n# 启动交互式模型选择向导\nhermes model\n```\n\n### 通过配置文件指定模型\n\n编辑 `~/.hermes/config.yaml`:\n\n```yaml\nmodel:\n  # LLM 提供商\n  provider: openrouter\n  \n  # 模型名称\n  # OpenRouter 格式: <provider>/<model-name>\n  model: anthropic/claude-sonnet-4-20250514\n  \n  # 或直接使用提供商原生名称:\n  # model: claude-3-5-sonnet-20241022    # Anthropic 直接调用\n  # model: gpt-4o                        # OpenAI 直接调用\n  \n  # 温度参数 (0.0 = 确定性, 2.0 = 最大随机性)\n  temperature: 0.7\n  \n  # 最大输出 token 数\n  max_tokens: 4096\n  \n  # Top P 采样参数\n  top_p: 1.0\n  \n  # 是否启用流式输出\n  streaming: true\n```\n\n### 推荐模型选择\n\n#### 性价比优先\n\n| 模型 | 成本 ($/1M tokens) | 特点 |\n|------|---------------------|------|\n| `openrouter/google/gemini-flash-1.5` | ~$0.07 | 最便宜，速度快 |\n| `openrouter/meta-llama/llama-3.1-8b-instruct:free` | 免费 | 开源，适合简单任务 |\n| `anthropic/claude-haiku-4-5-20251001` | ~$0.80 | 快速，质量好 |\n\n#### 质量优先\n\n| 模型 | 成本 ($/1M tokens) | 特点 |\n|------|---------------------|------|\n| `anthropic/claude-sonnet-4-20250514` | ~$3.00 | 平衡质量和成本 |\n| `openai/gpt-4o` | ~$2.50 | 多模态能力强 |\n| `google/gemini-2.5-pro` | ~$6.25 | 推理能力强，长上下文 |\n\n#### 专业用途\n\n| 用途 | 推荐模型 | 原因 |\n|------|----------|------|\n| 代码生成 | `anthropic/claude-sonnet-4-20250514` | 代码能力优秀 |\n| 网页研究 | `google/gemini-2.5-pro` | 大上下文窗口 |\n| 创意写作 | `openai/gpt-4o` | 文学风格多样 |\n| 快速问答 | `anthropic/claude-haiku-4-5-20251001` | 响应快，成本低 |\n| 数据分析 | `openai/o4-mini` | 推理能力强 |\n\n---\n\n## 提供商设置\n\n### OpenRouter（推荐）\n\n```yaml\nproviders:\n  openrouter:\n    base_url: \"https://openrouter.ai/api/v1\"\n    api_key_env: OPENROUTER_API_KEY  # 从 .env 读取\n    models:\n      default: \"anthropic/claude-sonnet-4-20250514\"\n    \n    # 高级选项\n    timeout: 120                    # 请求超时（秒）\n    max_retries: 3                  # 重试次数\n    \n    # HTTP Headers（可选）\n    extra_headers:\n      X-Title: \"Hermes Agent\"\n      HTTP-Referer: \"http://localhost:8080\"\n```\n\n### Anthropic 直接连接\n\n```yaml\nproviders:\n  anthropic:\n    api_key_env: ANTHROPIC_API_KEY\n    models:\n      default: \"claude-sonnet-4-20250514\"\n    base_url: \"https://api.anthropic.com\"\n```\n\n### OpenAI 直接连接\n\n```yaml\nproviders:\n  openai:\n    api_key_env: OPENAI_API_KEY\n    models:\n      default: \"gpt-4o\"\n    base_url: \"https://api.openai.com/v1\"\n```\n\n### Ollama（本地模型，零成本）\n\n```yaml\nproviders:\n  ollama:\n    base_url: \"http://localhost:11434/v1\"\n    models:\n      default: \"llama3.1:8b\"        # 需先运行 ollama pull llama3.1:8b\n    api_key: \"ollama\"               # Ollama 不需要真实 API Key\n    # 无需 API Key，完全离线运行\n```\n\n---\n\n## 工具集配置\n\n### 启用/禁用工具集\n\n```yaml\ntools:\n  # 全局默认启用状态\n  enabled_by_default: true\n  \n  # 工具集定义\n  toolsets:\n    web_search:\n      enabled: true\n      tools:\n        - search_web\n        - firecrawl_scrape\n        \n    browser:\n      enabled: true\n      backend: local_chrome       # browserbase_cloud | browser_use_cloud | local_chrome | local_chromium\n      \n    file_operations:\n      allowed_paths:\n        - /Users/chunhaixu/Projects\n        - /tmp\n        - ~/Documents\n      denied_paths:\n        - ~/.ssh\n        - ~/.gnupg\n        - /etc\n        \n    terminal:\n      allowed_commands:\n        - git\n        - npm\n        - python\n        - cat\n        - ls\n        - grep\n        - find\n      denied_commands:\n        - rm -rf /\n        - sudo\n        - chmod 777\n        \n    memory:\n      enabled: true\n      backend: built-in           # built-in | honcho | mem0 | ...\n      \n    code_execution:\n      enabled: true\n      sandbox: docker             # docker | subprocess\n      \n    delegation:\n      enabled: true\n      max_concurrent: 3          # 最大并发子代理数\n      default_timeout: 300        # 默认超时（秒）\n      \n    image_generation:\n      enabled: false              # 需要 FAL_KEY\n      provider: fal               # fal | ...\n      model: flux-2-pro          \n      upscale: true               # 自动 2x 放大\n      \n    voice:\n      enabled: true\n      tts_provider: edge_tts      # edge_tts | elevenlabs | openai_tts | minimax | neutts\n      stt_provider: whisper       # whisper | groq_whisper\n```\n\n---\n\n## 记忆系统配置\n\n```yaml\nmemory:\n  # 后端选择\n  provider: built-in             # built-in | honcho | mem0 | openviking | hindsight | holographic | retaindb | byte-rover\n  \n  # 内置后端特定配置\n  built_in:\n    storage_path: ~/.hermes/memory\n    fts_enabled: true            # 启用全文搜索\n    max_notes: 10000             # 最大笔记数\n    auto_summarize: true         # 自动摘要旧会话\n    summary_model: haiku         # 用于摘要的模型\n    \n  # Honcho 后端（如果使用）\n  honcho:\n    project_id: your-project-id\n    dialect_name: user-profile   # 用户方言文件名\n    \n  # 记忆保留策略\n  retention:\n    hot_memory_days: 7           # 热记忆保留天数\n    session_history_days: 30     # 会话历史保留天数\n    cold_storage_after: 90       # 天数后归档\n    auto_prune: true             # 自动清理过期记忆\n```\n\n---\n\n## 网关配置\n\n### Telegram 示例\n\n```yaml\ngateway:\n  telegram:\n    enabled: true\n    bot_token_env: TELEGRAM_BOT_TOKEN\n    allowed_users:                # 限制可用的用户 ID（可选）\n      - 123456789\n    allowed_groups:               # 限制群组（可选）\n      - -1001234567890\n    commands:\n      start: \"欢迎使用 Hermes Agent！输入你的问题开始对话。\"\n      help: \"可用命令：\\n/ask <问题>\\n/memory search <关键词>\\n/status\"\n    features:\n      voice: true                 # 支持语音消息\n      image_analysis: true        # 分析图片\n      inline_queries: true        # 内联模式\n```\n\n### Discord 示例\n\n```yaml\ngateway:\n  discord:\n    enabled: true\n    bot_token_env: DISCORD_BOT_TOKEN\n    command_prefix: \"!\"           # 命令前缀\n    allowed_guilds:              # 限制服务器\n      - \"123456789012345678\"\n    voice_channels:              # 支持语音频道\n      enabled: true\n    features:\n      slash_commands: true       # 斜杠命令\n      context_menus: true        # 右键菜单\n      message_content: true      # 内容意图（需在 Discord 开发者门户开启）\n```\n\n---\n\n## 安全配置\n\n```yaml\nsecurity:\n  # 提示注入防护\n  prompt_injection_protection:\n    enabled: true                 # v0.7.0+ 默认开启\n    strictness: medium            # low | medium | high\n    \n  # 凭证过滤\n  credential_filtering:\n    enabled: true\n    patterns:                    # 要过滤的模式\n      - \"(?i)(api[_-]?key|token|secret|password)[=:]\\s*\\S+\"\n      - \"sk-[a-zA-Z0-9]{20,}\"\n      - \"ghp_[a-zA-Z0-9]{36}\"\n      \n  # 工具权限控制\n  tool_permissions:\n    terminal:\n      require_confirmation:\n        - \"rm \"\n        - \"sudo\"\n        - \"chmod 777\"\n        - \"curl.*\\\\| bash\"\n        \n  # 日志审计\n  audit_logging:\n    enabled: true\n    log_tool_calls: true\n    log_file_access: true\n    log_network_requests: true\n    \n  # 网络访问控制\n  network:\n    allowed_domains:             # 白名单（留空则允许所有）\n      - \"*.openai.com\"\n      - \"*.anthropic.com\"\n      - \"*.openrouter.ai\"\n    blocked_domains:              # 黑名单\n      - \"*.malicious-site.com\"\n```\n\n---\n\n## 完整配置示例\n\n这是一个生产就绪的完整配置示例：\n\n```yaml\n# ============================================\n# Hermes Agent 完整配置示例\n# 文件位置: ~/.hermes/config.yaml\n# ============================================\n\n# --- 核心模型设置 ---\nmodel:\n  provider: openrouter\n  model: anthropic/claude-sonnet-4-20250514\n  temperature: 0.7\n  max_tokens: 8192\n  top_p: 1.0\n  streaming: true\n\n# --- 提供商 ---\nproviders:\n  openrouter:\n    base_url: \"https://openrouter.ai/api/v1\"\n    api_key_env: OPENROUTER_API_KEY\n    timeout: 120\n    max_retries: 3\n    extra_headers:\n      X-Title: \"My Hermes Instance\"\n\n# --- 工具集 ---\ntools:\n  enabled_by_default: true\n  toolsets:\n    web_search:\n      enabled: true\n    browser:\n      enabled: true\n      backend: local_chrome\n    file_operations:\n      allowed_paths:\n        - ~/Projects\n        - /tmp\n        - ~/Documents\n      denied_paths:\n        - ~/.ssh\n        - ~/.gnupg\n    terminal:\n      enabled: true\n      allowed_commands:\n        - git\n        - npm\n        - python\n        - node\n        - make\n        - cat\n        - ls\n        - grep\n        - find\n        - head\n        - tail\n        - wc\n        - sed\n        - awk\n    memory:\n      enabled: true\n      provider: built-in\n    code_execution:\n      enabled: true\n    delegation:\n      enabled: true\n      max_concurrent: 3\n      default_timeout: 300\n    image_generation:\n      enabled: false\n    voice:\n      enabled: true\n      tts_provider: edge_tts\n\n# --- 记忆系统 ---\nmemory:\n  provider: built-in\n  retention:\n    hot_memory_days: 7\n    session_history_days: 30\n    cold_storage_after: 90\n    auto_prune: true\n\n# --- 安全 ---\nsecurity:\n  prompt_injection_protection:\n    enabled: true\n    strictness: medium\n  credential_filtering:\n    enabled: true\n  tool_permissions:\n    terminal:\n      require_confirmation:\n        - \"rm -rf\"\n        - \"sudo\"\n        - \"curl.*\\\\| bash\"\n        - \"wget.*\\\\| sh\"\n  audit_logging:\n    enabled: true\n\n# --- 网关（按需启用）---\ngateway:\n  telegram:\n    enabled: false\n  discord:\n    enabled: false\n\n# --- UI 设置 ---\nui:\n  theme: dark                   # dark | light\n  color_output: true\n  show_thinking: false         # 显示推理过程\n  timestamp_format: \"%Y-%m-%d %H:%M:%S\"\n```\n\n---\n\n## 常见配置问题\n\n### Q: 如何切换模型？\n\n```bash\n# 方法1：交互式\nhermes model\n\n# 方法2：命令行临时覆盖\nhermes run \"prompt\" --model gpt-4o --non-interactive\n\n# 方法3：编辑配置文件\nnano ~/.hermes/config.yaml  # 修改 model.model 字段\n```\n\n### Q: 如何降低成本？\n\n1. 使用更便宜的模型（如 Haiku、Flash）\n2. 减少最大 token 数\n3. 限制启用的工具集（减少不必要的函数调用）\n4. 使用缓存友好的提示词\n5. 考虑 Ollama 本地模型（零 API 成本）\n\n### Q: 如何解决 \"API key invalid\" 错误？\n\n1. 检查 `~/.hermes/.env` 中密钥是否正确\n2. 确认密钥没有过期或达到配额限制\n3. 运行 `hermes doctor` 进行诊断\n4. 尝试切换到备用提供商\n\n### Q: 如何让多个项目共享同一个 Hermes？\n\n创建项目级 `.hermes/config.yaml`：\n\n```bash\ncd my-project\nmkdir -p .hermes\ncat > .hermes/config.yaml << EOF\nmodel:\n  provider: openrouter\n  model: anthropic/claude-sonnet-4-20250514\nEOF\n\nHERMES_ENABLE_PROJECT_AGENTS=true hermes\n```\n\nFile v2.1.0:references/mcp-integration.md\n\n# Hermes Agent MCP 集成详解\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [MCP 协议概述](#mcp-协议概述)\n2. [双向集成架构](#双向集成架构)\n3. [Server 模式（暴露能力）](#server-模式暴露能力)\n4. [Client 模式（连接外部服务）](#client-模式连接外部服务)\n5. [工具过滤与安全](#工具过滤与安全)\n6. [IDE 配置](#ide-配置)\n7. [高级用法](#高级用法)\n8. [故障排除](#故障排除)\n\n---\n\n## MCP 协议概述\n\n**Model Context Protocol (MCP)** 是一种开放标准，允许 AI 应用与外部数据源和工具进行标准化通信。Hermes Agent 从 v0.6.0 起支持 MCP 的**双向集成**：\n\n```\n┌─────────────────────────────────────────────────────┐\n│                  MCP 生态                             │\n│                                                     │\n│   ┌──────────┐     ┌──────────┐     ┌──────────┐   │\n│   │   IDE    │ ←→ │  Hermes  │ ←→ │ 外部API  │   │\n│   │(Cursor)  │     │   Agent  │     │ (DB/CRM) │   │\n│   └──────────┘     └──────────┘     └──────────┘   │\n│        ↑               ↑               ↑           │\n│   MCP Client       MCP Server      MCP Server       │\n│                                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n### 核心概念\n\n| 概念 | 说明 |\n|------|------|\n| **MCP Server** | 提供能力和资源的服务端 |\n| **MCP Client** | 连接并使用 MCP Server 能力的客户端 |\n| **Tool** | 可被 LLM 调用的函数 |\n| **Resource** | 可被读取的数据（文件、URI等） |\n| **Prompt** | 可被注入的提示模板 |\n\n---\n\n## 双向集成架构\n\n### 架构图\n\n```\n                         ┌─────────────────────────┐\n                         │    WorkBuddy / IDE       │\n                         │         (客户端)          │\n                         └───────────┬─────────────┘\n                                     │ MCP Protocol\n                                     ▼\n                    ┌────────────────────────────────┐\n                    │        Hermes Agent             │\n                    │                                │\n                    │  ┌─────────────────────────┐   │\n                    │  │   MCP Server Mode        │   │\n                    │  │  (暴露 Hermes 能力)      │   │\n                    │  │  - 47+ 工具             │   │\n                    │  │  - 记忆系统              │   │\n                    │  │  - 技能系统              │   │\n                    │  └─────────────────────────┘   │\n                    │                                │\n                    │  ┌─────────────────────────┐   │\n                    │  │   MCP Client Mode        │   │\n                    │  │  (连接外部服务)          │   │\n                    │  │  - 数据库               │   │\n                    │  │  - API 服务             │   │\n                    │  │  - 文件系统             │   │\n                    │  └─────────────────────────┘   │\n                    └────────────────────────────────┘\n```\n\n### 使用场景\n\n| 场景 | 模式 | 说明 |\n|------|------|------|\n| IDE 集成 | Server | 在 Cursor/Windsurf 中调用 Hermes |\n| 扩展能力 | Client | 让 Hermes 使用外部数据库/API |\n| 双向桥接 | 两者兼用 | 同时作为 Server 和 Client |\n\n---\n\n## Server 模式（暴露能力）\n\n### 启动 MCP Server\n\n```bash\n# 方式1：标准输入输出模式（推荐用于 IDE 集成）\nhermes mcp serve --stdio\n\n# 方式2：HTTP 服务器模式\nhermes mcp serve --port 8080\n\n# 方式3：带配置选项启动\nhermes mcp serve --stdio \\\n  --allowed-tools \"web_search,memory,delegation\" \\\n  --max-tokens 4096 \\\n  --model \"anthropic/claude-haiku\"\n```\n\n### Server 配置选项\n\n| 选项 | 默认值 | 说明 |\n|------|--------|------|\n| `--port` | 8080 | HTTP 模式端口号（仅 HTTP 模式） |\n| `--stdio` | false | 使用 stdio 模式（推荐） |\n| `--model` | 配置默认值 | 强制使用指定模型 |\n| `--max-tokens` | 配置默认值 | 最大输出 Token 数 |\n| `--temperature` | 配置默认值 | 温度参数 |\n| `--allowed-tools` | 全部 | 允许暴露的工具列表（逗号分隔） |\n| `--blocked-tools` | 无 | 禁止暴露的工具列表 |\n| `--enable-memory` | true | 是否暴露记忆相关工具 |\n| `--enable-delegation` | true | 是否暴露子代理委托工具 |\n| `--require-authentication` | false | 是否需要认证令牌 |\n| `--auth-token` | 自动生成 | 认证令牌 |\n\n### 暴露的工具列表\n\n当以 Server 模式运行时，以下工具会暴露给 MCP 客户端：\n\n#### 核心工具\n\n| 工具名 | 参数 | 说明 |\n|--------|------|------|\n| `run_task` | task, context? | 运行完整任务（等同于 `hermes run`） |\n| `search_memory` | query, limit? | 搜索历史记忆 |\n| `add_note` | content, tags? | 添加新笔记 |\n| `list_notes` | tag_filter? | 列出所有笔记 |\n| `delegate_task` | task, tools?, timeout? | 创建子代理执行任务 |\n| `list_skills` | - | 列出已学技能 |\n| `create_skill` | name, description, content? | 创建新技能 |\n| `web_search` | query, num_results? | 网页搜索 |\n| `read_file` | path, offset?, limit? | 读取文件内容 |\n| `write_file` | path, content | 写入文件 |\n| `execute_command` | command, timeout? | 执行终端命令 |\n| `browser_navigate` | url | 浏览器导航到 URL |\n| `browser_click` | selector | 点击页面元素 |\n| `browser_extract` | selector, extract_type? | 提取页面数据 |\n\n---\n\n## Client 模式（连接外部服务）\n\n### 连接 MCP Server\n\n```bash\n# 方式1：通过命令行添加\nhermes mcp connect --name my-database \\\n  --type sse \\\n  --url http://localhost:3000/sse\n\n# 方式2：通过 JSON 配置\nhermes mcp connect '{\n  \"name\": \"postgres-db\",\n  \"type\": \"sse\",\n  \"url\": \"http://localhost:3000/mcp\",\n  \"headers\": {\"Authorization\": \"Bearer token123\"}\n}'\n\n# 方式3：从配置文件加载\nhermes mcp connect --config ./mcp-servers.json\n```\n\n### 配置文件格式 (`~/.hermes/mcp_servers.json`)\n\n```json\n{\n  \"mcpServers\": {\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-postgres\", \n               \"postgresql://user:pass@localhost:5432/mydb\"],\n      \"env\": {}\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \n               \"/path/to/allowed/directory\"],\n      \"env\": {}\n    },\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"ghp_...\"\n      }\n    },\n    \"slack\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"xoxb-...\",\n        \"SLACK_APP_TOKEN\": \"xapp-...\"\n      }\n    },\n    \"brave-search\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-brave-search\"],\n      \"env\": {\n        \"BRAVE_API_KEY\": \"your-key\"\n      }\n    },\n    \"puppeteer\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-puppeteer\"]\n    },\n    \"fetch\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-fetch\"]\n    }\n  }\n}\n```\n\n### 管理 MCP 连接\n\n```bash\n# 列出已连接的 MCP 服务\nhermes mcp list\n\n# 显示某个服务的可用工具\nhermes mcp tools database\n\n# 断开连接\nhermes mcp disconnect database\n\n# 断开所有连接\nhermes mcp disconnect --all\n\n# 测试连接\nhermes mcp test database\n```\n\n---\n\n## 工具过滤与安全\n\n### Server 端工具过滤\n\n当 Hermes 作为 MCP Server 运行时，可以限制暴露的工具：\n\n```bash\n# 只暴露特定工具\nhermes mcp serve --stdio \\\n  --allowed-tools \"run_task,search_memory,web_search\"\n\n# 排除危险工具\nhermes mcp serve --stdio \\\n  --blocked-tools \"execute_command,write_file,browser_*\"\n\n# 组合使用\nhermes mcp serve --stdio \\\n  --allowed-tools \"run_task,search_memory,list_notes\" \\\n  --blocked-tools \"\"\n```\n\n### Client 端工具命名空间\n\n来自 MCP Client 的工具会被自动加上命名空间前缀：\n\n```bash\n# 假设连接了 postgres 和 github 两个 MCP Server\n\n# 来自 postgres 的工具：\npostgres:query\npostgres:list_tables\npostgres:get_schema\n\n# 来自 github 的工具：\ngithub:search_issues\ngithub:create_issue\ngithub:get_file_contents\n\n# Hermes 内置工具保持原样：\nrun_task\nsearch_memory\ndelegate_task\n```\n\n### 安全最佳实践\n\n```yaml\n# ~/.hermes/config.yaml\nsecurity:\n  mcp:\n    # Server 模式设置\n    server:\n      require_authentication: true\n      auth_token_env: HERMES_MCP_AUTH_TOKEN\n      allowed_origins:            # CORS 白名单\n        - \"vscode-webview://*\"\n        - \"windsurf://*\"\n      \n    # Client 模式设置\n    client:\n      allow_untrusted_servers: false  # 只允许预配置的服务器\n      timeout_per_tool: 60           # 每个 MCP 工具超时时间\n      \n    # 审计日志\n    audit_log:\n      enabled: true\n      log_mcp_calls: true\n      include_params: false          # 不记录敏感参数\n```\n\n---\n\n## IDE 配置\n\n### Cursor 配置\n\n在 `.cursor/mcp.json` 中添加：\n\n```json\n{\n  \"mcpServers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\", \n               \"--allowed-tools\", \"run_task,search_memory,web_search,read_file,write_file\"]\n    }\n  }\n}\n```\n\n### VS Code + Claude Code 配置\n\n在 `.vscode/settings.json` 或 Claude Code 配置中：\n\n```json\n{\n  \"mcpServers\": {\n    \"hermes-agent\": {\n      \"command\": \"/Users/username/.local/bin/hermes\",\n      \"args\": [\n        \"mcp\", \n        \"serve\", \n        \"--stdio\",\n        \"--model\", \"anthropic/claude-haiku\",\n        \"--allowed-tools\", \"run_task,search_memory,web_search,file_operations,execute_code\"\n      ]\n    }\n  }\n}\n```\n\n### Windsurf 配置\n\n在 `.windsurf/mcp.json` 中：\n\n```json\n{\n  \"servers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n    }\n  }\n}\n```\n\n### Zed 编辑器配置\n\n在 `settings.json` 中：\n\n```json\n{\n  \"mcp_servers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n    }\n  }\n}\n```\n\n---\n\n## 高级用法\n\n### 1. 多实例部署\n\n同时运行多个 Hermes MCP Server，每个有不同的模型和能力配置：\n\n```bash\n# 实例1：轻量级快速任务（Haiku）\nHERMES_MCP_PORT=8081 hermes mcp serve --port 8081 \\\n  --model anthropic/claude-haiku \\\n  --allowed-tools \"run_task,search_memory\" &\n\n# 实例2：深度研究任务（Sonnet）\nHERMES_MCP_PORT=8082 hermes mcp serve --port 8082 \\\n  --model anthropic/claude-sonnet \\\n  --allowed-tools \"run_task,web_search,browser,delegation\" &\n\n# 实例3：代码任务（GPT-4o）\nHERMES_MCP_PORT=8083 hermes mcp serve --port 8083 \\\n  --model openai/gpt-4o \\\n  --allowed-tools \"run_task,file_operations,code_execution,terminal\" &\n```\n\nIDE 配置中选择不同的端口连接不同能力的实例。\n\n### 2. 链式 MCP 调用\n\nHermes 作为中间层，串联多个 MCP 服务：\n\n```\nIDE → Hermes MCP Server → [Hermes 内部处理]\n                           ↓\n                    Hermes MCP Client A → PostgreSQL\n                    Hermes MCP Client B → GitHub API\n                    Hermes MCP Client C → Slack\n```\n\nHermes 可以智能地根据任务需求选择调用哪个外部 MCP 工具。\n\n### 3. 自定义工具包装\n\n将外部 MCP 工具包装为 Hermes 的原生技能：\n\n```python\n# 包装脚本示例\ndef wrap_mcp_tool(ctx, tool_name, params):\n    \"\"\"\n    将 MCP 工具调用包装为 Hermes 技能\n    \"\"\"\n    result = call_mcp_client(\"my-server\", tool_name, params)\n    \n    # 后处理结果\n    if tool_name.startswith(\"db:\"):\n        return format_as_markdown_table(result)\n    elif tool_name.startswith(\"gh:\"):\n        return format_github_result(result)\n    \n    return result\n\nctx.register_tool(\n    name=\"query_database_via_mcp\",\n    schema=db_schema,\n    handler=lambda p: wrap_mcp_tool(ctx, f\"db:query\", p)\n)\n```\n\n### 4. 性能优化\n\n```yaml\n# config.yaml\nmcp:\n  server:\n    # 缓存常用查询结果\n    cache_enabled: true\n    cache_ttl: 300          # 缓存有效期（秒）\n    \n    # 并发控制\n    max_concurrent_requests: 5\n    \n    # 流式响应\n    streaming_enabled: true\n    \n  client:\n    # 连接池\n    connection_pool_size: 10\n    \n    # 重试策略\n    retry_attempts: 3\n    retry_backoff: 1s\n    \n    # 请求超时\n    request_timeout: 30s\n```\n\n---\n\n## 故障排除\n\n### 常见问题\n\n#### Q: MCP Server 启动失败\n\n```bash\n# 检查依赖\nhermes doctor\n\n# 查看 MCP 相关日志\nhermes logs --level ERROR | grep -i mcp\n\n# 手动测试 stdio 模式\necho '{\"jsonrpc\":\"2.0\",\"method\":\"initialize\",\"params\":{\"capabilities\":{}},\"id\":1}' | hermes mcp serve --stdio\n```\n\n#### Q: IDE 无法连接到 MCP Server\n\n1. **检查路径**: 确保 `hermes` 命令在 PATH 中\n2. **检查权限**: 确保 IDE 有权限执行 shell 命令\n3. **检查参数**: 确保 `args` 数组格式正确\n4. **测试连接**: 在终端手动运行相同命令验证\n\n```bash\n# Cursor/VSCODE 的调试方法\nhermes mcp serve --stdio &\n# 输入 JSON-RPC 测试消息\necho '{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":1}'\n```\n\n#### Q: MCP Client 连接超时\n\n```bash\n# 测试外部 MCP Server 是否可达\ncurl -v http://localhost:3000/sse\n\n# 检查网络配置\nhermes mcp test <server-name>\n\n# 增加超时时间\nhermes mcp connect ... --timeout 120\n```\n\n#### Q: 工具名称冲突\n\n当 Hermes 内置工具和 MCP Client 工具同名时，MCP 工具会自动加前缀。如果需要自定义前缀：\n\n```yaml\nmcp:\n  client:\n    namespace_prefix: true           # 启用命名空间前缀（默认开启）\n    namespace_separator: \":\"         # 分隔符\n    conflict_resolution: \"prefix\"    # prefix | rename | error\n```\n\n### 调试模式\n\n```bash\n# 启用详细调试日志\nHERMES_LOG_LEVEL=DEBUG hermes mcp serve --stdio\n\n# 查看所有 MCP 通信\nhermes logs --follow | grep -i mcp\n```\n\n---\n\n## 参考资源\n\n- **MCP 规范**: https://modelcontextprotocol.io/\n- **官方 SDK**: https://github.com/modelcontextprotocol/python-sdk\n- **社区服务器**: https://mcp.so/\n- **Hermes MCP 源码**: `mcp_serve.py`\n\nFile v2.1.0:references/plugin-development.md\n\n# Hermes Agent 插件开发指南\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [插件概述](#插件概述)\n2. [目录结构](#目录结构)\n3. [插件类型](#插件类型)\n4. [开发流程](#开发流程)\n5. [API 参考](#api-参考)\n6. [钩子系统](#钩子系统)\n7. [发布与分发](#发布与分发)\n8. [示例插件](#示例插件)\n\n---\n\n## 插件概述\n\nHermes 的插件系统允许用户在不修改核心代码的情况下扩展功能，支持：\n\n| 能力 | 说明 |\n|------|------|\n| **自定义工具** | 添加新的 LLM 可调用工具 |\n| **生命周期钩子** | 在关键事件点执行自定义逻辑 |\n| **CLI 命令扩展** | 添加 `hermes <plugin>` 子命令 |\n| **技能绑定** | 随插件分发技能文件 |\n| **数据文件打包** | 包含配置、模板等资源 |\n\n---\n\n## 目录结构\n\n```\nmy-plugin/\n├── plugin.yaml          # 插件清单（必需）\n├── __init__.py          # 注册函数（必需）\n├── schemas.py           # 工具模式定义\n├── tools.py             # 工具处理器实现\n├── data/                # 数据文件（可选）\n│   └── config.json\n└── skill.md             # 绑定的技能（可选）\n```\n\n### plugin.yaml 格式\n\n```yaml\nname: my-plugin-name           # 插件标识符（必需）\nversion: \"1.0.0\"              # 语义化版本（必需）\ndescription: 简短描述插件的功能 # 用户可见的描述（推荐）\nauthor: Your Name              # 作者信息（可选）\nrequires_env: []               # 需要的环境变量（可选，安装时提示用户配置）\n\n# 插件类型（自动检测，通常不需要手动指定）\ntype: general                  # general | memory_provider | context_engine\n\n# 兼容性\nhermes_min_version: \"0.7.0\"   # 最低兼容版本（可选）\nlicense: MIT                   # 许可证（可选）\nrepository: https://github.com/user/repo  # Git 仓库地址（可选）\n```\n\n### __init__.py 注册函数\n\n```python\n\"\"\"\n我的 Hermes 插件 - 实现描述\n\"\"\"\n\ndef register(ctx):\n    \"\"\"\n    主注册函数。Hermes 加载插件时调用此函数。\n    \n    Args:\n        ctx (PluginContext): 插件上下文对象，提供以下 API：\n            - ctx.register_tool(name, schema, handler): 注册工具\n            - ctx.register_hook(event_name, callback): 注册钩子\n            - ctx.register_cli_command(name, help, setup_fn, handler_fn): 注册 CLI 命令\n            - ctx.inject_message(content, role=\"user\"): 注入消息\n    \"\"\"\n    \n    # 导入你的工具定义和处理器\n    from .schemas import tool_schema\n    from .tools import handle_tool_call\n    \n    # 注册自定义工具\n    ctx.register_tool(\"my_tool_name\", tool_schema, handle_tool_call)\n    \n    # 注册钩子（可选）\n    def on_tool_complete(tool_name, params, result):\n        print(f\"[my-plugin] Tool {tool_name} completed\")\n        \n    ctx.register_hook(\"post_tool_call\", on_tool_complete)\n```\n\n---\n\n## 插件类型\n\n### 1. 通用插件 (General Plugin)\n\n最灵活的插件类型，可以添加任意数量的工具和钩子。\n\n```yaml\n# plugin.yaml\nname: weather-plugin\nversion: \"1.0.0\"\ndescription: 天气查询插件\n```\n\n```python\n# __init__.py\nfrom .schemas import get_weather_schema\nfrom .tools import get_weather_handler\n\ndef register(ctx):\n    ctx.register_tool(\"get_weather\", get_weather_schema, get_weather_handler)\n```\n\n### 2. 内存提供者 (Memory Provider)\n\n替换或增强内置的记忆系统。\n\n```yaml\n# plugin.yaml\nname: custom-memory\nversion: \"1.0.0\"\ndescription: 自定义记忆后端\ntype: memory_provider\n```\n\n```python\n# __init__.py\ndef register(ctx):\n    \"\"\"\n    内存提供者需要实现特定接口：\n    - search(query) -> List[Note]\n    - add(note) -> Note\n    - list_notes() -> List[Note]\n    - delete(note_id) -> bool\n    \"\"\"\n    class CustomMemoryBackend:\n        def search(self, query):\n            # 你的搜索实现\n            pass\n            \n        def add(self, content, tags=None):\n            # 你的添加实现\n            pass\n    \n    ctx.set_memory_backend(CustomMemoryBackend())\n```\n\n**可用的内存提供者类型**:\n\n| 后端名 | 特点 |\n|--------|------|\n| `built-in` | 默认，SQLite + FTS5 |\n| `honcho` | AI 原生方言建模 |\n| `mem0` | 开源记忆服务 |\n| `openviking` | 高级向量检索 |\n| `hindsight` | 时间线记忆 |\n| `holographic` | 全息记忆系统 |\n\n### 3. 上下文引擎 (Context Engine)\n\n替换内置的上下文压缩器。\n\n```yaml\n# plugin.yaml\nname: smart-context\nversion: \"1.0.0\"\ndescription: 智能上下文压缩\ntype: context_engine\n```\n\n```python\n# __init__.py\ndef register(ctx):\n    class SmartContextEngine:\n        def compress(self, messages, max_tokens):\n            # 自定义的上下文压缩逻辑\n            pass\n            \n        def summarize(self, text, target_length):\n            # 自定义摘要逻辑\n            pass\n    \n    ctx.set_context_engine(SmartContextEngine())\n```\n\n---\n\n## 开发流程\n\n### 步骤 1：创建插件骨架\n\n```bash\nmkdir -p ~/.hermes/plugins/my-plugin\ncd ~/.hermes/plugins/my-plugin\ntouch plugin.yaml __init__.py schemas.py tools.py\n```\n\n### 步骤 2：编写 plugin.yaml\n\n```yaml\nname: my-awesome-plugin\nversion: \"0.1.0\"\ndescription: 我的第一款 Hermes 插件\nauthor: Your Name\n```\n\n### 步骤 3：定义工具模式 (schemas.py)\n\n```python\n\"\"\"\n工具模式定义 - LLM 看到的接口说明\n\"\"\"\n\ntool_schema = {\n    \"name\": \"awesome_tool\",\n    \"description\": \"这个工具做什么的详细描述\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"param1\": {\n                \"type\": \"string\",\n                \"description\": \"参数1的说明\",\n            },\n            \"param2\": {\n                \"type\": \"integer\",\n                \"description\": \"参数2的说明\",\n                \"default\": 10,\n            },\n            \"options\": {\n                \"type\": \"array\",\n                \"items\": {\"type\": \"string\"},\n                \"description\": \"可选选项列表\",\n            }\n        },\n        \"required\": [\"param1\"],\n    }\n}\n```\n\n### 步骤 4：实现工具处理器 (tools.py)\n\n```python\n\"\"\"\n工具处理器 - 实际执行逻辑\n\"\"\"\n\nimport json\n\ndef handle_tool_call(params: dict) -> str:\n    \"\"\"\n    处理工具调用。\n    \n    Args:\n        params: 从 LLM 调用中接收到的参数字典\n        \n    Returns:\n        str: 返回给 LLM 的结果字符串（会被添加到对话历史中）\n    \"\"\"\n    param1 = params.get(\"param1\", \"\")\n    param2 = params.get(\"param2\", 10)\n    options = params.get(\"options\", [])\n    \n    try:\n        # === 在这里实现你的业务逻辑 ===\n        \n        result = f\"处理结果: param1={param1}, param2={param2}\"\n        \n        if options:\n            result += f\", options={', '.join(options)}\"\n            \n        return result\n        \n    except Exception as e:\n        # 错误处理：返回有意义的错误信息给 LLM\n        return f\"错误: 执行失败 - {str(e)}\"\n\n# 如果有多个工具，可以定义多个 schema/handler 对\nanother_tool_schema = {\n    \"name\": \"another_tool\",\n    \"description\": \"另一个工具\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\"type\": \"string\", \"description\": \"查询内容\"}\n        },\n        \"required\": [\"query\"]\n    }\n}\n\ndef another_handler(params: dict) -> str:\n    query = params.get(\"query\", \"\")\n    return f\"查询 '{query}' 的结果是...\"\n```\n\n### 步骤 5：在 __init__.py 中注册\n\n```python\n\"\"\"My Awesome Plugin for Hermes Agent.\"\"\"\n\ndef register(ctx):\n    \"\"\"Register all tools and hooks with Hermes.\"\"\"\n    \n    # 导入本地模块\n    from .schemas import tool_schema, another_tool_schema\n    from .tools import handle_tool_call, another_handler\n    \n    # 注册工具 1\n    ctx.register_tool(\n        name=\"awesome_tool\",\n        schema=tool_schema,\n        handler=handle_tool_call\n    )\n    \n    # 注册工具 2\n    ctx.register_tool(\n        name=\"another_tool\",\n        schema=another_tool_schema,\n        handler=another_handler\n    )\n    \n    # 注册钩子（可选）\n    def log_tool_usage(tool_name, params, result):\n        \"\"\"记录每次工具调用到日志文件\"\"\"\n        import json\n        from datetime import datetime\n        \n        log_entry = {\n            \"timestamp\": datetime.now().isoformat(),\n            \"tool\": tool_name,\n            \"params\": params,\n            \"success\": not str(result).startswith(\"错误\")\n        }\n        \n        with open(\"/tmp/plugin-tool-usage.log\", \"a\") as f:\n            f.write(json.dumps(log_entry) + \"\\n\")\n            \n    ctx.register_hook(\"post_tool_call\", log_tool_usage)\n    \n    # 注册 CLI 命令（可选）\n    def setup_parser(parser):\n        \"\"\"设置 CLI 参数解析器\"\"\"\n        parser.add_argument(\"--verbose\", action=\"store_true\")\n        parser.add_argument(\"--output-format\", choices=[\"json\", \"text\"], default=\"text\")\n        \n    def cmd_handler(args):\n        \"\"\"处理 CLI 命令\"\"\"\n        print(f\"My plugin running with verbose={args.verbose}\")\n        \n    ctx.register_cli_command(\n        name=\"my-plugin\",\n        help=\"我的插件的自定义命令\",\n        setup_fn=setup_parser,\n        handler_fn=cmd_handler\n    )\n```\n\n### 步骤 6：安装和测试\n\n```bash\n# 安装插件（从本地路径）\nhermes plugins install /path/to/my-plugin\n\n# 或从 Git 安装\nhermes plugins install https://github.com/you/my-plugin.git\n\n# 启用插件\nhermes plugins enable my-plugin\n\n# 测试插件是否加载\nhermes plugins list\n\n# 在对话中测试\nhermes run \"使用 awesome_tool 工具，参数 param1=test\" --non-interactive --no-stream\n```\n\n---\n\n## API 参考\n\n### PluginContext API\n\n#### `ctx.register_tool(name, schema, handler)`\n\n注册一个可供 LLM 调用的工具。\n\n**参数**:\n- `name` (str): 工具名称，全局唯一\n- `schema` (dict): JSON Schema 格式的工具定义\n- `handler` (callable): 处理函数 `(params: dict) -> str`\n\n**示例**:\n```python\nctx.register_tool(\"my_tool\", {...}, lambda p: \"result\")\n```\n\n#### `ctx.register_hook(event_name, callback)`\n\n注册生命周期钩子。\n\n**可用事件**:\n\n| 事件名 | 回调签名 | 触发时机 |\n|--------|----------|----------|\n| `pre_tool_call` | `(tool_name, params)` | 工具执行前 |\n| `post_tool_call` | `(tool_name, params, result)` | 工具执行后 |\n| `pre_llm_call` | `(messages, kwargs)` | LLM 调用前，可返回 `{\"context\": \"...\"}` 注入上下文 |\n| `post_llm_call` | `(response, messages)` | LLM 调用成功后 |\n| `on_session_start` | `(session_id)` | 新会话创建时 |\n| `on_session_end` | `(session_id)` | 会话结束时 |\n\n#### `ctx.register_cli_command(name, help, setup_fn, handler_fn)`\n\n注册 CLI 子命令。\n\n**参数**:\n- `name` (str): 命令名称（如 `my-cmd`，调用方式为 `hermes my-cmd`）\n- `help` (str): 帮助文本\n- `setup_fn` (callable): 设置参数解析器 `(parser) -> None`\n- `handler_fn` (callable): 处理命令 `(args) -> None`\n\n#### `ctx.inject_message(content, role=\"user\")`\n\n向当前会话注入消息。\n\n**示例**:\n```python\nctx.inject_message(\"注意：用户偏好是使用中文回复。\", role=\"system\")\n```\n\n---\n\n## 钩子系统\n\n### 钩子执行顺序\n\n```\n用户输入 → pre_llm_call → [LLM 调用] → post_llm_call \n                                    ↓\n                              解析工具调用\n                                    ↓\n                              pre_tool_call → [工具执行] → post_tool_call\n                                    ↓\n                              返回响应\n```\n\n### 高级钩子用法\n\n#### 1. 上下文注入\n\n在每次 LLM 调用前注入额外的上下文信息：\n\n```python\ndef inject_user_preferences(messages, kwargs):\n    \"\"\"注入用户偏好的上下文\"\"\"\n    preferences = load_user_preferences()  # 你自己的函数\n    \n    context_text = (\n        f\"当前用户偏好:\\n\"\n        f\"- 语言: {preferences['language']}\\n\"\n        f\"- 时区: {preferences['timezone']}\\n\"\n        f\"- 专业领域: {preferences['domain']}\\n\"\n    )\n    \n    return {\"context\": context_text}\n\nctx.register_hook(\"pre_llm_call\", inject_user_preferences)\n```\n\n#### 2. 工具调用审计\n\n记录所有工具调用的完整日志：\n\n```python\ndef audit_tool_calls(tool_name, params, result):\n    \"\"\"审计所有工具调用\"\"\"\n    import logging\n    \n    logger = logging.getLogger(\"plugin.audit\")\n    logger.info({\n        \"tool\": tool_name,\n        \"params\": params,\n        \"result_length\": len(str(result)),\n        \"timestamp\": time.time()\n    })\n\nctx.register_hook(\"post_tool_call\", audit_tool_calls)\n```\n\n#### 3. 敏感操作确认\n\n对危险操作进行二次确认：\n\n```python\ndef confirm_destructive_actions(tool_name, params):\n    \"\"\"拦截破坏性操作\"\"\"\n    destructive_patterns = [\n        (\"file_delete\", [\"rm\", \"delete\"]),\n        (\"execute_command\", [\"rm -rf\", \"sudo\"]),\n    ]\n    \n    for t_tool, t_keywords in destructive_patterns:\n        if tool_name == t_tool:\n            for kw in t_keywords:\n                params_str = str(params).lower()\n                if kw in params_str:\n                    raise PermissionError(\n                        f\"⚠️ 危险操作被拦截: {tool_name} 包含关键词 '{kw}'\"\n                    )\n\nctx.register_hook(\"pre_tool_call\", confirm_destructive_actions)\n```\n\n---\n\n## 发布与分发\n\n### 本地安装\n\n```bash\n# 从本地目录安装\nhermes plugins install /path/to/my-plugin\n\n# 或直接复制到插件目录\ncp -r my-plugin ~/.hermes/plugins/\nhermes plugins enable my-plugin\n```\n\n### 通过 Git 分发\n\n```bash\n# 从 GitHub 安装\nhermes plugins install owner/repo\nhermes plugins install https://github.com/owner/repo.git\n\n# 从私有仓库安装（需认证）\nhermes plugins install git@github.com:owner/private-repo.git\n```\n\n### 通过 Pip 分发\n\n在 `pyproject.toml` 中添加入口点：\n\n```toml\n[project.entry-points.\"hermes_agent.plugins\"]\nmy_plugin = \"my_package:register\"\n```\n\n用户通过 `pip install your-package` 即可安装。\n\n### 更新插件\n\n```bash\n# 更新单个插件\nhermes plugins update my-plugin\n\n# 更新所有已安装的插件\nhermes plugins update --all\n```\n\n---\n\n## 示例插件\n\n### 示例 1：天气查询插件\n\n```yaml\n# plugin.yaml\nname: weather-plugin\nversion: \"1.0.0\"\ndescription: 使用 OpenWeatherMap API 查询天气\nrequires_env: [OPENWEATHERMAP_API_KEY]\nauthor: Example Author\n```\n\n```python\n# __init__.py\n\"\"\"Weather Query Plugin for Hermes Agent.\"\"\"\nimport os\n\ndef register(ctx):\n    from .schemas import weather_schema, forecast_schema\n    from .tools import get_current_weather, get_forecast\n    \n    ctx.register_tool(\"get_current_weather\", weather_schema, get_current_weather)\n    ctx.register_tool(\"get_weather_forecast\", forecast_schema, get_forecast)\n```\n\n```python\n# schemas.py\nweather_schema = {\n    \"name\": \"get_current_weather\",\n    \"description\": \"获取指定城市的当前天气情况\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"city\": {\n                \"type\": \"string\",\n                \"description\": \"城市名称，如 'Beijing'、'New York'\"\n            },\n            \"units\": {\n                \"type\": \"string\",\n                \"enum\": [\"metric\", \"imperial\"],\n                \"default\": \"metric\",\n                \"description\": \"温度单位\"\n            }\n        },\n        \"required\": [\"city\"]\n    }\n}\n\nforecast_schema = {\n    \"name\": \"get_weather_forecast\",\n    \"description\": \"获取未来几天的天气预报\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"city\": {\n                \"type\": \"string\",\n                \"description\": \"城市名称\"\n            },\n            \"days\": {\n                \"type\": \"integer\",\n                \"description\": \"预报天数（1-7）\",\n                \"default\": 3\n            }\n        },\n        \"required\": [\"city\"]\n    }\n}\n```\n\n```python\n# tools.py\n\"\"\"Weather tool implementations.\"\"\"\nimport os\nimport requests\n\nAPI_KEY = os.environ.get(\"OPENWEATHERMAP_API_KEY\", \"\")\nBASE_URL = \"https://api.openweathermap.org/data/2.5\"\n\ndef get_current_weather(params: dict) -> str:\n    city = params[\"city\"]\n    units = params.get(\"units\", \"metric\")\n    \n    url = f\"{BASE_URL}/weather?q={city}&appid={API_KEY}&units={units}\"\n    \n    response = requests.get(url, timeout=10)\n    \n    if response.status_code != 200:\n        return f\"无法获取天气信息: {response.json().get('message', '未知错误')}\"\n    \n    data = response.json()\n    temp_unit = \"°C\" if units == \"metric\" else \"°F\"\n    \n    return (\n        f\"{city} 当前天气:\\n\"\n        f\"- 温度: {data['main']['temp']}{temp_unit}\\n\"\n        f\"- 体感温度: {data['main']['feels_like']}{temp_unit}\\n\"\n        f\"- 湿度: {data['main']['humidity']}%\\n\"\n        f\"- 风速: {data['wind'].get('speed', 0)} m/s\\n\"\n        f\"- 天气状况: {data['weather'][0]['description']}\\n\"\n        f\"- 能见度: {data.get('visibility', 'N/A')} m\"\n    )\n\ndef get_forecast(params: dict) -> string:\n    city = params[\"city\"]\n    days = min(max(params.get(\"days\", 3), 1), 7)  # 限制在 1-7 天\n    \n    url = f\"{BASE_URL}/forecast?q={city}&appid={API_KEY}&units=metric&cnt={days * 8}\"  # 每3小时一个数据点\n    \n    response = requests.get(url, timeout=10)\n    \n    if response.status_code != 200:\n        return f\"无法获取预报: {response.json().get('message', '未知错误')}\"\n    \n    data = response.json()\n    \n    result = f\"{city} 未来{days}天预报:\\n\\n\"\n    \n    for item in data[\"list\"][:days * 8]:  # 取前 N 天的数据\n        dt = item[\"dt_txt\"]\n        temp = item[\"main\"][\"temp\"]\n        desc = item[\"weather\"][0][\"description\"]\n        result += f\"{dt}: {temp}°C, {desc}\\n\"\n    \n    return result\n```\n\n### 示例 2：数据库查询插件\n\n```python\n# __init__.py\n\"\"\"Database Query Plugin - 安全地执行 SQL 查询。\"\"\"\n\nimport sqlite3\n\ndef register(ctx):\n    db_schema = {\n        \"name\": \"query_database\",\n        \"description\": \"在 SQLite 数据库中执行只读 SQL 查询\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"db_path\": {\n                    \"type\": \"string\",\n                    \"description\": \"数据库文件路径\"\n                },\n                \"query\": {\n                    \"type\": \"string\",\n                    \"description\": \"SQL SELECT 查询语句\"\n                },\n                \"limit\": {\n                    \"type\": \"integer\",\n                    \"description\": \"最大返回行数（默认100）\",\n                    \"default\": 100\n                }\n            },\n            \"required\": [\"db_path\", \"query\"]\n        }\n    }\n    \n    def execute_query(params: dict) -> str:\n        db_path = params[\"db_path\"]\n        query = params[\"query\"].strip()\n        limit = params.get(\"limit\", 100)\n        \n        # 安全检查：只允许 SELECT 语句\n        if not query.upper().startswith(\"SELECT\"):\n            return \"错误: 只允许 SELECT 查询语句\"\n        \n        # 检查危险关键字\n        dangerous = [\"DROP\", \"DELETE\", \"UPDATE\", \"INSERT\", \"ALTER\", \"--\", \";\"]\n        for word in dangerous:\n            if word.upper() in query.upper():\n                return f\"错误: 查询包含不安全的关键字 '{word}'\"\n        \n        try:\n            conn = sqlite3.connect(db_path)\n            conn.row_factory = sqlite3.Row\n            \n            # 自动添加 LIMIT\n            if \"LIMIT\" not in query.upper():\n                query += f\"\\nLIMIT {limit}\"\n            \n            cursor = conn.execute(query)\n            rows = cursor.fetchall()\n            columns = [desc[0] for desc in cursor.description]\n            \n            conn.close()\n            \n            if not rows:\n                return \"查询返回空结果集\"\n            \n            # 格式化输出为表格\n            header = \" | \".join(columns)\n            separator = \"-+-\".join([\"-\" * len(c) for c in columns])\n            lines = [header, separator]\n            \n            for row in rows[:limit]:\n                line = \" | \".join(str(v) for v in row)\n                lines.append(line)\n                \n            return \"\\n\".join(lines)\n            \n        except sqlite3.Error as e:\n            return f\"SQL 错误: {str(e)}\"\n        except Exception as e:\n            return f\"执行错误: {str(e)}\"\n    \n    ctx.register_tool(\"query_database\", db_schema, execute_query)\n```\n\nFile v2.1.0:references/self-improving-integration.md\n\n# Hermes Agent 与 Self-Improving Agent CN 集成指南\n\n> **版本**: v1.0.0 | **最后更新**: 2026-04-11\n\n## 概述\n\n本集成方案让 Hermes Agent 和 **Self-Improving Agent CN** 形成完整的**正负反馈闭环**：\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    自改进学习循环                             │\n├─────────────────────────────────────────────────────────────┤\n│                                                             │\n│   ┌───────────────────┐     ┌──────────────────────────┐    │\n│   │   Hermes Agent     │     │  Self-Improving Agent   │    │\n│   │                   │     │         CN              │    │\n│   │  ✅ 成功任务 →     │     │  ❌ 失败/纠正 →          │    │\n│   │  提取可复用技能    │ ←→ │  记录错误教训            │    │\n│   │                   │     │                          │    │\n│   │  存储位置:          │     │  存储位置:               │    │\n│   │  ~/.hermes/skills/ │     │  ~/.openclaw/memory/     │    │\n│   └───────────────────┘     │  self-improving/         │    │\n│                             └──────────────────────────┘    │\n│                                                             │\n│   Wrapper/Delegate 脚本自动触发错误回调                       │\n│                                                             │\n└─────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## 集成方式\n\n### 自动错误回调机制（已内置）\n\n`hermes_wrapper.sh` 和 `hermes_delegate.sh` 已内置 `error_callback()` 函数：\n\n**触发条件**:\n1. 命令执行失败（退出码非0）\n2. 任务超时（退出码124）\n3. 并发限制达到\n4. 其他运行时错误\n\n**回调行为**:\n- 将错误信息记录到 `~/.openclaw/memory/self-improving/learnings.jsonl`\n- 包含时间戳、错误类型、任务描述、原始命令等上下文\n- 预留 `lesson` 字段供后续分析填充\n\n### 错误记录格式\n\n```json\n{\n  \"timestamp\": \"2026-04-11T20:46:00Z\",\n  \"error_type\": \"TIMEOUT\",\n  \"error_message\": \"任务执行超时 (300s): 研究竞品产品特性\",\n  \"task\": \"研究竞品产品特性\",\n  \"command\": \"hermes run '...' --non-interactive --no-stream --timeout 300\",\n  \"source\": \"hermes-delegate\",\n  \"context\": {\n    \"hermes_version\": \"Hermes Agent v0.8.0 (2026.4.8)\",\n    \"platform\": \"Darwin\",\n    \"user\": \"chunhaixu\"\n  },\n  \"lesson\": \"TODO: 待分析此错误的根本原因和解决方案\"\n}\n```\n\n---\n\n## 配置与使用\n\n### 启用自动记录（默认启用）\n\n```bash\n# 错误回调默认启用，无需额外配置\n# 记录文件位置: ~/.openclaw/memory/self-improving/learnings.jsonl\n```\n\n### 查看学习记录\n\n```bash\n# 查看所有错误记录\ncat ~/.openclaw/memory/self-improving/learnings.jsonl | jq .\n\n# 按日期过滤\ncat ~/.openclaw/memory/self-improving/learnings.jsonl \\\n  | jq 'select(.timestamp | startswith(\"2026-04\"))'\n\n# 按错误类型统计\ncat ~/.openclaw/memory/self-improving/learnings.jsonl \\\n  | jq -r '.error_type' | sort | uniq -c | sort -rn\n\n# 查看最近的错误\ntail -5 ~/.openclaw/memory/self-improving/learnings.jsonl | jq .\n```\n\n### 手动添加教训（填充 lesson 字段）\n\n当分析出错误原因后，更新记录：\n\n```bash\n# 使用 jq 更新特定记录的 lesson 字段\nRECORD_ID=$(tail -1 learnings.jsonl | jq '.timestamp')\njq \"if .timestamp == \\\"$RECORD_ID\\\" then .lesson = \\\"应该增加超时时间到600秒或简化任务范围\\\" else . end\" \\\n  learnings.jsonl > tmp.jsonl && mv tmp.jsonl learnings.jsonl\n```\n\n### 在 WorkBuddy 中使用\n\nWorkBuddy 加载 self-improving-agent-cn Skill 后会自动：\n\n1. **执行前检查**：读取 `learnings.jsonl` 中的历史错误\n2. **模式匹配**：识别当前任务是否与历史错误相似\n3. **预防性建议**：根据历史教训给出建议\n\n---\n\n## 最佳实践\n\n### 1. 定期审查错误日志\n\n建议每周检查一次学习记录：\n\n```bash\n#!/bin/bash\n# review_errors.sh - 审查本周 Hermes 错误\n\nERROR_FILE=\"$HOME/.openclaw/memory/self-improving/learnings.jsonl\"\nTHIS_WEEK=$(date +%Y-%W)\n\necho \"=== 本周 ($THIS_WEEK) Hermes 错误报告 ===\"\necho \"\"\n\nif [ -f \"$ERROR_FILE\" ]; then\n    # 统计错误数量\n    TOTAL=$(grep -c \"\" \"$ERROR_FILE\" 2>/dev/null || echo 0)\n    \n    # 统计各类错误\n    echo \"📊 错误类型分布:\"\n    cat \"$ERROR_FILE\" | jq -r '.error_type' | sort | uniq -c | sort -rn | while read count type; do\n        echo \"   $count x $type\"\n    done\n    \n    echo \"\"\n    echo \"📝 未解决的教训 (lesson 为 TODO):\"\n    cat \"$ERROR_FILE\" | jq -r 'select(.lesson | startswith(\"TODO\")) | \"- \\(.error_type): \\(.task)\"'\n    \nelse\n    echo \"✅ 无错误记录\"\nfi\n```\n\n### 2. 从错误中提取技能\n\n当同一类型的错误重复出现 3+ 次，考虑将其转化为 Hermes 技能：\n\n```bash\n#!/bin/bash\n# extract_skill_from_errors.sh - 从错误中提取技能模板\n\nERROR_FILE=\"$HOME/.openclaw/memory/self-improving/learnings.jsonl\"\nSKILLS_DIR=\"$HOME/.hermes/skills\"\n\n# 找出最频繁的错误类型\nTOP_ERROR=$(cat \"$ERROR_FILE\" | jq -r '.error_type' | sort | uniq -c | sort -rn | head -1 | awk '{print $2}')\n\necho \"检测到高频错误类型: $TOP_ERROR\"\n\ncase $TOP_ERROR in\n    TIMEOUT)\n        SKILL_NAME=\"timeout-handling\"\n        echo \"建议创建技能: $SKILL_NAME\"\n        \n        mkdir -p \"$SKILLS_DIR/$SKILL_NAME\"\n        cat > \"$SKILLS_DIR/$SKILL_NAME/skill.md\" << EOF\n---\nname: timeout-handling\ndescription: 处理可能超时的长时间任务\ntriggers:\n  - 超时任务\n  - 大量数据查询\n  - 复杂研究\n---\n\n# 超时处理技能\n\n## 策略\n1. **分解任务**: 将大任务拆分为多个小步骤\n2. **设置合理超时**: 简单任务60s, 中等300s, 复杂600s+\n3. **工具集限制**: 只启用必要的工具减少 Token 消耗\n4. **增量保存**: 每完成一步就保存中间结果\n5. **重试机制**: 失败后自动重试1次\n\n## 最佳实践\n\\`\\`\\`bash\n# 推荐参数\nhermes run \"任务\" --toolset web_search --timeout 120\n\\`\\`\\`\nEOF\n        \n        echo \"✅ 技能已创建: $SKILLS_DIR/$SKILL_NAME/skill.md\"\n        ;;\nesac\n```\n\n### 3. 双向同步\n\n让 Hermes 的技能系统和 Self-Improving 的错误系统互相感知：\n\n```python\n# 可选的高级集成代码示例\ndef sync_hermes_with_self_improving():\n    \"\"\"\n    定期同步 Hermes 技能和 Self-Improving 记录\n    \"\"\"\n    import json\n    \n    skills_dir = Path(\"~/.hermes/skills\").expanduser()\n    errors_file = Path(\"~/.openclaw/memory/self-improving/learnings.jsonl\").expanduser()\n    \n    # 1. 将新技能通知给 Self-Improving\n    for skill_file in skills_dir.glob(\"**/skill.md\"):\n        skill_name = skill_file.parent.name\n        # 标记为从成功经验中学到的能力\n        log_success(f\"New skill available: {skill_name}\")\n    \n    # 2. 分析错误模式并建议技能改进\n    if errors_file.exists():\n        with open(errors_file) as f:\n            errors = [json.loads(line) for line in f]\n        \n        # 按错误类型分组\n        from collections import Counter\n        error_types = Counter(e['error_type'] for e in errors)\n        \n        for error_type, count in error_types.most_common(3):\n            if count >= 3 and not any(s.name == f\"{error_type}-handling\" \n                                       for s in list_skills()):\n                suggest_skill_creation(error_type, errors)\n```\n\n---\n\n## 故障排除\n\n### Q: 错误记录文件不存在？\n\n```bash\nmkdir -p ~/.openclaw/memory/self-improving/\ntouch ~/.openclaw/memory/self-improving/learnings.jsonl\n```\n\n### Q: jq 命令不可用？\n\n```bash\n# macOS 安装 jq\nbrew install jq\n\n# 或使用 Python 替代\npython3 -c \"\nimport json\nwith open('learnings.jsonl') as f:\n    for line in f:\n        print(json.dumps(json.loads(line), indent=2))\n\"\n```\n\n### Q: 如何禁用错误回调？\n\n临时禁用：\n```bash\nHERMES_DISABLE_SELF_IMPROVING=true hermes_wrapper.sh run \"prompt\"\n```\n\n永久修改脚本中的 `error_callback()` 调用处即可。\n\n---\n\n## 总结\n\n| 维度 | Hermes Agent | Self-Improving Agent CN |\n|------|--------------|------------------------|\n| **学习来源** | ✅ 成功任务 | ❌ 失败/纠正 |\n| **存储格式** | Markdown 技能文件 | JSONL 记录文件 |\n| **触发时机** | 任务完成后 | 用户纠正/失败时 |\n| **优化频率** | 每15个任务评估 | 每次执行前检查 |\n| **内容类型** | 可复用方法论 | 应避免的错误 |\n\n两者互补，形成**完整的正负反馈闭环**，让 Agent 系统越用越智能！\n\nArchive v2.0.0: 11 files, 48347 bytes\n\nFiles: _meta.json (134b), README.md (3046b), references/cli-commands.md (10824b), references/config-guide.md (13818b), references/mcp-integration.md (15176b), references/plugin-development.md (20512b), references/self-improving-integration.md (9223b), scripts/hermes_delegate.sh (17949b), scripts/hermes_wrapper.sh (15436b), scripts/install_hermes.sh (13599b), SKILL.md (8987b)\n\nFile v2.0.0:SKILL.md\n\n---\nname: hermes-agent\ndescription: |\n  NousResearch Hermes Agent 通用集成 Skill。通过 CLI 调用 Hermes Agent 的核心能力：\n  - 🚀 自改进技能系统（从任务中自动创建可复用技能）\n  - 🧠 持久化记忆（FTS5全文搜索 + LLM摘要）\n  - 🤖 子代理委托（任务隔离和并行处理）\n  - 🔌 MCP 双向集成\n  - 🌐 浏览器自动化\n  - 💻 代码执行\n  - 🔍 网页研究\n  - 📦 完全可移植，支持任意 Claw/WorkBuddy 实例一键安装\n\ntriggers:\n  - \"使用 hermes\"\n  - \"调用 hermes\"\n  - \"hermes agent\"\n  - \"子代理委托\"\n  - \"hermes run\"\n  - \"hermes delegate\"\n  - \"hermes memory\"\n  - \"hermes skills\"\n  - \"让 hermes 帮我\"\n  - \"用 hermes 分析\"\n  - \"安装 hermes\"\n\ncategory: ai-agents\nversion: 2.0.0\nrequires_approval: false\ncost_awareness: |\n  ⚠️ 每次 `hermes run` 调用都会产生 LLM Token 消耗。\n  - 单轮简单问答：约 $0.001-0.01\n  - 复杂任务（含子代理）：约 $0.05-0.50\n  - 建议对复杂任务先评估成本，或限制工具集减少调用次数\n---\n\n# Hermes Agent Skill v2.0\n\n## 概述\n\n本 Skill 封装了 [NousResearch Hermes Agent](https://github.com/NousResearch/hermes-agent) 的 CLI 调用能力，让 WorkBuddy/Claw 可以通过 Shell 命令利用 Hermes 的核心功能。\n\n**v2.0 改进：完全可移植，无硬编码路径，支持任意实例一键安装。**\n\n---\n\n## 首次安装\n\n### 一键安装（推荐）\n\n当检测到 Hermes 未安装时，运行：\n\n```bash\n# 安装 Hermes Agent（自动克隆、创建虚拟环境、创建 CLI 入口）\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n\n# 或自定义安装目录\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh --prefix ~/custom/path\n```\n\n安装脚本会自动：\n1. ✅ 检测 Python 3.11+ 环境\n2. ✅ 克隆 Hermes Agent 源码\n3. ✅ 创建 Python 虚拟环境并安装依赖\n4. ✅ 创建 `~/.local/bin/hermes` CLI 入口\n5. ✅ 初始化 `~/.hermes/` 配置目录\n6. ✅ 生成默认 `.env` 配置模板\n\n### 安装后配置 API Key\n\n```bash\n# 编辑配置文件，填入你的 API Key\nnano ~/.hermes/.env\n```\n\n可选提供商（任选其一）：\n```bash\n# 智谱 AI（推荐国内用户）\nGLM_API_KEY=your-key-here\n\n# OpenRouter（支持多种模型）\nOPENROUTER_API_KEY=sk-or-v1-your-key-here\n\n# Anthropic\nANTHROPIC_API_KEY=sk-ant-your-key-here\n\n# OpenAI\nOPENAI_API_KEY=sk-your-key-here\n```\n\n### 验证安装\n\n```bash\n# 确认 PATH 包含 hermes\nexport PATH=\"$HOME/.local/bin:$PATH\"\nhermes --version\n\n# 运行诊断\nhermes doctor\n```\n\n---\n\n## 迁移到其他 Claw 实例\n\n将整个 Skill 目录复制到目标实例即可：\n\n```bash\n# 在目标实例上执行：\ncp -r /path/to/hermes-agent ~/.workbuddy/skills/hermes-agent\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n# 然后配置 API Key\n```\n\n---\n\n## 核心工作流\n\n### 1. 调用模式速查\n\n| 场景 | 命令 | 说明 |\n|------|------|------|\n| **快速问答** | `hermes run \"问题\" --non-interactive --no-stream` | 最简调用 |\n| **带上下文** | `hermes run \"问题\" --context-file ./ctx.md --non-interactive` | 注入项目上下文 |\n| **子代理委托** | 使用 `scripts/hermes_delegate.sh` | 复杂任务分解 |\n| **技能查询** | `hermes skills list` | 查看已学技能 |\n| **记忆搜索** | `hermes memory search \"关键词\"` | 检索历史知识 |\n| **状态检查** | `hermes status` 或 `hermes doctor` | 诊断安装状态 |\n\n### 2. CLI 命令完整参考\n\n#### 基础命令\n\n```bash\n# 启动交互式对话\nhermes\n\n# 单轮执行（WorkBuddy 集成首选）\nhermes run \"prompt\" [选项]\n\n# 非交互模式选项\n--non-interactive    # 关闭交互式 TUI（必需）\n--no-stream          # 禁用流式输出，返回完整结果\n--context-file PATH  # 注入上下文文件\n--toolset NAME       # 限制使用的工具集\n--model MODEL        # 指定模型\n--timeout SECONDS    # 超时时间（默认300秒）\n```\n\n#### 子代理委托\n\n```bash\n# 通过 wrapper 脚本调用（推荐）\n./scripts/hermes_delegate.sh \\\n  --task \"分析竞品A和B的产品特性\" \\\n  --tools \"web_search,browser,file_write\" \\\n  --timeout 300 \\\n  --output ./result.md\n\n# 直接在 hermes run 中使用 delegate_task 工具\nhermes run '使用delegate_task工具，任务是：分析XXX，工具限制：web_search,browser' \\\n  --non-interactive --no-stream\n```\n\n#### 记忆管理\n\n```bash\n# 搜索历史记忆\nhermes memory search \"关键词\"\n\n# 查看所有笔记\nhermes memory notes list\n\n# 添加手动笔记\nhermes memory notes add \"重要发现：...\"\n\n# 导出/导入记忆\nhermes memory export ./backup/\nhermes memory import ./backup/\n```\n\n#### 技能管理\n\n```bash\nhermes skills list                           # 列出所有技能\nhermes skills create my-skill --description \"描述\"  # 创建新技能\nhermes skills edit my-skill                  # 编辑技能\nhermes skills remove my-skill                # 删除技能\n```\n\n#### 插件管理\n\n```bash\nhermes plugins list                    # 列出插件\nhermes plugins install user/repo       # 安装插件\nhermes plugins enable/disable/update/remove plugin-name\n```\n\n#### 定时任务 (Cron)\n\n```bash\nhermes cron list                       # 列出定时任务\nhermes cron add --name \"日报\" --cron \"0 9 * * *\" --message \"生成总结\"\nhermes cron pause/resume/remove TASK_ID\n```\n\n#### MCP 集成\n\n```bash\nhermes mcp serve --port 8080           # 启动 MCP Server\nhermes mcp connect <server-config>     # 连接外部 MCP 服务\n```\n\n---\n\n## Wrapper 脚本\n\n### scripts/hermes_wrapper.sh\n\n统一的 CLI 封装脚本，提供 JSON 格式化输出和错误处理：\n\n```bash\n./scripts/hermes_wrapper.sh [命令] [参数...]\n\n# 示例\n./scripts/hermes_wrapper.sh run \"分析内容\" --timeout 60\n./scripts/hermes_wrapper.sh memory search \"关键词\"\n./scripts/hermes_wrapper.sh status\n```\n\n**输出格式**：JSON（包含 `success`, `output`, `error`, `duration_ms` 字段）\n\n### scripts/hermes_delegate.sh\n\n子代理委托专用脚本：\n\n```bash\n./scripts/hermes_delegate.sh --task \"任务描述\" [选项]\n\n# 可选选项\n--tools \"tool1,tool2\"      # 限制可用工具集\n--timeout 300              # 超时时间（秒）\n--output ./result.md        # 输出文件路径\n--max-concurrent 3         # 最大并发数（默认3）\n--context-file ./ctx.md     # 额外上下文文件\n-v                         # 详细输出\n```\n\n### scripts/install_hermes.sh\n\n一键安装脚本（详见上方「首次安装」章节）：\n\n```bash\nbash scripts/install_hermes.sh [--skip-deps] [--prefix DIR]\n```\n\n---\n\n## 模型配置\n\n运行交互式配置向导：\n\n```bash\nhermes model\n```\n\n或直接编辑 `~/.hermes/config.yaml`：\n\n```yaml\nmodel:\n  provider: zai           # 可选: openrouter, anthropic, openai, zai, gemini 等\n  default: \"glm-5\"        # 默认模型\n  base_url: \"https://api.z.ai/api/paas/v4\"  # 自定义 API 地址\n```\n\n**支持的提供商**：openrouter, anthropic, openai, gemini, zai, kimi-coding, nous, custom\n\n---\n\n## 最佳实践\n\n### ✅ 推荐做法\n\n1. **始终使用 `--non-interactive --no-stream`**：避免 TUI 阻塞\n2. **设置合理的超时时间**：简单任务 60s，复杂任务 300s\n3. **限制工具集**：用 `--toolset` 减少 Token 消耗\n4. **使用上下文文件**：将大段背景信息放入文件，而非 prompt 中\n5. **错误重试机制**：网络问题时自动重试 1-2 次\n\n### ⚠️ 注意事项\n\n1. **Token 成本**：每次调用都有成本\n2. **并发限制**：最多 3 个并发子代理\n3. **超时保护**：长时间运行的任务必须设置 timeout\n4. **API Key 安全**：不要在 Skill 文件中硬编码密钥\n5. **Python 版本**：确保使用 Python 3.11+\n\n---\n\n## 故障排除\n\n| 问题 | 解决方案 |\n|------|----------|\n| `command not found: hermes` | 运行 `export PATH=\"$HOME/.local/bin:$PATH\"` 或重新执行 `install_hermes.sh` |\n| `TypeError: unsupported operand` | 确保 Python 3.11+ |\n| API Key 错误 | 检查 `~/.hermes/.env` 配置 |\n| 连接超时 | 检查网络，或更换 LLM 提供商 |\n| 子代理失败 | 减少 `--max-concurrent` 或增加 `--timeout` |\n| 安装脚本失败 | 运行 `hermes doctor` 诊断 |\n\n---\n\n## 文件结构\n\n```\nhermes-agent/\n├── SKILL.md                    # 本文件（Skill 说明文档）\n├── _meta.json                  # Skill 元数据（可移植性声明）\n├── scripts/\n│   ├── install_hermes.sh       # 一键安装脚本（通用）\n│   ├── hermes_wrapper.sh       # 统一 CLI 封装（动态路径检测）\n│   └── hermes_delegate.sh      # 子代理委托脚本（动态路径检测）\n└── references/                 # 参考文档\n```\n\n---\n\n## 更新日志\n\n- **v2.0.0** (2026-04-12): 完全可移植版 — 移除所有硬编码路径，添加一键安装脚本，支持任意 Claw 实例迁移\n- **v1.0.0** (2026-04-11): 初始版本，支持基础 CLI 调用、子代理委托、记忆/技能管理\n\nFile v2.0.0:README.md\n\n# Hermes Agent Skill 🏥\n\n> 通用可移植的 Hermes Agent 集成 Skill，适用于 WorkBuddy / Claude Code / Cursor 等 AI Agent 平台。\n\n[![Version](https://img.shields.io/badge/version-2.0.0-blue)]()\n[![License](https://img.shields.io/badge/license-MIT-green)]()\n[![Hermes](https://img.shields.io/badge/Hermes-v0.8.0-purple)]()\n\n## ✨ 功能特性\n\n- 🚀 **自改进技能系统** — 从任务中自动创建可复用技能\n- 🧠 **持久化记忆** — FTS5 全文搜索 + LLM 摘要\n- 🤖 **子代理委托** — 任务隔离和并行处理\n- 🔌 **MCP 双向集成** — Model Context Protocol 支持\n- 🌐 **浏览器自动化** — Web 页面交互\n- 💻 **代码执行** — 沙盒内安全执行\n- 🔍 **网页研究** — 信息检索与分析\n\n## 📦 安装\n\n### 方式一：一键安装（推荐）\n\n```bash\nnpx skills add chunhaixu/hermes-agent-skill@hermes-agent -g -y\n```\n\n### 方式二：手动安装\n\n```bash\n# 1. 克隆仓库\ngit clone https://github.com/chunhaixu/hermes-agent-skill.git\n\n# 2. 复制到 Skill 目录\ncp -r hermes-agent-skill ~/.workbuddy/skills/hermes-agent\n\n# 3. 运行安装脚本\nbash ~/.workbuddy/skills/hermes-agent/scripts/install_hermes.sh\n\n# 4. 配置 API Key\nnano ~/.hermes/.env\n```\n\n## ⚙️ 配置\n\n### API Key 配置\n\n编辑 `~/.hermes/.env`，添加你的 LLM 提供商密钥：\n\n```bash\n# 智谱 AI（推荐）\nGLM_API_KEY=your_key_here\n\n# 或 OpenRouter\nOPENROUTER_API_KEY=your_key_here\n\n# 或 Anthropic\nANTHROPIC_API_KEY=your_key_here\n```\n\n### 模型配置\n\n编辑 `~/.hermes/config.yaml`：\n\n```yaml\nmodel:\n  default: \"glm-5\"          # 默认模型\n  provider: \"zai\"           # 提供商: zai / openrouter / anthropic / ...\n  base_url: \"https://api.z.ai/api/paas/v4\"\n```\n\n## 🔧 使用\n\n安装后，在 AI Agent 中使用以下触发词：\n\n| 触发词 | 说明 |\n|--------|------|\n| `使用 hermes` | 激活 Hermes Agent |\n| `hermes run \"任务\"` | 执行单轮任务 |\n| `hermes memory search \"关键词\"` | 搜索记忆 |\n| `hermes delegate \"复杂任务\"` | 子代理委托 |\n| `hermes skills list` | 查看已学技能 |\n\n## 🏗️ 项目结构\n\n```\nhermes-agent-skill/\n├── SKILL.md              # Skill 描述文件（Agent 自动加载）\n├── _meta.json            # 元数据（版本、依赖、触发词等）\n├── scripts/\n│   ├── install_hermes.sh    # 一键安装脚本\n│   ├── hermes_wrapper.sh    # CLI 统一封装\n│   └── hermes_delegate.sh   # 子代理委托脚本\n└── references/\n    ├── cli-commands.md           # CLI 命令参考\n    ├── config-guide.md           # 配置指南\n    ├── mcp-integration.md        # MCP 集成\n    ├── plugin-development.md     # 插件开发\n    └── self-improving-integration.md  # 自改进系统\n```\n\n## 🔗 相关链接\n\n- [Hermes Agent 官方仓库](https://github.com/NousResearch/hermes-agent)\n- [Skills.sh - Agent Skill 生态](https://skills.sh/)\n- [智谱 AI 开放平台](https://open.bigmodel.cn)\n\n## 📄 License\n\nMIT License\n\nFile v2.0.0:_meta.json\n\n{\n  \"ownerId\": \"kn75neczzxsdbx7djhh1kn544182nsbj\",\n  \"slug\": \"hermes-agent-v2\",\n  \"version\": \"2.0.0\",\n  \"publishedAt\": 1775957183386\n}\n\nFile v2.0.0:references/cli-commands.md\n\n# Hermes Agent CLI 完整命令手册\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [基础命令](#基础命令)\n2. [执行模式](#执行模式)\n3. [工具管理](#工具管理)\n4. [记忆系统](#记忆系统)\n5. [技能管理](#技能管理)\n6. [插件系统](#插件系统)\n7. [消息网关](#消息网关)\n8. [定时任务](#定时任务)\n9. [MCP 集成](#mcp-集成)\n10. [诊断与调试](#诊断与调试)\n\n---\n\n## 基础命令\n\n### 启动交互式会话\n\n```bash\nhermes\n```\n\n启动 TUI（终端用户界面）交互式对话。\n\n**快捷键**:\n- `Ctrl+C` - 中断当前生成\n- `Ctrl+D` - 退出\n- `Tab` - 自动补全\n- `↑/↓` - 历史记录\n\n### 查看版本信息\n\n```bash\nhermes --version\nhermes -v\n\n# 输出示例:\n# Hermes Agent v0.8.0 (2026.4.8)\n# Project: /path/to/hermes-agent\n# Python: 3.11.15\n# OpenAI SDK: 2.31.0\n```\n\n### 显示帮助信息\n\n```bash\nhermes --help\nhermes help <command>\n```\n\n---\n\n## 执行模式\n\n### 单轮执行 (run)\n\n```bash\nhermes run \"你的提示词\" [选项]\n```\n\n**核心选项**:\n\n| 选项 | 简写 | 默认值 | 说明 |\n|------|------|--------|------|\n| `--non-interactive` | 无 | false | 关闭 TUI，适合脚本调用 |\n| `--no-stream` | 无 | false | 禁用流式输出，返回完整结果 |\n| `--context-file` | `-c` | null | 注入上下文文件路径 |\n| `--toolset` | `-t` | null | 限制使用的工具集名称 |\n| `--model` | `-m` | 配置默认值 | 指定模型（覆盖配置） |\n| `--provider` | 无 | 配置默认值 | 指定 LLM 提供商 |\n| `--timeout` | 无 | 300 | 超时时间（秒） |\n| `--max-tokens` | 无 | 配置默认值 | 最大输出 Token 数 |\n| `--temperature` | 无 | 配置默认值 | 温度参数 (0.0-2.0) |\n\n**使用示例**:\n\n```bash\n# 最简单的单轮调用\nhermes run \"什么是机器学习？\" --non-interactive --no-stream\n\n# 带上下文文件\nhermes run \"分析这个项目的架构\" \\\n  --context-file ./AGENTS.md \\\n  --non-interactive --no-stream\n\n# 限制工具集\nhermes run \"搜索最新的 React 文档\" \\\n  --toolset web_search \\\n  --non-interactive --no-stream\n\n# 指定模型和超时\nhermes run \"写一个排序算法\" \\\n  --model gpt-4o \\\n  --temperature 0.2 \\\n  --timeout 60 \\\n  --non-interactive --no-stream\n```\n\n---\n\n## 工具管理\n\n### 列出所有可用工具\n\n```bash\nhermes tools list\nhermes tools list --all    # 包括未启用的\n```\n\n### 启用/禁用工具集\n\n```bash\n# 列出可用工具集\nhermes toolsets\n\n# 启用特定工具集\nhermes tools enable web_search browser file_operations\n\n# 禁用特定工具集\nhermes tools disable code_execution terminal\n```\n\n### 内置工具列表\n\n| 工具集 | 包含工具 | 用途 |\n|--------|----------|------|\n| `web_search` | search_web, firecrawl_scrape, brave_search, searxng_search | 网页搜索和抓取 |\n| `browser` | browser_navigate, browser_click, browser_type, browser_screenshot, browser_extract | 浏览器自动化 |\n| `file_operations` | read_file, write_file, edit_file, glob_files, list_directory | 文件读写操作 |\n| `terminal` | execute_command, bash, shell | 终端命令执行 |\n| `memory` | memory_search, memory_add_note, memory_list_notes | 记忆系统访问 |\n| `code_execution` | execute_code | 代码执行沙盒 |\n| `delegation` | delegate_task | 子代理委托 |\n| `skills` | skills_list, skills_create, skills_edit, skills_remove | 技能管理 |\n| `image_generation` | generate_image, upscale_image | AI 图像生成 |\n| `voice` | text_to_speech, transcribe_audio | 语音合成与识别 |\n\n---\n\n## 记忆系统\n\n### 搜索记忆\n\n```bash\nhermes memory search \"关键词\"\nhermes memory search \"用户偏好设置\" --limit 10\n```\n\n### 笔记管理\n\n```bash\n# 列出所有笔记\nhermes memory notes list\n\n# 添加新笔记\nhermes memory notes add \"重要发现：XXX\"\n\n# 搜索笔记内容\nhermes memory notes search \"查询内容\"\n```\n\n### 导入导出\n\n```bash\n# 导出所有记忆数据\nhermes memory export ./backup/\n\n# 从备份导入\nhermes memory import ./backup/\n```\n\n### 记忆后端切换\n\n```bash\n# 查看当前记忆后端\nhermes memory status\n\n# 切换到 Honcho 后端\nhermes memory setup honcho\n\n# 使用内置后端\nhermes memory setup built-in\n```\n\n**支持的记忆后端**:\n\n| 后端 | 特点 |\n|------|------|\n| `built-in` | 默认，SQLite + FTS5 全文搜索 |\n| `honcho` | AI 原生记忆，方言建模 |\n| `mem0` | 开源记忆服务 |\n| `openviking` | 高级向量检索 |\n| `hindsight` | 时间线记忆 |\n| `holographic` | 全息记忆系统 |\n| `retaindb` | 企业级记忆存储 |\n| `byte-rover` | 轻量级本地记忆 |\n\n---\n\n## 技能管理\n\n### 列出技能\n\n```bash\nhermes skills list\nhermes skills ls           # 短形式\n\n# 查看技能详情\nhermes skills show skill-name\n```\n\n### 创建技能\n\n```bash\n# 交互式创建\nhermes skills create my-skill\n\n# 带描述创建\nhermes skills create research-methodology \\\n  --description \"系统性网页研究方法论\"\n\n# 从模板创建\nhermes skills create code-review --template default\n```\n\n### 编辑技能\n\n```bash\nhermes skills edit my-skill\n# 打开默认编辑器编辑技能 Markdown 文件\n```\n\n### 删除技能\n\n```bash\nhermes skills remove my-skill\nhermes skills rm old-skill   # 短形式\n```\n\n### 技能格式规范\n\n每个技能是一个 Markdown 文件，位于 `~/.hermes/skills/<skill-name>/skill.md`：\n\n```markdown\n---\nname: my-skill\ndescription: 技能描述\ntriggers:\n  - \"触发词1\"\n  - \"触发词2\"\ntags:\n  - category1\n  - category2\n---\n\n# 技能名称\n\n## 步骤\n1. 第一步说明\n2. 第二步说明\n\n## 最佳实践\n- 注意事项\n- 推荐做法\n```\n\n---\n\n## 插件系统\n\n### 插件管理\n\n```bash\n# 列出已安装插件\nhermes plugins list\nhermes plugins ls\n\n# 安装插件（从 Git）\nhermes plugins install owner/repo\nhermes plugins install https://github.com/owner/repo.git\n\n# 更新插件\nhermes plugins update plugin-name\nhermes plugins update --all    # 更新所有\n\n# 卸载插件\nhermes plugins remove plugin-name\nhermes plugins rm plugin-name\n\n# 启用/禁用插件（保留安装但不加载）\nhermes plugins enable plugin-name\nhermes plugins disable plugin-name\n```\n\n### 插件类型\n\n```bash\n# 列出通用插件\nhermes plugins list --type general\n\n# 列出内存提供者\nhermes plugins list --type memory\n\n# 列出上下文引擎\nhermes plugins list --type context_engine\n```\n\n### 插件开发\n\n详见 [plugin-development.md](./plugin-development.md)\n\n---\n\n## 消息网关\n\n### 网关管理\n\n```bash\n# 设置向导\nhermes gateway setup\n\n# 列出已配置的网关\nhermes gateway list\n\n# 安装特定平台网关\nhermes gateway install telegram\nhermes gateway install discord\nhermes gateway install slack\n\n# 启动所有网关\nhermes gateway start\n\n# 停止所有网关\nhermes gateway stop\n\n# 重启特定网关\nhermes gateway restart discord\n```\n\n### 支持的消息平台\n\n| 平台 | 网关名称 | 功能 |\n|------|----------|------|\n| Telegram | `telegram` | 完整支持（文字、语音、群组） |\n| Discord | `discord` | 完整支持（含语音频道） |\n| Slack | `slack` | 支持 |\n| WhatsApp | `whatsapp` | 支持 |\n| Signal | `signal` | 支持 |\n| Matrix | `matrix` | 支持 |\n| Mattermost | `mattermost` | 支持 |\n| Email | `email` | 支持 |\n| SMS | `sms` | 支持 |\n| DingTalk (钉钉) | `dingtalk` | 支持 |\n| Feishu (飞书) | `feishu` | 支持 |\n| WeCom (企业微信) | `wecom` | 支持 |\n| Home Assistant | `homeassistant` | 支持 |\n\n---\n\n## 定时任务 (Cron)\n\n### 任务管理\n\n```bash\n# 列出所有任务\nhermes cron list\n\n# 创建任务\nhermes cron add \\\n  --name \"每日新闻摘要\" \\\n  --cron \"0 9 * * *\" \\          # 每天 9:00\n  --message \"总结今日科技新闻\" \\\n  --skill daily-news             # 可附加技能\n\n# 暂停任务\nhermes cron pause TASK_ID 或 任务名\n\n# 恢复任务\nhermes cron resume TASK_ID 或 任务名\n\n# 编辑任务\nhermes cron edit TASK_ID\n\n# 删除任务\nhermes cron remove TASK_ID\nhermes cron rm TASK_ID            # 短形式\n\n# 手动触发任务\nhermes cron run TASK_ID\n```\n\n### Cron 表达式语法\n\n```\n┌───────────── 分钟 (0-59)\n│ ┌───────────── 小时 (0-23)\n│ │ ┌───────────── 月中天 (1-31)\n│ │ │ ┌───────────── 月 (1-12)\n│ │ │ │ ┌───────────── 周中天 (0-6, 0=周日)\n│ │ │ │ │\n* * * * *\n```\n\n**示例**:\n\n| 表达式 | 含义 |\n|--------|------|\n| `* * * * *` | 每分钟 |\n| `*/15 * * * *` | 每15分钟 |\n| `0 * * * *` | 每小时 |\n| `0 9 * * *` | 每天 9:00 |\n| `0 9 * * 1` | 每周一 9:00 |\n| `0 9 1 * *` | 每月1号 9:00 |\n| `0 9-17 * * 1-5` | 工作日 9:00-17:00 每小时 |\n\n---\n\n## MCP 集成\n\n### Server 模式（暴露能力给 IDE）\n\n```bash\n# 启动 MCP Server\nhermes mcp serve --port 8080\nhermes mcp serve --stdio        # 标准输入输出模式\n\n# 配置 MCP Server\nhermes mcp serve-config         # 生成 IDE 配置片段\n```\n\n### Client 模式（连接外部服务）\n\n```bash\n# 连接外部 MCP 服务器\nhermes mcp connect <server-config-json>\n\n# 列出已连接的 MCP 服务\nhermes mcp list\n\n# 断开连接\nhermes mcp disconnect <server-id>\n```\n\n详见 [mcp-integration.md](./mcp-integration.md)\n\n---\n\n## 诊断与调试\n\n### 状态检查\n\n```bash\n# 快速状态概览\nhermes status\n\n# 详细诊断\nhermes doctor\n```\n\n### 日志查看\n\n```bash\n# 实时查看日志\nhermes logs --follow\nhermes logs -f\n\n# 查看最近N行\nhermes logs -n 100\n\n# 过滤日志级别\nhermes logs --level ERROR\nhermes logs --level WARNING\n\n# 查看特定会话的日志\nhermes logs --session SESSION_ID\n```\n\n### 性能分析\n\n```bash\n# 查看最近的性能指标\nhermes stats\n\n# 查看Token使用统计\nhermes stats tokens\n\n# 查看任务耗时统计\nhermes stats timing\n```\n\n### 重置与清理\n\n```bash\n# 清理缓存\nhermes cleanup cache\n\n# 清理旧会话（超过N天的）\nhermes cleanup sessions --older-than 30\n\n# 重置为出厂设置（⚠️ 会删除所有数据和配置）\nhermes reset --factory\n```\n\n---\n\n## 环境变量\n\n| 变量名 | 说明 | 默认值 |\n|--------|------|--------|\n| `HERMES_HOME` | Hermes 数据目录 | `~/.hermes` |\n| `HERMES_CONFIG` | 自定义配置文件路径 | `~/.hermes/config.yaml` |\n| `HERMES_ENV_FILE` | 自定义环境变量文件 | `~/.hermes/.env` |\n| `HERMES_LOG_LEVEL` | 日志级别 | INFO |\n| `HERMES_NO_COLOR` | 禁用彩色输出 | false |\n| `HERMES_ENABLE_PROJECT_PLUGINS` | 启用项目级插件 | false |\n| `HERMES_OPTIONAL_SKILLS` | 自定义可选技能目录 | null |\n\n---\n\n## 退出码\n\n| 退出码 | 含义 |\n|--------|------|\n| 0 | 成功 |\n| 1 | 一般错误 |\n| 2 | 参数错误 |\n| 3 | 配置错误 |\n| 4 | 网络错误 |\n| 5 | API 认证失败 |\n| 124 | 超时（来自 timeout 命令） |\n| 130 | 用户中断 (Ctrl+C) |\n\nFile v2.0.0:references/config-guide.md\n\n# Hermes Agent 配置指南\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [API Key 配置](#api-key-配置)\n2. [模型配置](#模型配置)\n3. [提供商设置](#提供商设置)\n4. [工具集配置](#工具集配置)\n5. [记忆系统配置](#记忆系统配置)\n6. [网关配置](#网关配置)\n7. [安全配置](#安全配置)\n8. [完整配置示例](#完整配置示例)\n\n---\n\n## API Key 配置\n\n### 环境变量文件 (`~/.hermes/.env`)\n\n这是存储所有敏感凭证的主要位置。**不要将此文件提交到版本控制系统！**\n\n```bash\n# ========================================\n# 必需：至少配置一个 LLM 提供商\n# ========================================\n\n# OpenRouter（推荐，支持 200+ 模型）\nOPENROUTER_API_KEY=sk-or-v1-your-key-here\n\n# 或使用其他提供商：\n# Anthropic (Claude)\nANTHROPIC_API_KEY=sk-ant-your-key-here\n\n# OpenAI (GPT-4o, etc.)\nOPENAI_API_KEY=sk-openai-your-key-here\n\n# Google (Gemini)\nGOOGLE_API_KEY=your-google-api-key\n\n# ========================================\n# 可选：增强功能\n# ========================================\n\n# Firecrawl - 高级网页抓取（比内置搜索更强大）\nFIRECRAWL_API_KEY=fc-your-firecrawl-key\n\n# FAL.ai - 图像生成（FLUX 模型）\nFAL_KEY=your-fal-api-key\n\n# ElevenLabs - 高级语音合成（替代免费的 Edge TTS）\nELEVENLABS_API_KEY=your-elevenlabs-key\n\n# Brave Search - 网页搜索\nBRAVE_API_KEY=your-brave-search-key\n\n# OpenWeatherMap - 天气查询\nOPENWEATHERMAP_API_KEY=your-weather-key\n\n# GitHub Token - 用于 GitHub 集成\nGITHUB_TOKEN=ghp_your-github-token\n\n# ========================================\n# 可选：消息平台\n# ========================================\n\n# Telegram Bot\nTELEGRAM_BOT_TOKEN=your-telegram-bot-token\n\n# Discord Bot\nDISCORD_BOT_TOKEN=your-discord-bot-token\n\n# Slack Bot\nSLACK_BOT_TOKEN=xoxb-your-slack-bot-token\nSLACK_APP_TOKEN=xapp-your-slack-app-token\n\n# WhatsApp Bridge (需要单独配置)\n# 参考文档: https://hermes-agent.nousresearch.com/docs/gateways/whatsapp/\n```\n\n### 获取 API Key 的途径\n\n| 服务 | 获取地址 | 免费额度 |\n|------|----------|----------|\n| **OpenRouter** | https://openrouter.ai/keys | 注册即送少量额度 |\n| **Anthropic** | https://console.anthropic.com/ | 新用户 $5 免费 |\n| **OpenAI** | https://platform.openai.com/api-keys | 新用户 $5 免费 |\n| **Google AI** | https://aistudio.google.com/apikey | 免费层可用 |\n| **Firecrawl** | https://www.firecrawl.dev/account | 500 次免费抓取 |\n| **FAL.ai** | https://fal.ai/dashboard/keys | 每日免费额度 |\n| **ElevenLabs** | https://elevenlabs.io/app/settings/api-keys | 每月 10k 字符免费 |\n| **Brave Search** | https://brave.com/search/api/ | 每月 2k 次免费 |\n\n---\n\n## 模型配置\n\n### 通过 CLI 选择模型\n\n```bash\n# 启动交互式模型选择向导\nhermes model\n```\n\n### 通过配置文件指定模型\n\n编辑 `~/.hermes/config.yaml`:\n\n```yaml\nmodel:\n  # LLM 提供商\n  provider: openrouter\n  \n  # 模型名称\n  # OpenRouter 格式: <provider>/<model-name>\n  model: anthropic/claude-sonnet-4-20250514\n  \n  # 或直接使用提供商原生名称:\n  # model: claude-3-5-sonnet-20241022    # Anthropic 直接调用\n  # model: gpt-4o                        # OpenAI 直接调用\n  \n  # 温度参数 (0.0 = 确定性, 2.0 = 最大随机性)\n  temperature: 0.7\n  \n  # 最大输出 token 数\n  max_tokens: 4096\n  \n  # Top P 采样参数\n  top_p: 1.0\n  \n  # 是否启用流式输出\n  streaming: true\n```\n\n### 推荐模型选择\n\n#### 性价比优先\n\n| 模型 | 成本 ($/1M tokens) | 特点 |\n|------|---------------------|------|\n| `openrouter/google/gemini-flash-1.5` | ~$0.07 | 最便宜，速度快 |\n| `openrouter/meta-llama/llama-3.1-8b-instruct:free` | 免费 | 开源，适合简单任务 |\n| `anthropic/claude-haiku-4-5-20251001` | ~$0.80 | 快速，质量好 |\n\n#### 质量优先\n\n| 模型 | 成本 ($/1M tokens) | 特点 |\n|------|---------------------|------|\n| `anthropic/claude-sonnet-4-20250514` | ~$3.00 | 平衡质量和成本 |\n| `openai/gpt-4o` | ~$2.50 | 多模态能力强 |\n| `google/gemini-2.5-pro` | ~$6.25 | 推理能力强，长上下文 |\n\n#### 专业用途\n\n| 用途 | 推荐模型 | 原因 |\n|------|----------|------|\n| 代码生成 | `anthropic/claude-sonnet-4-20250514` | 代码能力优秀 |\n| 网页研究 | `google/gemini-2.5-pro` | 大上下文窗口 |\n| 创意写作 | `openai/gpt-4o` | 文学风格多样 |\n| 快速问答 | `anthropic/claude-haiku-4-5-20251001` | 响应快，成本低 |\n| 数据分析 | `openai/o4-mini` | 推理能力强 |\n\n---\n\n## 提供商设置\n\n### OpenRouter（推荐）\n\n```yaml\nproviders:\n  openrouter:\n    base_url: \"https://openrouter.ai/api/v1\"\n    api_key_env: OPENROUTER_API_KEY  # 从 .env 读取\n    models:\n      default: \"anthropic/claude-sonnet-4-20250514\"\n    \n    # 高级选项\n    timeout: 120                    # 请求超时（秒）\n    max_retries: 3                  # 重试次数\n    \n    # HTTP Headers（可选）\n    extra_headers:\n      X-Title: \"Hermes Agent\"\n      HTTP-Referer: \"http://localhost:8080\"\n```\n\n### Anthropic 直接连接\n\n```yaml\nproviders:\n  anthropic:\n    api_key_env: ANTHROPIC_API_KEY\n    models:\n      default: \"claude-sonnet-4-20250514\"\n    base_url: \"https://api.anthropic.com\"\n```\n\n### OpenAI 直接连接\n\n```yaml\nproviders:\n  openai:\n    api_key_env: OPENAI_API_KEY\n    models:\n      default: \"gpt-4o\"\n    base_url: \"https://api.openai.com/v1\"\n```\n\n### Ollama（本地模型，零成本）\n\n```yaml\nproviders:\n  ollama:\n    base_url: \"http://localhost:11434/v1\"\n    models:\n      default: \"llama3.1:8b\"        # 需先运行 ollama pull llama3.1:8b\n    api_key: \"ollama\"               # Ollama 不需要真实 API Key\n    # 无需 API Key，完全离线运行\n```\n\n---\n\n## 工具集配置\n\n### 启用/禁用工具集\n\n```yaml\ntools:\n  # 全局默认启用状态\n  enabled_by_default: true\n  \n  # 工具集定义\n  toolsets:\n    web_search:\n      enabled: true\n      tools:\n        - search_web\n        - firecrawl_scrape\n        \n    browser:\n      enabled: true\n      backend: local_chrome       # browserbase_cloud | browser_use_cloud | local_chrome | local_chromium\n      \n    file_operations:\n      allowed_paths:\n        - /Users/chunhaixu/Projects\n        - /tmp\n        - ~/Documents\n      denied_paths:\n        - ~/.ssh\n        - ~/.gnupg\n        - /etc\n        \n    terminal:\n      allowed_commands:\n        - git\n        - npm\n        - python\n        - cat\n        - ls\n        - grep\n        - find\n      denied_commands:\n        - rm -rf /\n        - sudo\n        - chmod 777\n        \n    memory:\n      enabled: true\n      backend: built-in           # built-in | honcho | mem0 | ...\n      \n    code_execution:\n      enabled: true\n      sandbox: docker             # docker | subprocess\n      \n    delegation:\n      enabled: true\n      max_concurrent: 3          # 最大并发子代理数\n      default_timeout: 300        # 默认超时（秒）\n      \n    image_generation:\n      enabled: false              # 需要 FAL_KEY\n      provider: fal               # fal | ...\n      model: flux-2-pro          \n      upscale: true               # 自动 2x 放大\n      \n    voice:\n      enabled: true\n      tts_provider: edge_tts      # edge_tts | elevenlabs | openai_tts | minimax | neutts\n      stt_provider: whisper       # whisper | groq_whisper\n```\n\n---\n\n## 记忆系统配置\n\n```yaml\nmemory:\n  # 后端选择\n  provider: built-in             # built-in | honcho | mem0 | openviking | hindsight | holographic | retaindb | byte-rover\n  \n  # 内置后端特定配置\n  built_in:\n    storage_path: ~/.hermes/memory\n    fts_enabled: true            # 启用全文搜索\n    max_notes: 10000             # 最大笔记数\n    auto_summarize: true         # 自动摘要旧会话\n    summary_model: haiku         # 用于摘要的模型\n    \n  # Honcho 后端（如果使用）\n  honcho:\n    project_id: your-project-id\n    dialect_name: user-profile   # 用户方言文件名\n    \n  # 记忆保留策略\n  retention:\n    hot_memory_days: 7           # 热记忆保留天数\n    session_history_days: 30     # 会话历史保留天数\n    cold_storage_after: 90       # 天数后归档\n    auto_prune: true             # 自动清理过期记忆\n```\n\n---\n\n## 网关配置\n\n### Telegram 示例\n\n```yaml\ngateway:\n  telegram:\n    enabled: true\n    bot_token_env: TELEGRAM_BOT_TOKEN\n    allowed_users:                # 限制可用的用户 ID（可选）\n      - 123456789\n    allowed_groups:               # 限制群组（可选）\n      - -1001234567890\n    commands:\n      start: \"欢迎使用 Hermes Agent！输入你的问题开始对话。\"\n      help: \"可用命令：\\n/ask <问题>\\n/memory search <关键词>\\n/status\"\n    features:\n      voice: true                 # 支持语音消息\n      image_analysis: true        # 分析图片\n      inline_queries: true        # 内联模式\n```\n\n### Discord 示例\n\n```yaml\ngateway:\n  discord:\n    enabled: true\n    bot_token_env: DISCORD_BOT_TOKEN\n    command_prefix: \"!\"           # 命令前缀\n    allowed_guilds:              # 限制服务器\n      - \"123456789012345678\"\n    voice_channels:              # 支持语音频道\n      enabled: true\n    features:\n      slash_commands: true       # 斜杠命令\n      context_menus: true        # 右键菜单\n      message_content: true      # 内容意图（需在 Discord 开发者门户开启）\n```\n\n---\n\n## 安全配置\n\n```yaml\nsecurity:\n  # 提示注入防护\n  prompt_injection_protection:\n    enabled: true                 # v0.7.0+ 默认开启\n    strictness: medium            # low | medium | high\n    \n  # 凭证过滤\n  credential_filtering:\n    enabled: true\n    patterns:                    # 要过滤的模式\n      - \"(?i)(api[_-]?key|token|secret|password)[=:]\\s*\\S+\"\n      - \"sk-[a-zA-Z0-9]{20,}\"\n      - \"ghp_[a-zA-Z0-9]{36}\"\n      \n  # 工具权限控制\n  tool_permissions:\n    terminal:\n      require_confirmation:\n        - \"rm \"\n        - \"sudo\"\n        - \"chmod 777\"\n        - \"curl.*\\\\| bash\"\n        \n  # 日志审计\n  audit_logging:\n    enabled: true\n    log_tool_calls: true\n    log_file_access: true\n    log_network_requests: true\n    \n  # 网络访问控制\n  network:\n    allowed_domains:             # 白名单（留空则允许所有）\n      - \"*.openai.com\"\n      - \"*.anthropic.com\"\n      - \"*.openrouter.ai\"\n    blocked_domains:              # 黑名单\n      - \"*.malicious-site.com\"\n```\n\n---\n\n## 完整配置示例\n\n这是一个生产就绪的完整配置示例：\n\n```yaml\n# ============================================\n# Hermes Agent 完整配置示例\n# 文件位置: ~/.hermes/config.yaml\n# ============================================\n\n# --- 核心模型设置 ---\nmodel:\n  provider: openrouter\n  model: anthropic/claude-sonnet-4-20250514\n  temperature: 0.7\n  max_tokens: 8192\n  top_p: 1.0\n  streaming: true\n\n# --- 提供商 ---\nproviders:\n  openrouter:\n    base_url: \"https://openrouter.ai/api/v1\"\n    api_key_env: OPENROUTER_API_KEY\n    timeout: 120\n    max_retries: 3\n    extra_headers:\n      X-Title: \"My Hermes Instance\"\n\n# --- 工具集 ---\ntools:\n  enabled_by_default: true\n  toolsets:\n    web_search:\n      enabled: true\n    browser:\n      enabled: true\n      backend: local_chrome\n    file_operations:\n      allowed_paths:\n        - ~/Projects\n        - /tmp\n        - ~/Documents\n      denied_paths:\n        - ~/.ssh\n        - ~/.gnupg\n    terminal:\n      enabled: true\n      allowed_commands:\n        - git\n        - npm\n        - python\n        - node\n        - make\n        - cat\n        - ls\n        - grep\n        - find\n        - head\n        - tail\n        - wc\n        - sed\n        - awk\n    memory:\n      enabled: true\n      provider: built-in\n    code_execution:\n      enabled: true\n    delegation:\n      enabled: true\n      max_concurrent: 3\n      default_timeout: 300\n    image_generation:\n      enabled: false\n    voice:\n      enabled: true\n      tts_provider: edge_tts\n\n# --- 记忆系统 ---\nmemory:\n  provider: built-in\n  retention:\n    hot_memory_days: 7\n    session_history_days: 30\n    cold_storage_after: 90\n    auto_prune: true\n\n# --- 安全 ---\nsecurity:\n  prompt_injection_protection:\n    enabled: true\n    strictness: medium\n  credential_filtering:\n    enabled: true\n  tool_permissions:\n    terminal:\n      require_confirmation:\n        - \"rm -rf\"\n        - \"sudo\"\n        - \"curl.*\\\\| bash\"\n        - \"wget.*\\\\| sh\"\n  audit_logging:\n    enabled: true\n\n# --- 网关（按需启用）---\ngateway:\n  telegram:\n    enabled: false\n  discord:\n    enabled: false\n\n# --- UI 设置 ---\nui:\n  theme: dark                   # dark | light\n  color_output: true\n  show_thinking: false         # 显示推理过程\n  timestamp_format: \"%Y-%m-%d %H:%M:%S\"\n```\n\n---\n\n## 常见配置问题\n\n### Q: 如何切换模型？\n\n```bash\n# 方法1：交互式\nhermes model\n\n# 方法2：命令行临时覆盖\nhermes run \"prompt\" --model gpt-4o --non-interactive\n\n# 方法3：编辑配置文件\nnano ~/.hermes/config.yaml  # 修改 model.model 字段\n```\n\n### Q: 如何降低成本？\n\n1. 使用更便宜的模型（如 Haiku、Flash）\n2. 减少最大 token 数\n3. 限制启用的工具集（减少不必要的函数调用）\n4. 使用缓存友好的提示词\n5. 考虑 Ollama 本地模型（零 API 成本）\n\n### Q: 如何解决 \"API key invalid\" 错误？\n\n1. 检查 `~/.hermes/.env` 中密钥是否正确\n2. 确认密钥没有过期或达到配额限制\n3. 运行 `hermes doctor` 进行诊断\n4. 尝试切换到备用提供商\n\n### Q: 如何让多个项目共享同一个 Hermes？\n\n创建项目级 `.hermes/config.yaml`：\n\n```bash\ncd my-project\nmkdir -p .hermes\ncat > .hermes/config.yaml << EOF\nmodel:\n  provider: openrouter\n  model: anthropic/claude-sonnet-4-20250514\nEOF\n\nHERMES_ENABLE_PROJECT_AGENTS=true hermes\n```\n\nFile v2.0.0:references/mcp-integration.md\n\n# Hermes Agent MCP 集成详解\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [MCP 协议概述](#mcp-协议概述)\n2. [双向集成架构](#双向集成架构)\n3. [Server 模式（暴露能力）](#server-模式暴露能力)\n4. [Client 模式（连接外部服务）](#client-模式连接外部服务)\n5. [工具过滤与安全](#工具过滤与安全)\n6. [IDE 配置](#ide-配置)\n7. [高级用法](#高级用法)\n8. [故障排除](#故障排除)\n\n---\n\n## MCP 协议概述\n\n**Model Context Protocol (MCP)** 是一种开放标准，允许 AI 应用与外部数据源和工具进行标准化通信。Hermes Agent 从 v0.6.0 起支持 MCP 的**双向集成**：\n\n```\n┌─────────────────────────────────────────────────────┐\n│                  MCP 生态                             │\n│                                                     │\n│   ┌──────────┐     ┌──────────┐     ┌──────────┐   │\n│   │   IDE    │ ←→ │  Hermes  │ ←→ │ 外部API  │   │\n│   │(Cursor)  │     │   Agent  │     │ (DB/CRM) │   │\n│   └──────────┘     └──────────┘     └──────────┘   │\n│        ↑               ↑               ↑           │\n│   MCP Client       MCP Server      MCP Server       │\n│                                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n### 核心概念\n\n| 概念 | 说明 |\n|------|------|\n| **MCP Server** | 提供能力和资源的服务端 |\n| **MCP Client** | 连接并使用 MCP Server 能力的客户端 |\n| **Tool** | 可被 LLM 调用的函数 |\n| **Resource** | 可被读取的数据（文件、URI等） |\n| **Prompt** | 可被注入的提示模板 |\n\n---\n\n## 双向集成架构\n\n### 架构图\n\n```\n                         ┌─────────────────────────┐\n                         │    WorkBuddy / IDE       │\n                         │         (客户端)          │\n                         └───────────┬─────────────┘\n                                     │ MCP Protocol\n                                     ▼\n                    ┌────────────────────────────────┐\n                    │        Hermes Agent             │\n                    │                                │\n                    │  ┌─────────────────────────┐   │\n                    │  │   MCP Server Mode        │   │\n                    │  │  (暴露 Hermes 能力)      │   │\n                    │  │  - 47+ 工具             │   │\n                    │  │  - 记忆系统              │   │\n                    │  │  - 技能系统              │   │\n                    │  └─────────────────────────┘   │\n                    │                                │\n                    │  ┌─────────────────────────┐   │\n                    │  │   MCP Client Mode        │   │\n                    │  │  (连接外部服务)          │   │\n                    │  │  - 数据库               │   │\n                    │  │  - API 服务             │   │\n                    │  │  - 文件系统             │   │\n                    │  └─────────────────────────┘   │\n                    └────────────────────────────────┘\n```\n\n### 使用场景\n\n| 场景 | 模式 | 说明 |\n|------|------|------|\n| IDE 集成 | Server | 在 Cursor/Windsurf 中调用 Hermes |\n| 扩展能力 | Client | 让 Hermes 使用外部数据库/API |\n| 双向桥接 | 两者兼用 | 同时作为 Server 和 Client |\n\n---\n\n## Server 模式（暴露能力）\n\n### 启动 MCP Server\n\n```bash\n# 方式1：标准输入输出模式（推荐用于 IDE 集成）\nhermes mcp serve --stdio\n\n# 方式2：HTTP 服务器模式\nhermes mcp serve --port 8080\n\n# 方式3：带配置选项启动\nhermes mcp serve --stdio \\\n  --allowed-tools \"web_search,memory,delegation\" \\\n  --max-tokens 4096 \\\n  --model \"anthropic/claude-haiku\"\n```\n\n### Server 配置选项\n\n| 选项 | 默认值 | 说明 |\n|------|--------|------|\n| `--port` | 8080 | HTTP 模式端口号（仅 HTTP 模式） |\n| `--stdio` | false | 使用 stdio 模式（推荐） |\n| `--model` | 配置默认值 | 强制使用指定模型 |\n| `--max-tokens` | 配置默认值 | 最大输出 Token 数 |\n| `--temperature` | 配置默认值 | 温度参数 |\n| `--allowed-tools` | 全部 | 允许暴露的工具列表（逗号分隔） |\n| `--blocked-tools` | 无 | 禁止暴露的工具列表 |\n| `--enable-memory` | true | 是否暴露记忆相关工具 |\n| `--enable-delegation` | true | 是否暴露子代理委托工具 |\n| `--require-authentication` | false | 是否需要认证令牌 |\n| `--auth-token` | 自动生成 | 认证令牌 |\n\n### 暴露的工具列表\n\n当以 Server 模式运行时，以下工具会暴露给 MCP 客户端：\n\n#### 核心工具\n\n| 工具名 | 参数 | 说明 |\n|--------|------|------|\n| `run_task` | task, context? | 运行完整任务（等同于 `hermes run`） |\n| `search_memory` | query, limit? | 搜索历史记忆 |\n| `add_note` | content, tags? | 添加新笔记 |\n| `list_notes` | tag_filter? | 列出所有笔记 |\n| `delegate_task` | task, tools?, timeout? | 创建子代理执行任务 |\n| `list_skills` | - | 列出已学技能 |\n| `create_skill` | name, description, content? | 创建新技能 |\n| `web_search` | query, num_results? | 网页搜索 |\n| `read_file` | path, offset?, limit? | 读取文件内容 |\n| `write_file` | path, content | 写入文件 |\n| `execute_command` | command, timeout? | 执行终端命令 |\n| `browser_navigate` | url | 浏览器导航到 URL |\n| `browser_click` | selector | 点击页面元素 |\n| `browser_extract` | selector, extract_type? | 提取页面数据 |\n\n---\n\n## Client 模式（连接外部服务）\n\n### 连接 MCP Server\n\n```bash\n# 方式1：通过命令行添加\nhermes mcp connect --name my-database \\\n  --type sse \\\n  --url http://localhost:3000/sse\n\n# 方式2：通过 JSON 配置\nhermes mcp connect '{\n  \"name\": \"postgres-db\",\n  \"type\": \"sse\",\n  \"url\": \"http://localhost:3000/mcp\",\n  \"headers\": {\"Authorization\": \"Bearer token123\"}\n}'\n\n# 方式3：从配置文件加载\nhermes mcp connect --config ./mcp-servers.json\n```\n\n### 配置文件格式 (`~/.hermes/mcp_servers.json`)\n\n```json\n{\n  \"mcpServers\": {\n    \"database\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-postgres\", \n               \"postgresql://user:pass@localhost:5432/mydb\"],\n      \"env\": {}\n    },\n    \"filesystem\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \n               \"/path/to/allowed/directory\"],\n      \"env\": {}\n    },\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"ghp_...\"\n      }\n    },\n    \"slack\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"xoxb-...\",\n        \"SLACK_APP_TOKEN\": \"xapp-...\"\n      }\n    },\n    \"brave-search\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-brave-search\"],\n      \"env\": {\n        \"BRAVE_API_KEY\": \"your-key\"\n      }\n    },\n    \"puppeteer\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-puppeteer\"]\n    },\n    \"fetch\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol/server-fetch\"]\n    }\n  }\n}\n```\n\n### 管理 MCP 连接\n\n```bash\n# 列出已连接的 MCP 服务\nhermes mcp list\n\n# 显示某个服务的可用工具\nhermes mcp tools database\n\n# 断开连接\nhermes mcp disconnect database\n\n# 断开所有连接\nhermes mcp disconnect --all\n\n# 测试连接\nhermes mcp test database\n```\n\n---\n\n## 工具过滤与安全\n\n### Server 端工具过滤\n\n当 Hermes 作为 MCP Server 运行时，可以限制暴露的工具：\n\n```bash\n# 只暴露特定工具\nhermes mcp serve --stdio \\\n  --allowed-tools \"run_task,search_memory,web_search\"\n\n# 排除危险工具\nhermes mcp serve --stdio \\\n  --blocked-tools \"execute_command,write_file,browser_*\"\n\n# 组合使用\nhermes mcp serve --stdio \\\n  --allowed-tools \"run_task,search_memory,list_notes\" \\\n  --blocked-tools \"\"\n```\n\n### Client 端工具命名空间\n\n来自 MCP Client 的工具会被自动加上命名空间前缀：\n\n```bash\n# 假设连接了 postgres 和 github 两个 MCP Server\n\n# 来自 postgres 的工具：\npostgres:query\npostgres:list_tables\npostgres:get_schema\n\n# 来自 github 的工具：\ngithub:search_issues\ngithub:create_issue\ngithub:get_file_contents\n\n# Hermes 内置工具保持原样：\nrun_task\nsearch_memory\ndelegate_task\n```\n\n### 安全最佳实践\n\n```yaml\n# ~/.hermes/config.yaml\nsecurity:\n  mcp:\n    # Server 模式设置\n    server:\n      require_authentication: true\n      auth_token_env: HERMES_MCP_AUTH_TOKEN\n      allowed_origins:            # CORS 白名单\n        - \"vscode-webview://*\"\n        - \"windsurf://*\"\n      \n    # Client 模式设置\n    client:\n      allow_untrusted_servers: false  # 只允许预配置的服务器\n      timeout_per_tool: 60           # 每个 MCP 工具超时时间\n      \n    # 审计日志\n    audit_log:\n      enabled: true\n      log_mcp_calls: true\n      include_params: false          # 不记录敏感参数\n```\n\n---\n\n## IDE 配置\n\n### Cursor 配置\n\n在 `.cursor/mcp.json` 中添加：\n\n```json\n{\n  \"mcpServers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\", \n               \"--allowed-tools\", \"run_task,search_memory,web_search,read_file,write_file\"]\n    }\n  }\n}\n```\n\n### VS Code + Claude Code 配置\n\n在 `.vscode/settings.json` 或 Claude Code 配置中：\n\n```json\n{\n  \"mcpServers\": {\n    \"hermes-agent\": {\n      \"command\": \"/Users/username/.local/bin/hermes\",\n      \"args\": [\n        \"mcp\", \n        \"serve\", \n        \"--stdio\",\n        \"--model\", \"anthropic/claude-haiku\",\n        \"--allowed-tools\", \"run_task,search_memory,web_search,file_operations,execute_code\"\n      ]\n    }\n  }\n}\n```\n\n### Windsurf 配置\n\n在 `.windsurf/mcp.json` 中：\n\n```json\n{\n  \"servers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n    }\n  }\n}\n```\n\n### Zed 编辑器配置\n\n在 `settings.json` 中：\n\n```json\n{\n  \"mcp_servers\": {\n    \"hermes\": {\n      \"command\": \"hermes\",\n      \"args\": [\"mcp\", \"serve\", \"--stdio\"]\n    }\n  }\n}\n```\n\n---\n\n## 高级用法\n\n### 1. 多实例部署\n\n同时运行多个 Hermes MCP Server，每个有不同的模型和能力配置：\n\n```bash\n# 实例1：轻量级快速任务（Haiku）\nHERMES_MCP_PORT=8081 hermes mcp serve --port 8081 \\\n  --model anthropic/claude-haiku \\\n  --allowed-tools \"run_task,search_memory\" &\n\n# 实例2：深度研究任务（Sonnet）\nHERMES_MCP_PORT=8082 hermes mcp serve --port 8082 \\\n  --model anthropic/claude-sonnet \\\n  --allowed-tools \"run_task,web_search,browser,delegation\" &\n\n# 实例3：代码任务（GPT-4o）\nHERMES_MCP_PORT=8083 hermes mcp serve --port 8083 \\\n  --model openai/gpt-4o \\\n  --allowed-tools \"run_task,file_operations,code_execution,terminal\" &\n```\n\nIDE 配置中选择不同的端口连接不同能力的实例。\n\n### 2. 链式 MCP 调用\n\nHermes 作为中间层，串联多个 MCP 服务：\n\n```\nIDE → Hermes MCP Server → [Hermes 内部处理]\n                           ↓\n                    Hermes MCP Client A → PostgreSQL\n                    Hermes MCP Client B → GitHub API\n                    Hermes MCP Client C → Slack\n```\n\nHermes 可以智能地根据任务需求选择调用哪个外部 MCP 工具。\n\n### 3. 自定义工具包装\n\n将外部 MCP 工具包装为 Hermes 的原生技能：\n\n```python\n# 包装脚本示例\ndef wrap_mcp_tool(ctx, tool_name, params):\n    \"\"\"\n    将 MCP 工具调用包装为 Hermes 技能\n    \"\"\"\n    result = call_mcp_client(\"my-server\", tool_name, params)\n    \n    # 后处理结果\n    if tool_name.startswith(\"db:\"):\n        return format_as_markdown_table(result)\n    elif tool_name.startswith(\"gh:\"):\n        return format_github_result(result)\n    \n    return result\n\nctx.register_tool(\n    name=\"query_database_via_mcp\",\n    schema=db_schema,\n    handler=lambda p: wrap_mcp_tool(ctx, f\"db:query\", p)\n)\n```\n\n### 4. 性能优化\n\n```yaml\n# config.yaml\nmcp:\n  server:\n    # 缓存常用查询结果\n    cache_enabled: true\n    cache_ttl: 300          # 缓存有效期（秒）\n    \n    # 并发控制\n    max_concurrent_requests: 5\n    \n    # 流式响应\n    streaming_enabled: true\n    \n  client:\n    # 连接池\n    connection_pool_size: 10\n    \n    # 重试策略\n    retry_attempts: 3\n    retry_backoff: 1s\n    \n    # 请求超时\n    request_timeout: 30s\n```\n\n---\n\n## 故障排除\n\n### 常见问题\n\n#### Q: MCP Server 启动失败\n\n```bash\n# 检查依赖\nhermes doctor\n\n# 查看 MCP 相关日志\nhermes logs --level ERROR | grep -i mcp\n\n# 手动测试 stdio 模式\necho '{\"jsonrpc\":\"2.0\",\"method\":\"initialize\",\"params\":{\"capabilities\":{}},\"id\":1}' | hermes mcp serve --stdio\n```\n\n#### Q: IDE 无法连接到 MCP Server\n\n1. **检查路径**: 确保 `hermes` 命令在 PATH 中\n2. **检查权限**: 确保 IDE 有权限执行 shell 命令\n3. **检查参数**: 确保 `args` 数组格式正确\n4. **测试连接**: 在终端手动运行相同命令验证\n\n```bash\n# Cursor/VSCODE 的调试方法\nhermes mcp serve --stdio &\n# 输入 JSON-RPC 测试消息\necho '{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":1}'\n```\n\n#### Q: MCP Client 连接超时\n\n```bash\n# 测试外部 MCP Server 是否可达\ncurl -v http://localhost:3000/sse\n\n# 检查网络配置\nhermes mcp test <server-name>\n\n# 增加超时时间\nhermes mcp connect ... --timeout 120\n```\n\n#### Q: 工具名称冲突\n\n当 Hermes 内置工具和 MCP Client 工具同名时，MCP 工具会自动加前缀。如果需要自定义前缀：\n\n```yaml\nmcp:\n  client:\n    namespace_prefix: true           # 启用命名空间前缀（默认开启）\n    namespace_separator: \":\"         # 分隔符\n    conflict_resolution: \"prefix\"    # prefix | rename | error\n```\n\n### 调试模式\n\n```bash\n# 启用详细调试日志\nHERMES_LOG_LEVEL=DEBUG hermes mcp serve --stdio\n\n# 查看所有 MCP 通信\nhermes logs --follow | grep -i mcp\n```\n\n---\n\n## 参考资源\n\n- **MCP 规范**: https://modelcontextprotocol.io/\n- **官方 SDK**: https://github.com/modelcontextprotocol/python-sdk\n- **社区服务器**: https://mcp.so/\n- **Hermes MCP 源码**: `mcp_serve.py`\n\nFile v2.0.0:references/plugin-development.md\n\n# Hermes Agent 插件开发指南\n\n> **版本**: v0.8.0 | **最后更新**: 2026-04-11\n\n## 目录\n\n1. [插件概述](#插件概述)\n2. [目录结构](#目录结构)\n3. [插件类型](#插件类型)\n4. [开发流程](#开发流程)\n5. [API 参考](#api-参考)\n6. [钩子系统](#钩子系统)\n7. [发布与分发](#发布与分发)\n8. [示例插件](#示例插件)\n\n---\n\n## 插件概述\n\nHermes 的插件系统允许用户在不修改核心代码的情况下扩展功能，支持：\n\n| 能力 | 说明 |\n|------|------|\n| **自定义工具** | 添加新的 LLM 可调用工具 |\n| **生命周期钩子** | 在关键事件点执行自定义逻辑 |\n| **CLI 命令扩展** | 添加 `hermes <plugin>` 子命令 |\n| **技能绑定** | 随插件分发技能文件 |\n| **数据文件打包** | 包含配置、模板等资源 |\n\n---\n\n## 目录结构\n\n```\nmy-plugin/\n├── plugin.yaml          # 插件清单（必需）\n├── __init__.py          # 注册函数（必需）\n├── schemas.py           # 工具模式定义\n├── tools.py             # 工具处理器实现\n├── data/                # 数据文件（可选）\n│   └── config.json\n└── skill.md             # 绑定的技能（可选）\n```\n\n### plugin.yaml 格式\n\n```yaml\nname: my-plugin-name           # 插件标识符（必需）\nversion: \"1.0.0\"              # 语义化版本（必需）\ndescription: 简短描述插件的功能 # 用户可见的描述（推荐）\nauthor: Your Name              # 作者信息（可选）\nrequires_env: []               # 需要的环境变量（可选，安装时提示用户配置）\n\n# 插件类型（自动检测，通常不需要手动指定）\ntype: general                  # general | memory_provider | context_engine\n\n# 兼容性\nhermes_min_version: \"0.7.0\"   # 最低兼容版本（可选）\nlicense: MIT                   # 许可证（可选）\nrepository: https://github.com/user/repo  # Git 仓库地址（可选）\n```\n\n### __init__.py 注册函数\n\n```python\n\"\"\"\n我的 Hermes 插件 - 实现描述\n\"\"\"\n\ndef register(ctx):\n    \"\"\"\n    主注册函数。Hermes 加载插件时调用此函数。\n    \n    Args:\n        ctx (PluginContext): 插件上下文对象，提供以下 API：\n            - ctx.register_tool(name, schema, handler): 注册工具\n            - ctx.register_hook(event_name, callback): 注册钩子\n            - ctx.register_cli_command(name, help, setup_fn, handler_fn): 注册 CLI 命令\n            - ctx.inject_message(content, role=\"user\"): 注入消息\n    \"\"\"\n    \n    # 导入你的工具定义和处理器\n    from .schemas import tool_schema\n    from .tools import handle_tool_call\n    \n    # 注册自定义工具\n    ctx.register_tool(\"my_tool_name\", tool_schema, handle_tool_call)\n    \n    # 注册钩子（可选）\n    def on_tool_complete(tool_name, params, result):\n        print(f\"[my-plugin] Tool {tool_name} completed\")\n        \n    ctx.register_hook(\"post_tool_call\", on_tool_complete)\n```\n\n---\n\n## 插件类型\n\n### 1. 通用插件 (General Plugin)\n\n最灵活的插件类型，可以添加任意数量的工具和钩子。\n\n```yaml\n# plugin.yaml\nname: weather-plugin\nversion: \"1.0.0\"\ndescription: 天气查询插件\n```\n\n```python\n# __init__.py\nfrom .schemas import get_weather_schema\nfrom .tools import get_weather_handler\n\ndef register(ctx):\n    ctx.register_tool(\"get_weather\", get_weather_schema, get_weather_handler)\n```\n\n### 2. 内存提供者 (Memory Provider)\n\n替换或增强内置的记忆系统。\n\n```yaml\n# plugin.yaml\nname: custom-memory\nversion: \"1.0.0\"\ndescription: 自定义记忆后端\ntype: memory_provider\n```\n\n```python\n# __init__.py\ndef register(ctx):\n    \"\"\"\n    内存提供者需要实现特定接口：\n    - search(query) -> List[Note]\n    - add(note) -> Note\n    - list_notes() -> List[Note]\n    - delete(note_id) -> bool\n    \"\"\"\n    class CustomMemoryBackend:\n        def search(self, query):\n            # 你的搜索实现\n            pass\n            \n        def add(self, content, tags=None):\n            # 你的添加实现\n            pass\n    \n    ctx.set_memory_backend(CustomMemoryBackend())\n```\n\n**可用的内存提供者类型**:\n\n| 后端名 | 特点 |\n|--------|------|\n| `built-in` | 默认，SQLite + FTS5 |\n| `honcho` | AI 原生方言建模 |\n| `mem0` | 开源记忆服务 |\n| `openviking` | 高级向量检索 |\n| `hindsight` | 时间线记忆 |\n| `holographic` | 全息记忆系统 |\n\n### 3. 上下文引擎 (Context Engine)\n\n替换内置的上下文压缩器。\n\n```yaml\n# plugin.yaml\nname: smart-context\nversion: \"1.0.0\"\ndescription: 智能上下文压缩\ntype: context_engine\n```\n\n```python\n# __init__.py\ndef register(ctx):\n    class SmartContextEngine:\n        def compress(self, messages, max_tokens):\n            # 自定义的上下文压缩逻辑\n            pass\n            \n        def summarize(self, text, target_length):\n            # 自定义摘要逻辑\n            pass\n    \n    ctx.set_context_engine(SmartContextEngine())\n```\n\n---\n\n## 开发流程\n\n### 步骤 1：创建插件骨架\n\n```bash\nmkdir -p ~/.hermes/plugins/my-plugin\ncd ~/.hermes/plugins/my-plugin\ntouch plugin.yaml __init__.py schemas.py tools.py\n```\n\n### 步骤 2：编写 plugin.yaml\n\n```yaml\nname: my-awesome-plugin\nversion: \"0.1.0\"\ndescription: 我的第一款 Hermes 插件\nauthor: Your Name\n```\n\n### 步骤 3：定义工具模式 (schemas.py)\n\n```python\n\"\"\"\n工具模式定义 - LLM 看到的接口说明\n\"\"\"\n\ntool_schema = {\n    \"name\": \"awesome_tool\",\n    \"description\": \"这个工具做什么的详细描述\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"param1\": {\n                \"type\": \"string\",\n                \"description\": \"参数1的说明\",\n            },\n            \"param2\": {\n                \"type\": \"integer\",\n                \"description\": \"参数2的说明\",\n                \"default\": 10,\n            },\n            \"options\": {\n                \"type\": \"array\",\n                \"items\": {\"type\": \"string\"},\n                \"description\": \"可选选项列表\",\n            }\n        },\n        \"required\": [\"param1\"],\n    }\n}\n```\n\n### 步骤 4：实现工具处理器 (tools.py)\n\n```python\n\"\"\"\n工具处理器 - 实际执行逻辑\n\"\"\"\n\nimport json\n\ndef handle_tool_call(params: dict) -> str:\n    \"\"\"\n    处理工具调用。\n    \n    Args:\n        params: 从 LLM 调用中接收到的参数字典\n        \n    Returns:\n        str: 返回给 LLM 的结果字符串（会被添加到对话历史中）\n    \"\"\"\n    param1 = params.get(\"param1\", \"\")\n    param2 = params.get(\"param2\", 10)\n    options = params.get(\"options\", [])\n    \n    try:\n        # === 在这里实现你的业务逻辑 ===\n        \n        result = f\"处理结果: param1={param1}, param2={param2}\"\n        \n        if options:\n            result += f\", options={', '.join(options)}\"\n            \n        return result\n        \n    except Exception as e:\n        # 错误处理：返回有意义的错误信息给 LLM\n        return f\"错误: 执行失败 - {str(e)}\"\n\n# 如果有多个工具，可以定义多个 schema/handler 对\nanother_tool_schema = {\n    \"name\": \"another_tool\",\n    \"description\": \"另一个工具\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"query\": {\"type\": \"string\", \"description\": \"查询内容\"}\n        },\n        \"required\": [\"query\"]\n    }\n}\n\ndef another_handler(params: dict) -> str:\n    query = params.get(\"query\", \"\")\n    return f\"查询 '{query}' 的结果是...\"\n```\n\n### 步骤 5：在 __init__.py 中注册\n\n```python\n\"\"\"My Awesome Plugin for Hermes Agent.\"\"\"\n\ndef register(ctx):\n    \"\"\"Register all tools and hooks with Hermes.\"\"\"\n    \n    # 导入本地模块\n    from .schemas import tool_schema, another_tool_schema\n    from .tools import handle_tool_call, another_handler\n    \n    # 注册工具 1\n    ctx.register_tool(\n        name=\"awesome_tool\",\n        schema=tool_schema,\n        handler=handle_tool_call\n    )\n    \n    # 注册工具 2\n    ctx.register_tool(\n        name=\"another_tool\",\n        schema=another_tool_schema,\n        handler=another_handler\n    )\n    \n    # 注册钩子（可选）\n    def log_tool_usage(tool_name, params, result):\n        \"\"\"记录每次工具调用到日志文件\"\"\"\n        import json\n        from datetime import datetime\n        \n        log_entry = {\n            \"timestamp\": datetime.now().isoformat(),\n            \"tool\": tool_name,\n            \"params\": params,\n            \"success\": not str(result).startswith(\"错误\")\n        }\n        \n        with open(\"/tmp/plugin-tool-usage.log\", \"a\") as f:\n            f.write(json.dumps(log_entry) + \"\\n\")\n            \n    ctx.register_hook(\"post_tool_call\", log_tool_usage)\n    \n    # 注册 CLI 命令（可选）\n    def setup_parser(parser):\n        \"\"\"设置 CLI 参数解析器\"\"\"\n        parser.add_argument(\"--verbose\", action=\"store_true\")\n        parser.add_argument(\"--output-format\", choices=[\"json\", \"text\"], default=\"text\")\n        \n    def cmd_handler(args):\n        \"\"\"处理 CLI 命令\"\"\"\n        print(f\"My plugin running with verbose={args.verbose}\")\n        \n    ctx.register_cli_command(\n        name=\"my-plugin\",\n        help=\"我的插件的自定义命令\",\n        setup_fn=setup_parser,\n        handler_fn=cmd_handler\n    )\n```\n\n### 步骤 6：安装和测试\n\n```bash\n# 安装插件（从本地路径）\nhermes plugins install /path/to/my-plugin\n\n# 或从 Git 安装\nhermes plugins install https://github.com/you/my-plugin.git\n\n# 启用插件\nhermes plugins enable my-plugin\n\n# 测试插件是否加载\nhermes plugins list\n\n# 在对话中测试\nhermes run \"使用 awesome_tool 工具，参数 param1=test\" --non-interactive --no-stream\n```\n\n---\n\n## API 参考\n\n### PluginContext API\n\n#### `ctx.register_tool(name, schema, handler)`\n\n注册一个可供 LLM 调用的工具。\n\n**参数**:\n- `name` (str): 工具名称，全局唯一\n- `schema` (dict): JSON Schema 格式的工具定义\n- `handler` (callable): 处理函数 `(params: dict) -> str`\n\n**示例**:\n```python\nctx.register_tool(\"my_tool\", {...}, lambda p: \"result\")\n```\n\n#### `ctx.register_hook(event_name, callback)`\n\n注册生命周期钩子。\n\n**可用事件**:\n\n| 事件名 | 回调签名 | 触发时机 |\n|--------|----------|----------|\n| `pre_tool_call` | `(tool_name, params)` | 工具执行前 |\n| `post_tool_call` | `(tool_name, params, result)` | 工具执行后 |\n| `pre_llm_call` | `(messages, kwargs)` | LLM 调用前，可返回 `{\"context\": \"...\"}` 注入上下文 |\n| `post_llm_call` | `(response, messages)` | LLM 调用成功后 |\n| `on_session_start` | `(session_id)` | 新会话创建时 |\n| `on_session_end` | `(session_id)` | 会话结束时 |\n\n#### `ctx.register_cli_command(name, help, setup_fn, handler_fn)`\n\n注册 CLI 子命令。\n\n**参数**:\n- `name` (str): 命令名称（如 `my-cmd`，调用方式为 `hermes my-cmd`）\n- `help` (str): 帮助文本\n- `setup_fn` (callable): 设置参数解析器 `(parser) -> None`\n- `handler_fn` (callable): 处理命令 `(args) -> None`\n\n#### `ctx.inject_message(content, role=\"user\")`\n\n向当前会话注入消息。\n\n**示例**:\n```python\nctx.inject_message(\"注意：用户偏好是使用中文回复。\", role=\"system\")\n```\n\n---\n\n## 钩子系统\n\n### 钩子执行顺序\n\n```\n用户输入 → pre_llm_call → [LLM 调用] → post_llm_call \n                                    ↓\n                              解析工具调用\n                                    ↓\n                              pre_tool_call → [工具执行] → post_tool_call\n                                    ↓\n                              返回响应\n```\n\n### 高级钩子用法\n\n#### 1. 上下文注入\n\n在每次 LLM 调用前注入额外的上下文信息：\n\n```python\ndef inject_user_preferences(messages, kwargs):\n    \"\"\"注入用户偏好的上下文\"\"\"\n    preferences = load_user_preferences()  # 你自己的函数\n    \n    context_text = (\n        f\"当前用户偏好:\\n\"\n        f\"- 语言: {preferences['language']}\\n\"\n        f\"- 时区: {preferences['timezone']}\\n\"\n        f\"- 专业领域: {preferences['domain']}\\n\"\n    )\n    \n    return {\"context\": context_text}\n\nctx.register_hook(\"pre_llm_call\", inject_user_preferences)\n```\n\n#### 2. 工具调用审计\n\n记录所有工具调用的完整日志：\n\n```python\ndef audit_tool_calls(tool_name, params, result):\n    \"\"\"审计所有工具调用\"\"\"\n    import logging\n    \n    logger = logging.getLogger(\"plugin.audit\")\n    logger.info({\n        \"tool\": tool_name,\n        \"params\": params,\n        \"result_length\": len(str(result)),\n        \"timestamp\": time.time()\n    })\n\nctx.register_hook(\"post_tool_call\", audit_tool_calls)\n```\n\n#### 3. 敏感操作确认\n\n对危险操作进行二次确认：\n\n```python\ndef confirm_destructive_actions(tool_name, params):\n    \"\"\"拦截破坏性操作\"\"\"\n    destructive_patterns = [\n        (\"file_delete\", [\"rm\", \"delete\"]),\n        (\"execute_command\", [\"rm -rf\", \"sudo\"]),\n    ]\n    \n    for t_tool, t_keywords in destructive_patterns:\n        if tool_name == t_tool:\n            for kw in t_keywords:\n                params_str = str(params).lower()\n                if kw in params_str:\n                    raise PermissionError(\n                        f\"⚠️ 危险操作被拦截: {tool_name} 包含关键词 '{kw}'\"\n                    )\n\nctx.register_hook(\"pre_tool_call\", confirm_destructive_actions)\n```\n\n---\n\n## 发布与分发\n\n### 本地安装\n\n```bash\n# 从本地目录安装\nhermes plugins install /path/to/my-plugin\n\n# 或直接复制到插件目录\ncp -r my-plugin ~/.hermes/plugins/\nhermes plugins enable my-plugin\n```\n\n### 通过 Git 分发\n\n```bash\n# 从 GitHub 安装\nhermes plugins install owner/repo\nhermes plugins install https://github.com/owner/repo.git\n\n# 从私有仓库安装（需认证）\nhermes plugins install git@github.com:owner/private-repo.git\n```\n\n### 通过 Pip 分发\n\n在 `pyproject.toml` 中添加入口点：\n\n```toml\n[project.entry-points.\"hermes_agent.plugins\"]\nmy_plugin = \"my_package:register\"\n```\n\n用户通过 `pip install your-package` 即可安装。\n\n### 更新插件\n\n```bash\n# 更新单个插件\nhermes plugins update my-plugin\n\n# 更新所有已安装的插件\nhermes plugins update --all\n```\n\n---\n\n## 示例插件\n\n### 示例 1：天气查询插件\n\n```yaml\n# plugin.yaml\nname: weather-plugin\nversion: \"1.0.0\"\ndescription: 使用 OpenWeatherMap API 查询天气\nrequires_env: [OPENWEATHERMAP_API_KEY]\nauthor: Example Author\n```\n\n```python\n# __init__.py\n\"\"\"Weather Query Plugin for Hermes Agent.\"\"\"\nimport os\n\ndef register(ctx):\n    from .schemas import weather_schema, forecast_schema\n    from .tools import get_current_weather, get_forecast\n    \n    ctx.register_tool(\"get_current_weather\", weather_schema, get_current_weather)\n    ctx.register_tool(\"get_weather_forecast\", forecast_schema, get_forecast)\n```\n\n```python\n# schemas.py\nweather_schema = {\n    \"name\": \"get_current_weather\",\n    \"description\": \"获取指定城市的当前天气情况\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"city\": {\n                \"type\": \"string\",\n                \"description\": \"城市名称，如 'Beijing'、'New York'\"\n            },\n            \"units\": {\n                \"type\": \"string\",\n                \"enum\": [\"metric\", \"imperial\"],\n                \"default\": \"metric\",\n                \"description\": \"温度单位\"\n            }\n        },\n        \"required\": [\"city\"]\n    }\n}\n\nforecast_schema = {\n    \"name\": \"get_weather_forecast\",\n    \"description\": \"获取未来几天的天气预报\",\n    \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n            \"city\": {\n                \"type\": \"string\",\n                \"description\": \"城市名称\"\n            },\n            \"days\": {\n                \"type\": \"integer\",\n                \"description\": \"预报天数（1-7）\",\n                \"default\": 3\n            }\n        },\n        \"required\": [\"city\"]\n    }\n}\n```\n\n```python\n# tools.py\n\"\"\"Weather tool implementations.\"\"\"\nimport os\nimport requests\n\nAPI_KEY = os.environ.get(\"OPENWEATHERMAP_API_KEY\", \"\")\nBASE_URL = \"https://api.openweathermap.org/data/2.5\"\n\ndef get_current_weather(params: dict) -> str:\n    city = params[\"city\"]\n    units = params.get(\"units\", \"metric\")\n    \n    url = f\"{BASE_URL}/weather?q={city}&appid={API_KEY}&units={units}\"\n    \n    response = requests.get(url, timeout=10)\n    \n    if response.status_code != 200:\n        return f\"无法获取天气信息: {response.json().get('message', '未知错误')}\"\n    \n    data = response.json()\n    temp_unit = \"°C\" if units == \"metric\" else \"°F\"\n    \n    return (\n        f\"{city} 当前天气:\\n\"\n        f\"- 温度: {data['main']['temp']}{temp_unit}\\n\"\n        f\"- 体感温度: {data['main']['feels_like']}{temp_unit}\\n\"\n        f\"- 湿度: {data['main']['humidity']}%\\n\"\n        f\"- 风速: {data['wind'].get('speed', 0)} m/s\\n\"\n        f\"- 天气状况: {data['weather'][0]['description']}\\n\"\n        f\"- 能见度: {data.get('visibility', 'N/A')} m\"\n    )\n\ndef get_forecast(params: dict) -> string:\n    city = params[\"city\"]\n    days = min(max(params.get(\"days\", 3), 1), 7)  # 限制在 1-7 天\n    \n    url = f\"{BASE_URL}/forecast?q={city}&appid={API_KEY}&units=metric&cnt={days * 8}\"  # 每3小时一个数据点\n    \n    response = requests.get(url, timeout=10)\n    \n    if response.status_code != 200:\n        return f\"无法获取预报: {response.json().get('message', '未知错误')}\"\n    \n    data = response.json()\n    \n    result = f\"{city} 未来{days}天预报:\\n\\n\"\n    \n    for item in data[\"list\"][:days * 8]:  # 取前 N 天的数据\n        dt = item[\"dt_txt\"]\n        temp = item[\"main\"][\"temp\"]\n        desc = item[\"weather\"][0][\"description\"]\n        result += f\"{dt}: {temp}°C, {desc}\\n\"\n    \n    return result\n```\n\n### 示例 2：数据库查询插件\n\n```python\n# __init__.py\n\"\"\"Database Query Plugin - 安全地执行 SQL 查询。\"\"\"\n\nimport sqlite3\n\ndef register(ctx):\n    db_schema = {\n        \"name\": \"query_database\",\n        \"description\": \"在 SQLite 数据库中执行只读 SQL 查询\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"db_path\": {\n                    \"type\": \"string\",\n                    \"description\": \"数据库文件路径\"\n                },\n                \"query\": {\n                    \"type\": \"string\",\n                    \"description\": \"SQL SELECT 查询语句\"\n                },\n                \"limit\": {\n                    \"type\": \"integer\",\n                    \"description\": \"最大返回行数（默认100）\",\n                    \"default\": 100\n                }\n            },\n            \"required\": [\"db_path\", \"query\"]\n        }\n    }\n    \n    def execute_query(params: dict) -> str:\n        db_path = params[\"db_path\"]\n        query = params[\"query\"].strip()\n        limit = params.get(\"limit\", 100)\n        \n        # 安全检查：只允许 SELECT 语句\n        if not query.upper().startswith(\"SELECT\"):\n            return \"错误: 只允许 SELECT 查询语句\"\n        \n        # 检查危险关键字\n        dangerous = [\"DROP\", \"DELETE\", \"UPDATE\", \"INSERT\", \"ALTER\", \"--\", \";\"]\n        for word in dangerous:\n            if word.upper() in query.upper():\n                return f\"错误: 查询包含不安全的关键字 '{word}'\"\n        \n        try:\n            conn = sqlite3.connect(db_path)\n            conn.row_factory = sqlite3.Row\n            \n            # 自动添加 LIMIT\n            if \"LIMIT\" not in query.upper():\n                query += f\"\\nLIMIT {limit}\"\n            \n            cursor = conn.execute(query)\n            rows = cursor.fetchall()\n            columns = [desc[0] for desc in cursor.description]\n            \n            conn.close()\n            \n            if not rows:\n                return \"查询返回空结果集\"\n            \n            # 格式化输出为表格\n            header = \" | \".join(columns)\n            separator = \"-+-\".join([\"-\" * len(c) for c in columns])\n            lines = [header, separator]\n            \n            for row in rows[:limit]:\n                line = \" | \".join(str(v) for v in row)\n                lines.append(line)\n                \n            return \"\\n\".join(lines)\n            \n        except sqlite3.Error as e:\n            return f\"SQL 错误: {str(e)}\"\n        except Exception as e:\n            return f\"执行错误: {str(e)}\"\n    \n    ctx.register_tool(\"query_database\", db_schema, execute_query)\n```\n\nFile v2.0.0:references/self-improving-integration.md\n\n# Hermes Agent 与 Self-Improving Agent CN 集成指南\n\n> **版本**: v1.0.0 | **最后更新**: 2026-04-11\n\n## 概述\n\n本集成方案让 Hermes Agent 和 **Self-Improving Agent CN** 形成完整的**正负反馈闭环**：\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│                    自改进学习循环                             │\n├─────────────────────────────────────────────────────────────┤\n│                                                             │\n│   ┌───────────────────┐     ┌──────────────────────────┐    │\n│   │   Hermes Agent     │     │  Self-Improving Agent   │    │\n│   │                   │     │         CN              │    │\n│   │  ✅ 成功任务 →     │     │  ❌ 失败/纠正 →          │    │\n│   │  提取可复用技能    │ ←→ │  记录错误教训            │    │\n│   │                   │     │                          │    │\n│   │  存储位置:          │     │  存储位置:               │    │\n│   │  ~/.hermes/skills/ │     │  ~/.openclaw/memory/     │    │\n│   └───────────────────┘     │  self-improving/         │    │\n│                             └──────────────────────────┘    │\n│                                                             │\n│   Wrapper/Delegate 脚本自动触发错误回调                       │\n│                                                             │\n└─────────────────────────────────────────────────────────────┘\n```\n\n---\n\n## 集成方式\n\n### 自动错误回调机制（已内置）\n\n`hermes_wrapper.sh` 和 `hermes_delegate.sh` 已内置 `error_callback()` 函数：\n\n**触发条件**:\n1. 命令执行失败（退出码非0）\n2. 任务超时（退出码124）\n3. 并发限制达到\n4. 其他运行时错误\n\n**回调行为**:\n- 将错误信息记录到 `~/.openclaw/memory/self-improving/learnings.jsonl`\n- 包含时间戳、错误类型、任务描述、原始命令等上下文\n- 预留 `lesson` 字段供后续分析填充\n\n### 错误记录格式\n\n```json\n{\n  \"timestamp\": \"2026-04-11T20:46:00Z\",\n  \"error_type\": \"TIMEOUT\",\n  \"error_message\": \"任务执行超时 (300s): 研究竞品产品特性\",\n  \"task\": \"研究竞品产品特性\",\n  \"command\": \"hermes run '...' --non-interactive --no-stream --timeout 300\",\n  \"source\": \"hermes-delegate\",\n  \"context\": {\n    \"hermes_version\": \"Hermes Agent v0.8.0 (2026.4.8)\",\n    \"platform\": \"Darwin\",\n    \"user\": \"chunhaixu\"\n  },\n  \"lesson\": \"TODO: 待分析此错误的根本原因和解决方案\"\n}\n```\n\n---\n\n## 配置与使用\n\n### 启用自动记录（默认启用）\n\n```bash\n# 错误回调默认启用，无需额外配置\n# 记录文件位置: ~/.openclaw/memory/self-improving/learnings.jsonl\n```\n\n### 查看学习记录\n\n```bash\n# 查看所有错误记录\ncat ~/.openclaw/memory/self-improving/learnings.jsonl | jq .\n\n# 按日期过滤\ncat ~/.openclaw/memory/self-improving/learnings.jsonl \\\n  | jq 'select(.timestamp | startswith(\"2026-04\"))'\n\n# 按错误类型统计\ncat ~/.openclaw/memory/self-improving/learnings.jsonl \\\n  | jq -r '.error_type' | sort | uniq -c | sort -rn\n\n# 查看最近的错误\ntail -5 ~/.openclaw/memory/self-improving/learnings.jsonl | jq .\n```\n\n### 手动添加教训（填充 lesson 字段）\n\n当分析出错误原因后，更新记录：\n\n```bash\n# 使用 jq 更新特定记录的 lesson 字段\nRECORD_ID=$(tail -1 learnings.jsonl | jq '.timestamp')\njq \"if .timestamp == \\\"$RECORD_ID\\\" then .lesson = \\\"应该增加超时时间到600秒或简化任务范围\\\" else . end\" \\\n  learnings.jsonl > tmp.jsonl && mv tmp.jsonl learnings.jsonl\n```\n\n### 在 WorkBuddy 中使用\n\nWorkBuddy 加载 self-improving-agent-cn Skill 后会自动：\n\n1. **执行前检查**：读取 `learnings.jsonl` 中的历史错误\n2. **模式匹配**：识别当前任务是否与历史错误相似\n3. **预防性建议**：根据历史教训给出建议\n\n---\n\n## 最佳实践\n\n### 1. 定期审查错误日志\n\n建议每周检查一次学习记录：\n\n```bash\n#!/bin/bash\n# review_errors.sh - 审查本周 Hermes 错误\n\nERROR_FILE=\"$HOME/.openclaw/memory/self-improving/learnings.jsonl\"\nTHIS_WEEK=$(date +%Y-%W)\n\necho \"=== 本周 ($THIS_WEEK) Hermes 错误报告 ===\"\necho \"\"\n\nif [ -f \"$ERROR_FILE\" ]; then\n    # 统计错误数量\n    TOTAL=$(grep -c \"\" \"$ERROR_FILE\" 2>/dev/null || echo 0)\n    \n    # 统计各类错误\n    echo \"📊 错误类型分布:\"\n    cat \"$ERROR_FILE\" | jq -r '.error_type' | sort | uniq -c | sort -rn | while read count type; do\n        echo \"   $count x $type\"\n    done\n    \n    echo \"\"\n    echo \"📝 未解决的教训 (lesson 为 TODO):\"\n    cat \"$ERROR_FILE\" | jq -r 'select(.lesson | startswith(\"TODO\")) | \"- \\(.error_type): \\(.task)\"'\n    \nelse\n    echo \"✅ 无错误记录\"\nfi\n```\n\n### 2. 从错误中提取技能\n\n当同一类型的错误重复出现 3+ 次，考虑将其转化为 Hermes 技能：\n\n```bash\n#!/bin/bash\n# extract_skill_from_errors.sh - 从错误中提取技能模板\n\nERROR_FILE=\"$HOME/.openclaw/memory/self-improving/learnings.jsonl\"\nSKILLS_DIR=\"$HOME/.hermes/skills\"\n\n# 找出最频繁的错误类型\nTOP_ERROR=$(cat \"$ERROR_FILE\" | jq -r '.error_type' | sort | uniq -c | sort -rn | head -1 | awk '{print $2}')\n\necho \"检测到高频错误类型: $TOP_ERROR\"\n\ncase $TOP_ERROR in\n    TIMEOUT)\n        SKILL_NAME=\"timeout-handling\"\n        echo \"建议创建技能: $SKILL_NAME\"\n        \n        mkdir -p \"$SKILLS_DIR/$SKILL_NAME\"\n        cat > \"$SKILLS_DIR/$SKILL_NAME/skill.md\" << EOF\n---\nname: timeout-handling\ndescription: 处理可能超时的长时间任务\ntriggers:\n  - 超时任务\n  - 大量数据查询\n  - 复杂研究\n---\n\n# 超时处理技能\n\n## 策略\n1. **分解任务**: 将大任务拆分为多个小步骤\n2. **设置合理超时**: 简单任务60s, 中等300s, 复杂600s+\n3. **工具集限制**: 只启用必要的工具减少 Token 消耗\n4. **增量保存**: 每完成一步就保存中间结果\n5. **重试机制**: 失败后自动重试1次\n\n## 最佳实践\n\\`\\`\\`bash\n# 推荐参数\nhermes run \"任务\" --toolset web_search --timeout 120\n\\`\\`\\`\nEOF\n        \n        echo \"✅ 技能已创建: $SKILLS_DIR/$SKILL_NAME/skill.md\"\n        ;;\nesac\n```\n\n### 3. 双向同步\n\n让 Hermes 的技能系统和 Self-Improving 的错误系统互相感知：\n\n```python\n# 可选的高级集成代码示例\ndef sync_hermes_with_self_improving():\n    \"\"\"\n    定期同步 Hermes 技能和 Self-Improving 记录\n    \"\"\"\n    import json\n    \n    skills_dir = Path(\"~/.hermes/skills\").expanduser()\n    errors_file = Path(\"~/.openclaw/memory/self-improving/learnings.jsonl\").expanduser()\n    \n    # 1. 将新技能通知给 Self-Improving\n    for skill_file in skills_dir.glob(\"**/skill.md\"):\n        skill_name = skill_file.parent.name\n        # 标记为从成功经验中学到的能力\n        log_success(f\"New skill available: {skill_name}\")\n    \n    # 2. 分析错误模式并建议技能改进\n    if errors_file.exists():\n        with open(errors_file) as f:\n            errors = [json.loads(line) for line in f]\n        \n        # 按错误类型分组\n        from collections import Counter\n        error_types = Counter(e['error_type'] for e in errors)\n        \n        for error_type, count in error_types.most_common(3):\n            if count >= 3 and not any(s.name == f\"{error_type}-handling\" \n                                       for s in list_skills()):\n                suggest_skill_creation(error_type, errors)\n```\n\n---\n\n## 故障排除\n\n### Q: 错误记录文件不存在？\n\n```bash\nmkdir -p ~/.openclaw/memory/self-improving/\ntouch ~/.openclaw/memory/self-improving/learnings.jsonl\n```\n\n### Q: jq 命令不可用？\n\n```bash\n# macOS 安装 jq\nbrew install jq\n\n# 或使用 Python 替代\npython3 -c \"\nimport json\nwith open('learnings.jsonl') as f:\n    for line in f:\n        print(json.dumps(json.loads(line), indent=2))\n\"\n```\n\n### Q: 如何禁用错误回调？\n\n临时禁用：\n```bash\nHERMES_DISABLE_SELF_IMPROVING=true hermes_wrapper.sh run \"prompt\"\n```\n\n永久修改脚本中的 `error_callback()` 调用处即可。\n\n---\n\n## 总结\n\n| 维度 | Hermes Agent | Self-Improving Agent CN |\n|------|--------------|------------------------|\n| **学习来源** | ✅ 成功任务 | ❌ 失败/纠正 |\n| **存储格式** | Markdown 技能文件 | JSONL 记录文件 |\n| **触发时机** | 任务完成后 | 用户纠正/失败时 |\n| **优化频率** | 每15个任务评估 | 每次执行前检查 |\n| **内容类型** | 可复用方法论 | 应避免的错误 |\n\n两者互补，形成**完整的正负反馈闭环**，让 Agent 系统越用越智能！","readmeExcerpt":"Skill: Hermes Agent Skill Owner: wihy Summary: NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation... Tags: agent:2.0.0, ai:2.0.0, delegation:2.0.0, hermes:2.0.0, latest:2.1.1, mcp:2.0.0, memory:2.0.0, self-improving:2.0.0 Version history: v2.1.1 | 2026-04-12T01:49:58.074Z | user - Major simplification: Documenta","codeSnippets":[],"executableExamples":[{"language":"bash","snippet":"hermes run \"your question\" --non-interactive --no-stream"},{"language":"bash","snippet":"hermes run \"question\" --context-file ./ctx.md --non-interactive"},{"language":"bash","snippet":"hermes run \"use delegate_task to: research topic\" --non-interactive --no-stream"},{"language":"bash","snippet":"hermes memory search \"keyword\"\nhermes memory notes list\nhermes memory notes add \"note content\""},{"language":"bash","snippet":"hermes skills list\nhermes skills create \"name\" --description \"desc\""},{"language":"bash","snippet":"hermes status\nhermes doctor"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: hermes-agent-v2\ndescription: |\n  NousResearch Hermes Agent CLI integration. Core capabilities:\n  - Self-improving skill system\n  - Persistent memory (FTS5 + LLM summaries)\n  - Sub-agent delegation\n  - MCP integration\n  - Browser automation\n  - Code execution\n\ntriggers:\n  - \"使用 hermes\"\n  - \"调用 hermes\"\n  - \"hermes agent\"\n  - \"hermes run\"\n  - \"hermes delegate\"\n  - \"hermes memory\"\n  - \"hermes skills\"\n\ncategory: ai-agents\nversion: 2.1.0\nrequires_approval: false\nsecurity: |\n  This skill only calls the hermes CLI command. It does not read, write, or modify\n  any files outside of standard hermes operations (~/.hermes/).\n  Hermes Agent source: https://github.com/NousResearch/hermes-agent\n---\n\n# Hermes Agent Skill\n\nCall [NousResearch Hermes Agent](https://github.com/NousResearch/hermes-agent) via CLI.\n\n## Prerequisites\n\nHermes CLI must be installed. See https://github.com/NousResearch/hermes-agent for installation.\n\n## Usage\n\n### Quick Q&A\n\n```bash\nhermes run \"your question\" --non-interactive --no-stream\n```\n\n### With Context\n\n```bash\nhermes run \"question\" --context-file ./ctx.md --non-interactive\n```\n\n### Sub-agent Delegation\n\n```bash\nhermes run \"use delegate_task to: research topic\" --non-interactive --no-stream\n```\n\n### Memory\n\n```bash\nhermes memory search \"keyword\"\nhermes memory notes list\nhermes memory notes add \"note content\"\n```\n\n### Skills\n\n```bash\nhermes skills list\nhermes skills create \"name\" --description \"desc\"\n```\n\n### Status\n\n```bash\nhermes status\nhermes doctor\n```\n\n## Configuration\n\nEdit `~/.hermes/.env` to set your LLM provider key.\nEdit `~/.hermes/config.yaml` to set model and provider.\n\n## File Access Scope\n\nThis skill only invokes hermes CLI commands. No direct file operations.\nHermes Agent operates within `~/.hermes/` only."},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn75neczzxsdbx7djhh1kn544182nsbj\",\n  \"slug\": \"hermes-agent-v2\",\n  \"version\": \"2.1.1\",\n  \"publishedAt\": 1775958598074\n}"},{"path":"skill-card.md","content":"## Description:\n\nHermes Agent Skill integrates the NousResearch Hermes Agent CLI for agent workflows including persistent memory, sub-agent delegation, MCP integration, browser automation, and code execution.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[wihy](https://clawhub.ai/user/wihy)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and agent operators use this skill to call Hermes CLI from an agent session for Q&A, context-aware runs, delegation, memory operations, skill management, status checks, and configuration guidance.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Hermes CLI and its configured model provider may process prompts, context files, and delegated tasks outside this skill.\n\nMitigation: Use this skill only with a trusted Hermes CLI installation and trusted model provider configuration; avoid passing sensitive files with --context-file unless that processing is intended.\n\nRisk: Memory notes, created skills, and ~/.hermes configuration changes can persist beyond a single run.\n\nMitigation: Periodically review Hermes memory notes, created skills, and ~/.hermes configuration for stale, sensitive, or unexpected state.\n\nRisk: Broad Hermes agent capabilities, including delegation, browser automation, code execution, and MCP integration, may operate without clear approval boundaries.\n\nMitigation: Run Hermes in controlled workspaces, review commands before execution, and apply local sandbox or approval policies where available.\n\n## Reference(s):\n\n- [ClawHub Hermes Agent Skill](https://clawhub.ai/wihy/skills/hermes-agent-v2)\n- [NousResearch Hermes Agent documentation](https://github.com/NousResearch/hermes-agent)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, shell commands, configuration, guidance]\n\n**Output Format:** [Markdown with inline bash code blocks]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May reference local Hermes configuration and persistent Hermes memory state.]\n\n## Skill Version(s):\n\n2.1.1 (source: server release metadata; artifact frontmatter and _meta.json list 2.1.0)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment."}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":"NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation... Skill: Hermes Agent Skill Owner: wihy Summary: NousResearch Hermes Agent CLI integration. Core capabilities: - Self-improving skill system - Persistent memory (FTS5 + LLM summaries) - Sub-agent delegation... Tags: agent:2.0.0, ai:2.0.0, delegation:2.0.0, hermes:2.0.0, latest:2.1.1, mcp:2.0.0, memory:2.0.0, self-improving:2.0.0 Version history: v2.1.1 | 2026-04-12T01:49:58.074Z | user - Major simplification: Documenta","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":983,"uniquenessScore":52,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-09T05:15:48.051Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-09T19:36:16.936Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}