跳到主要內容

Claude Code

將編碼任務委託給 Claude Code(Anthropic 的 CLI 代理)。用於構建功能、重構代碼、PR 審查和迭代式編碼。需要安裝 claude CLI。

技能元數據

來源捆綁(默認安裝)
路徑skills/autonomous-ai-agents/claude-code
版本2.2.0
作者Hermes Agent + Teknium
許可證MIT
標籤Coding-Agent, Claude, Anthropic, Code-Review, Refactoring, PTY, Automation
相關技能codex, hermes-agent, opencode

參考:完整 SKILL.md

信息

以下是 Hermes 在觸發此技能時加載的完整技能定義。這是技能激活時代理看到的指令。

Claude Code — Hermes 編排指南

通過 Hermes 終端將編碼任務委託給 Claude Code(Anthropic 的自主編碼代理 CLI)。Claude Code v2.x 可以讀取文件、編寫代碼、運行 shell 命令、生成子代理以及自主管理 git 工作流。

前提條件

  • 安裝: npm install -g @anthropic-ai/claude-code
  • 認證: 運行一次 claude 以登錄(Pro/Max 用戶通過瀏覽器 OAuth,或設置 ANTHROPIC_API_KEY
  • 控制檯認證: claude auth login --console 用於 API 密鑰計費
  • SSO 認證: claude auth login --sso 用於企業版
  • 檢查狀態: claude auth status(JSON 格式)或 claude auth status --text(人類可讀格式)
  • 健康檢查: claude doctor — 檢查自動更新程序和安裝健康狀況
  • 版本檢查: claude --version(需要 v2.x+)
  • 更新: claude updateclaude upgrade

兩種編排模式

Hermes 以兩種根本不同的方式與 Claude Code 交互。請根據任務選擇。

模式 1:打印模式 (-p) — 非交互式(大多數任務的首選)

打印模式運行一次性任務,返回結果並退出。不需要 PTY。沒有交互式提示。這是最乾淨的集成路徑。

terminal(command="claude -p 'Add error handling to all API calls in src/' --allowedTools 'Read,Edit' --max-turns 10", workdir="/path/to/project", timeout=120)

何時使用打印模式:

  • 一次性編碼任務(修復錯誤、添加功能、重構)
  • CI/CD 自動化和腳本編寫
  • 使用 --json-schema 進行結構化數據提取
  • 管道輸入處理(cat file | claude -p "analyze this"
  • 任何不需要多輪對話的任務

打印模式跳過所有交互式對話框 — 沒有工作區信任提示,沒有權限確認。這使其成為自動化的理想選擇。

模式 2:通過 tmux 的交互式 PTY — 多輪會話

交互式模式為您提供完整的對話式 REPL,您可以發送後續提示、使用斜槓命令並實時觀察 Claude 的工作。需要 tmux 編排。

# Start a tmux session
terminal(command="tmux new-session -d -s claude-work -x 140 -y 40")

# Launch Claude Code inside it
terminal(command="tmux send-keys -t claude-work 'cd /path/to/project && claude' Enter")

# Wait for startup, then send your task
# (after ~3-5 seconds for the welcome screen)
terminal(command="sleep 5 && tmux send-keys -t claude-work 'Refactor the auth module to use JWT tokens' Enter")

# Monitor progress by capturing the pane
terminal(command="sleep 15 && tmux capture-pane -t claude-work -p -S -50")

# Send follow-up tasks
terminal(command="tmux send-keys -t claude-work 'Now add unit tests for the new JWT code' Enter")

# Exit when done
terminal(command="tmux send-keys -t claude-work '/exit' Enter")

何時使用交互式模式:

  • 多輪迭代工作(重構 → 審查 → 修復 → 測試循環)
  • 需要人工介入決策的任務
  • 探索性編碼會話
  • 當您需要使用 Claude 的斜槓命令時(/compact, /review, /model

PTY 對話框處理(交互式模式的關鍵)

Claude Code 在首次啟動時最多會顯示兩個確認對話框。您必須通過 tmux send-keys 處理這些對話框:

對話框 1:工作區信任(首次訪問目錄)

❯ 1. Yes, I trust this folder    ← DEFAULT (just press Enter)
2. No, exit

處理: tmux send-keys -t <session> Enter — 默認選擇是正確的。

對話框 2:繞過權限警告(僅在使用 --dangerously-skip-permissions 時)

❯ 1. No, exit                    ← DEFAULT (WRONG choice!)
2. Yes, I accept

處理: 必須先向下導航,然後按 Enter:

tmux send-keys -t <session> Down && sleep 0.3 && tmux send-keys -t <session> Enter

穩健的對話框處理模式

# Launch with permissions bypass
terminal(command="tmux send-keys -t claude-work 'claude --dangerously-skip-permissions \"your task\"' Enter")

# Handle trust dialog (Enter for default "Yes")
terminal(command="sleep 4 && tmux send-keys -t claude-work Enter")

# Handle permissions dialog (Down then Enter for "Yes, I accept")
terminal(command="sleep 3 && tmux send-keys -t claude-work Down && sleep 0.3 && tmux send-keys -t claude-work Enter")

# Now wait for Claude to work
terminal(command="sleep 15 && tmux capture-pane -t claude-work -p -S -60")

注意: 在首次接受某個目錄的信任後,信任對話框將不再出現。只有權限對話框會在每次使用 --dangerously-skip-permissions 時重複出現。

CLI 子命令

子命令用途
claude啟動交互式 REPL
claude "query"使用初始提示啟動 REPL
claude -p "query"打印模式(非交互式,完成後退出)
cat file | claude -p "query"將內容通過管道作為 stdin 上下文傳入
claude -c繼續此目錄中最近的對話
claude -r "id"按 ID 或名稱恢復特定會話
claude auth login登錄(添加 --console 用於 API 計費,--sso 用於企業版)
claude auth status檢查登錄狀態(返回 JSON;使用 --text 獲取人類可讀格式)
claude mcp add <name> -- <cmd>添加 MCP 服務器
claude mcp list列出已配置的 MCP 服務器
claude mcp remove <name>移除 MCP 服務器
claude agents列出已配置的代理
claude doctor對安裝和自動更新程序運行健康檢查
claude update / claude upgrade將 Claude Code 更新至最新版本
claude remote-control啟動服務器以從 claude.ai 或移動應用控制 Claude
claude install [target]安裝原生構建版本(stable、latest 或特定版本)
claude setup-token設置長期有效的身份驗證令牌(需要訂閱)
claude plugin / claude plugins管理 Claude Code 插件
claude auto-mode檢查自動模式分類器配置

結構化 JSON 輸出

terminal(command="claude -p 'Analyze auth.py for security issues' --output-format json --max-turns 5", workdir="/project", timeout=120)

返回包含以下內容的 JSON 對象:

{
"type": "result",
"subtype": "success",
"result": "The analysis text...",
"session_id": "75e2167f-...",
"num_turns": 3,
"total_cost_usd": 0.0787,
"duration_ms": 10276,
"stop_reason": "end_turn",
"terminal_reason": "completed",
"usage": { "input_tokens": 5, "output_tokens": 603, ... },
"modelUsage": { "claude-sonnet-4-6": { "costUSD": 0.078, "contextWindow": 200000 } }
}

關鍵字段session_id 用於恢復會話,num_turns 用於代理循環計數,total_cost_usd 用於支出跟蹤,subtype 用於成功/錯誤檢測(successerror_max_turnserror_budget)。

流式 JSON 輸出

對於實時令牌流式傳輸,請將 stream-json--verbose 一起使用:

terminal(command="claude -p 'Write a summary' --output-format stream-json --verbose --include-partial-messages", timeout=60)

返回換行符分隔的 JSON 事件。使用 jq 過濾以獲取實時文本:

claude -p "Explain X" --output-format stream-json --verbose --include-partial-messages | \
jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

流事件包括帶有 attemptmax_retrieserror 字段(例如 rate_limitbilling_error)的 system/api_retry

雙向流式傳輸

對於實時輸入輸出流式傳輸:

claude -p "task" --input-format stream-json --output-format stream-json --replay-user-messages

--replay-user-messages 在 stdout 上重新發出用戶消息以進行確認。

管道輸入

# Pipe a file for analysis
terminal(command="cat src/auth.py | claude -p 'Review this code for bugs' --max-turns 1", timeout=60)

# Pipe multiple files
terminal(command="cat src/*.py | claude -p 'Find all TODO comments' --max-turns 1", timeout=60)

# Pipe command output
terminal(command="git diff HEAD~3 | claude -p 'Summarize these changes' --max-turns 1", timeout=60)

用於結構化提取的 JSON Schema

terminal(command="claude -p 'List all functions in src/' --output-format json --json-schema '{\"type\":\"object\",\"properties\":{\"functions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"functions\"]}' --max-turns 5", workdir="/project", timeout=90)

從 JSON 結果中解析 structured_output。Claude 在返回之前會根據 schema 驗證輸出。

會話延續

# Start a task
terminal(command="claude -p 'Start refactoring the database layer' --output-format json --max-turns 10 > /tmp/session.json", workdir="/project", timeout=180)

# Resume with session ID
terminal(command="claude -p 'Continue and add connection pooling' --resume $(cat /tmp/session.json | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"session_id\"])') --max-turns 5", workdir="/project", timeout=120)

# Or resume the most recent session in the same directory
terminal(command="claude -p 'What did you do last time?' --continue --max-turns 1", workdir="/project", timeout=30)

# Fork a session (new ID, keeps history)
terminal(command="claude -p 'Try a different approach' --resume <id> --fork-session --max-turns 10", workdir="/project", timeout=120)

用於 CI/腳本編寫的裸模式

terminal(command="claude --bare -p 'Run all tests and report failures' --allowedTools 'Read,Bash' --max-turns 10", workdir="/project", timeout=180)

--bare 跳過鉤子、插件、MCP 發現和 CLAUDE.md 加載。啟動速度最快。需要 ANTHROPIC_API_KEY(跳過 OAuth)。

要在裸模式中選擇性加載上下文:

要加載的內容標誌
系統提示附加內容--append-system-prompt "text"--append-system-prompt-file path
設置--settings <file-or-json>
MCP 服務器--mcp-config <file-or-json>
自定義代理--agents '<json>'

過載時的回退模型

terminal(command="claude -p 'task' --fallback-model haiku --max-turns 5", timeout=90)

當默認模型過載時,自動回退到指定模型(僅限打印模式)。

完整 CLI 標誌參考

會話與環境

標誌效果
-p, --print非交互式一次性模式(完成後退出)
-c, --continue恢復當前目錄中最近的對話
-r, --resume <id>按 ID 或名稱恢復特定會話(如果沒有 ID,則使用交互式選擇器)
--fork-session恢復時,創建新的會話 ID 而不是重用原始 ID
--session-id <uuid>為對話使用特定的 UUID
--no-session-persistence不將會話保存到磁盤(僅限打印模式)
--add-dir <paths...>授予 Claude 訪問其他工作目錄的權限
-w, --worktree [name].claude/worktrees/<name> 處的隔離 git worktree 中運行
--tmux為 worktree 創建 tmux 會話(需要 --worktree
--ide啟動時自動連接到有效的 IDE
--chrome / --no-chrome啟用/禁用 Chrome 瀏覽器集成以進行 Web 測試
--from-pr [number]恢復鏈接到特定 GitHub PR 的會話
--file <specs...>啟動時下載的文件資源(格式:file_id:relative_path

模型與性能

標誌效果
--model <alias>模型選擇:sonnetopushaiku,或完整名稱如 claude-sonnet-4-6
--effort <level>推理深度:lowmediumhighmaxauto
--max-turns <n>限制代理循環次數(僅限打印模式;防止失控)
--max-budget-usd <n>限制 API 支出上限(美元)(僅限打印模式)
--fallback-model <model>當默認模型過載時自動回退(僅限打印模式)
--betas <betas...>在 API 請求中包含的 Beta 頭信息(僅限 API 密鑰用戶)

權限與安全

標誌效果
--dangerously-skip-permissions自動批准所有工具使用(文件寫入、bash、網絡等)
--allow-dangerously-skip-permissions將繞過權限作為選項啟用,但不默認啟用
--permission-mode <mode>defaultacceptEditsplanautodontAskbypassPermissions
--allowedTools <tools...>白名單特定工具(逗號或空格分隔)
--disallowedTools <tools...>黑名單特定工具
--tools <tools...>覆蓋內置工具集("" = 無,"default" = 全部,或工具名稱)

輸出與輸入格式

標誌效果
--output-format <fmt>text(默認)、json(單個結果對象)、stream-json(換行符分隔)
--input-format <fmt>text(默認)或 stream-json(實時流式輸入)
--json-schema <schema>強制輸出符合 schema 的結構化 JSON
--verbose完整的逐輪輸出
--include-partial-messages包含到達時的部分消息塊(stream-json + 打印)
--replay-user-messages在 stdout 上重新發出用戶消息(stream-json 雙向)

系統提示詞與上下文

標誌效果
--append-system-prompt <text>追加到默認系統提示詞(保留內置功能)
--append-system-prompt-file <path>將文件內容追加到默認系統提示詞
--system-prompt <text>替換整個系統提示詞(通常建議使用 --append)
--system-prompt-file <path>用文件內容替換系統提示詞
--bare跳過鉤子、插件、MCP 發現、CLAUDE.md、OAuth(最快啟動)
--agents '<json>'以 JSON 形式動態定義自定義子代理
--mcp-config <path>從 JSON 文件加載 MCP 服務器(可重複)
--strict-mcp-config僅使用來自 --mcp-config 的 MCP 服務器,忽略所有其他 MCP 配置
--settings <file-or-json>從 JSON 文件或內聯 JSON 加載附加設置
--setting-sources <sources>要加載的源,逗號分隔:userprojectlocal
--plugin-dir <paths...>僅為此會話從目錄加載插件
--disable-slash-commands禁用所有技能/斜槓命令

調試

標誌效果
-d, --debug [filter]啟用調試日誌記錄,帶有可選類別過濾器(例如 "api,hooks""!1p,!file"
--debug-file <path>將調試日誌寫入文件(隱式啟用調試模式)

代理團隊

標誌效果
--teammate-mode <mode>代理團隊顯示方式:autoin-processtmux
--brief啟用 SendUserMessage 工具用於代理到用戶的通信

--allowedTools / --disallowedTools 的工具名稱語法

Read                    # All file reading
Edit # File editing (existing files)
Write # File creation (new files)
Bash # All shell commands
Bash(git *) # Only git commands
Bash(git commit *) # Only git commit commands
Bash(npm run lint:*) # Pattern matching with wildcards
WebSearch # Web search capability
WebFetch # Web page fetching
mcp__<server>__<tool> # Specific MCP tool

設置與配置

設置層級(優先級從高到低)

  1. CLI 標誌 — 覆蓋所有內容
  2. 本地項目: .claude/settings.local.json(個人,被 git 忽略)
  3. 項目: .claude/settings.json(共享,受 git 跟蹤)
  4. 用戶: ~/.claude/settings.json(全局)

設置中的權限

{
"permissions": {
"allow": ["Bash(npm run lint:*)", "WebSearch", "Read"],
"ask": ["Write(*.ts)", "Bash(git push*)"],
"deny": ["Read(.env)", "Bash(rm -rf *)"]
}
}

記憶文件 (CLAUDE.md) 層級

  1. 全局: ~/.claude/CLAUDE.md — 適用於所有項目
  2. 項目: ./CLAUDE.md — 項目特定上下文(受 git 跟蹤)
  3. 本地: .claude/CLAUDE.local.md — 個人項目覆蓋(被 git 忽略)

在交互模式下使用 # 前綴快速添加到記憶:# Always use 2-space indentation

交互會話:斜槓命令

會話與上下文

命令用途
/help顯示所有命令(包括自定義和 MCP 命令)
/compact [focus]壓縮上下文以節省 token;CLAUDE.md 在壓縮後保留。例如:/compact focus on auth logic
/clear清除對話歷史以重新開始
/context以彩色網格可視化上下文使用情況,並提供優化建議
/cost查看 token 使用情況,包含每個模型和緩存命中率的細分
/resume切換或恢復不同的會話
/rewind回退到對話或代碼中的先前檢查點
/btw <question>提出側面問題而不增加上下文成本
/status顯示版本、連接性和會話信息
/todos列出對話中跟蹤的行動項
/exitCtrl+D結束會話

開發與審查

命令用途
/review請求對當前更改進行代碼審查
/security-review對當前更改執行安全分析
/plan [description]進入計劃模式並自動開始任務規劃
/loop [interval]在會話中安排重複任務
/batch為大型並行更改自動創建工作樹(5-30 個工作樹)

配置與工具

命令用途
/model [model]在會話中途切換模型(使用方向鍵調整推理力度)
/effort [level]設置推理力度:lowmediumhighmaxauto
/init創建 CLAUDE.md 文件以存儲項目記憶
/memory打開 CLAUDE.md 進行編輯
/config打開交互式設置配置
/permissions查看/更新工具權限
/agents管理專用子代理(subagents)
/mcp用於管理 MCP 服務器的交互式界面
/add-dir添加額外的工作目錄(對單體倉庫很有用)
/usage顯示計劃限額和速率限制狀態
/voice啟用按住說話語音模式(支持 20 種語言;按住空格鍵錄音,鬆開發送)
/release-notes用於選擇版本發佈說明的交互式選擇器

自定義斜槓命令

創建 .claude/commands/<name>.md(項目共享)或 ~/.claude/commands/<name>.md(個人):

# .claude/commands/deploy.md
Run the deploy pipeline:
1. Run all tests
2. Build the Docker image
3. Push to registry
4. Update the $ARGUMENTS environment (default: staging)

用法:/deploy production$ARGUMENTS 將被替換為用戶的輸入。

技能(自然語言調用)

與斜槓命令(手動調用)不同,.claude/skills/ 中的技能是 Markdown 指南,當任務匹配時,Claude 會通過自然語言自動調用它們:

# .claude/skills/database-migration.md
When asked to create or modify database migrations:
1. Use Alembic for migration generation
2. Always create a rollback function
3. Test migrations against a local database copy

交互式會話:鍵盤快捷鍵

常規控制

按鍵操作
Ctrl+C取消當前輸入或生成
Ctrl+D退出會話
Ctrl+R反向搜索命令歷史
Ctrl+B將正在運行的任務置於後臺
Ctrl+V將圖片粘貼到對話中
Ctrl+O轉錄模式 — 查看 Claude 的思考過程
Ctrl+GCtrl+X Ctrl+E在外部編輯器中打開提示詞
Esc Esc回退對話或代碼狀態 / 總結

模式切換

按鍵操作
Shift+Tab循環切換權限模式(正常 → 自動接受 → 計劃)
Alt+P切換模型
Alt+T切換思考模式
Alt+O切換快速模式

多行輸入

按鍵操作
\ + Enter快速換行
Shift+Enter換行(替代方式)
Ctrl+J換行(替代方式)

輸入前綴

前綴操作
!直接執行 bash,繞過 AI(例如 !npm test)。單獨使用 ! 可切換 shell 模式。
@引用文件/目錄並支持自動補全(例如 @./src/api/
#快速添加到 CLAUDE.md 記憶(例如 # Use 2-space indentation
/斜槓命令

專業提示:"ultrathink"

在提示詞中使用關鍵字 "ultrathink",以便在特定輪次中獲得最大推理力度。無論當前的 /effort 設置如何,這都會觸發最深度的思考模式。

PR 審查模式

快速審查(打印模式)

terminal(command="cd /path/to/repo && git diff main...feature-branch | claude -p 'Review this diff for bugs, security issues, and style problems. Be thorough.' --max-turns 1", timeout=60)

深度審查(交互式 + Worktree)

terminal(command="tmux new-session -d -s review -x 140 -y 40")
terminal(command="tmux send-keys -t review 'cd /path/to/repo && claude -w pr-review' Enter")
terminal(command="sleep 5 && tmux send-keys -t review Enter") # Trust dialog
terminal(command="sleep 2 && tmux send-keys -t review 'Review all changes vs main. Check for bugs, security issues, race conditions, and missing tests.' Enter")
terminal(command="sleep 30 && tmux capture-pane -t review -p -S -60")

通過編號進行 PR 審查

terminal(command="claude -p 'Review this PR thoroughly' --from-pr 42 --max-turns 10", workdir="/path/to/repo", timeout=120)

帶有 tmux 的 Claude Worktree

terminal(command="claude -w feature-x --tmux", workdir="/path/to/repo")

.claude/worktrees/feature-x 創建一個隔離的 git worktree,併為其創建一個 tmux 會話。如果可用,會使用 iTerm2 原生窗格;添加 --tmux=classic 以使用傳統 tmux。

並行 Claude 實例

同時運行多個獨立的 Claude 任務:

# Task 1: Fix backend
terminal(command="tmux new-session -d -s task1 -x 140 -y 40 && tmux send-keys -t task1 'cd ~/project && claude -p \"Fix the auth bug in src/auth.py\" --allowedTools \"Read,Edit\" --max-turns 10' Enter")

# Task 2: Write tests
terminal(command="tmux new-session -d -s task2 -x 140 -y 40 && tmux send-keys -t task2 'cd ~/project && claude -p \"Write integration tests for the API endpoints\" --allowedTools \"Read,Write,Bash\" --max-turns 15' Enter")

# Task 3: Update docs
terminal(command="tmux new-session -d -s task3 -x 140 -y 40 && tmux send-keys -t task3 'cd ~/project && claude -p \"Update README.md with the new API endpoints\" --allowedTools \"Read,Edit\" --max-turns 5' Enter")

# Monitor all
terminal(command="sleep 30 && for s in task1 task2 task3; do echo '=== '$s' ==='; tmux capture-pane -t $s -p -S -5 2>/dev/null; done")

CLAUDE.md — 項目上下文文件

Claude Code 會自動從項目根目錄加載 CLAUDE.md。使用它來持久化項目上下文:

# Project: My API

## Architecture
- FastAPI backend with SQLAlchemy ORM
- PostgreSQL database, Redis cache
- pytest for testing with 90% coverage target

## Key Commands
- `make test` — run full test suite
- `make lint` — ruff + mypy
- `make dev` — start dev server on :8000

## Code Standards
- Type hints on all public functions
- Docstrings in Google style
- 2-space indentation for YAML, 4-space for Python
- No wildcard imports

具體明確。 不要使用“編寫好代碼”,而應使用“JS 使用 2 空格縮進”或“測試文件名稱使用 .test.ts 後綴”。具體的指令可以節省修正循環的時間。

規則目錄(模塊化 CLAUDE.md)

對於擁有許多規則的項目,使用規則目錄而不是一個巨大的 CLAUDE.md:

  • 項目規則: .claude/rules/*.md — 團隊共享,由 git 跟蹤
  • 用戶規則: ~/.claude/rules/*.md — 個人,全局

規則目錄中的每個 .md 文件都會作為附加上下文加載。這比將所有內容塞進單個 CLAUDE.md 更清晰。

自動記憶

Claude 會自動將學到的項目上下文存儲在 ~/.claude/projects/<project>/memory/ 中。

  • 限制: 每個項目 25KB 或 200 行
  • 這與 CLAUDE.md 分開——它是 Claude 自己關於項目的筆記,跨會話累積

自定義子代理

.claude/agents/(項目)、~/.claude/agents/(個人)中定義專用代理,或通過 --agents CLI 標誌(會話)定義:

代理位置優先級

  1. .claude/agents/ — 項目級,團隊共享
  2. --agents CLI 標誌 — 會話特定,動態
  3. ~/.claude/agents/ — 用戶級,個人

創建代理

# .claude/agents/security-reviewer.md
---
name: security-reviewer
description: Security-focused code review
model: opus
tools: [Read, Bash]
---
You are a senior security engineer. Review code for:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication/authorization flaws
- Secrets in code
- Unsafe deserialization

調用方式:@security-reviewer review the auth module

通過 CLI 動態代理

terminal(command="claude --agents '{\"reviewer\": {\"description\": \"Reviews code\", \"prompt\": \"You are a code reviewer focused on performance\"}}' -p 'Use @reviewer to check auth.py'", timeout=120)

Claude 可以協調多個代理:“使用 @db-expert 優化查詢,然後使用 @security 審計更改。”

Hooks — 事件自動化

.claude/settings.json(項目)或 ~/.claude/settings.json(全局)中配置:

{
"hooks": {
"PostToolUse": [{
"matcher": "Write(*.py)",
"hooks": [{"type": "command", "command": "ruff check --fix $CLAUDE_FILE_PATHS"}]
}],
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{"type": "command", "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'rm -rf'; then echo 'Blocked!' && exit 2; fi"}]
}],
"Stop": [{
"hooks": [{"type": "command", "command": "echo 'Claude finished a response' >> /tmp/claude-activity.log"}]
}]
}
}

全部 8 種 Hook 類型

Hook觸發時機常見用途
UserPromptSubmit在 Claude 處理用戶提示之前輸入驗證、日誌記錄
PreToolUse在工具執行之前安全門禁、阻止危險命令(exit 2 = 阻止)
PostToolUse在工具完成後自動格式化代碼、運行 linter
Notification在權限請求或等待輸入時桌面通知、警報
Stop當 Claude 完成響應時完成日誌記錄、狀態更新
SubagentStop當子代理(subagent)完成時代理編排
PreCompact在清除上下文內存之前備份會話轉錄內容
SessionStart當會話開始時加載開發上下文(例如,git status

Hook 環境變量

變量內容
CLAUDE_PROJECT_DIR當前項目路徑
CLAUDE_FILE_PATHS正在修改的文件
CLAUDE_TOOL_INPUT工具參數(JSON 格式)

安全 Hook 示例

{
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{"type": "command", "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'rm -rf|git push.*--force|:(){ :|:& };:'; then echo 'Dangerous command blocked!' && exit 2; fi"}]
}]
}

MCP 集成

為數據庫、API 和服務添加外部工具服務器:

# GitHub integration
terminal(command="claude mcp add -s user github -- npx @modelcontextprotocol/server-github", timeout=30)

# PostgreSQL queries
terminal(command="claude mcp add -s local postgres -- npx @anthropic-ai/server-postgres --connection-string postgresql://localhost/mydb", timeout=30)

# Puppeteer for web testing
terminal(command="claude mcp add puppeteer -- npx @anthropic-ai/server-puppeteer", timeout=30)

MCP 作用域

標誌作用域存儲位置
-s user全局(所有項目)~/.claude.json
-s local當前項目(個人).claude/settings.local.json(被 git 忽略)
-s project當前項目(團隊共享).claude/settings.json(由 git 跟蹤)

打印/CI 模式中的 MCP

terminal(command="claude --bare -p 'Query database' --mcp-config mcp-servers.json --strict-mcp-config", timeout=60)

--strict-mcp-config 會忽略除 --mcp-config 指定的 MCP 服務器之外的所有 MCP 服務器。

在聊天中引用 MCP 資源:@github:issue://123

MCP 限制與調優

  • 工具描述: 每個服務器的工具描述和服務器指令上限為 2KB
  • 結果大小: 默認有上限;使用 maxResultSizeChars 註解允許大型輸出最多達到 50萬 個字符
  • 輸出 Token: export MAX_MCP_OUTPUT_TOKENS=50000 — 限制來自 MCP 服務器的輸出,以防止上下文氾濫
  • 傳輸方式: stdio(本地進程)、http(遠程)、sse(服務器發送事件)

監控交互式會話

閱讀 TUI 狀態

# Periodic capture to check if Claude is still working or waiting for input
terminal(command="tmux capture-pane -t dev -p -S -10")

留意以下指示符:

  • 底部的 = 等待你的輸入(Claude 已完成或正在提問)
  • 行 = Claude 正在 actively 使用工具(讀取、寫入、運行命令)
  • ⏵⏵ bypass permissions on = 狀態欄顯示權限模式
  • ◐ medium · /effort = 狀態欄中當前的努力程度級別
  • ctrl+o to expand = 工具輸出被截斷(可以交互式展開)

上下文窗口健康狀態

在交互模式下使用 /context 查看上下文使用情況的彩色網格。關鍵閾值:

  • < 70% — 正常運行,精度完整
  • 70-85% — 精度開始下降,考慮使用 /compact
  • > 85% — 幻覺風險顯著增加,使用 /compact/clear

環境變量

變量效果
ANTHROPIC_API_KEY用於身份驗證的 API 密鑰(OAuth 的替代方案)
CLAUDE_CODE_EFFORT_LEVEL默認努力程度:lowmediumhighmaxauto
MAX_THINKING_TOKENS限制思考 token(設置為 0 以完全禁用思考)
MAX_MCP_OUTPUT_TOKENS限制來自 MCP 服務器的輸出(默認值各異;例如設置為 50000
CLAUDE_CODE_NO_FLICKER=1啟用備用屏幕渲染以消除終端閃爍
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB從子進程中剝離憑據以確保安全

成本與性能技巧

  1. 在打印模式中使用 --max-turns 以防止無限循環。大多數任務從 5-10 次開始。
  2. 使用 --max-budget-usd 設置成本上限。注意:創建系統提示緩存最低需要約 $0.05。
  3. 對於簡單任務使用 --effort low(更快、更便宜)。對於複雜推理使用 highmax
  4. 對於 CI/腳本編寫使用 --bare 以跳過插件/hook 發現開銷。
  5. 使用 --allowedTools 僅限制為所需的工具(例如,審查時僅允許 Read)。
  6. 在交互式會話中,當上下文變大時使用 /compact
  7. 當你只需要分析已知內容時,管道輸入 而不是讓 Claude 讀取文件。
  8. 對於簡單任務使用 --model haiku(更便宜),對於複雜的多步驟工作使用 --model opus
  9. 在打印模式中使用 --fallback-model haiku 以優雅地處理模型過載。
  10. 為不同的任務開始新會話 — 會話持續 5 小時;新鮮的上下文更高效。
  11. 在 CI 中使用 --no-session-persistence 以避免在磁盤上累積保存的會話。

陷阱與注意事項

  1. 交互模式需要 tmux — Claude Code 是一個完整的 TUI 應用程序。在 Hermes 終端中僅使用 pty=true 雖然可行,但 tmux 提供了用於監控的 capture-pane 和用於輸入的 send-keys,這對於編排至關重要。
  2. --dangerously-skip-permissions 對話框默認為“No, exit” — 你必須發送 Down(下箭頭)然後 Enter(回車)來接受。打印模式(-p)會完全跳過此步驟。
  3. --max-budget-usd 的最小值約為 $0.05 — 僅系統提示緩存創建就會消耗這麼多費用。設置更低的值會立即報錯。
  4. --max-turns 僅適用於打印模式 — 在交互會話中會被忽略。
  5. Claude 可能使用 python 而非 python3 — 在沒有 python 符號鏈接的系統上,Claude 的 bash 命令首次嘗試時會失敗,但它會自動修正。
  6. 會話恢復需要相同的目錄--continue 會查找當前工作目錄最近的會話。
  7. --json-schema 需要足夠的 --max-turns — Claude 必須在生成結構化輸出之前讀取文件,這需要多個回合。
  8. 信任對話框每個目錄僅出現一次 — 僅在首次使用時出現,之後會被緩存。
  9. 後臺 tmux 會話會持續存在 — 完成後務必使用 tmux kill-session -t <name> 進行清理。
  10. 斜槓命令(如 /commit)僅在交互模式下有效 — 在 -p 模式下,請用自然語言描述任務。
  11. --bare 跳過 OAuth — 需要設置 ANTHROPIC_API_KEY 環境變量或在設置中配置 apiKeyHelper
  12. 上下文退化是真實存在的 — 當上下文窗口使用率超過 70% 時,AI 輸出質量會顯著下降。請使用 /context 監控並主動使用 /compact 壓縮上下文。

Hermes Agent 規則

  1. 單個任務優先使用打印模式(-p — 更乾淨,無需處理對話框,支持結構化輸出
  2. 多輪交互工作使用 tmux — 這是編排 TUI 的唯一可靠方式
  3. 始終設置 workdir — 讓 Claude 專注於正確的項目目錄
  4. 在打印模式中設置 --max-turns — 防止無限循環和成本失控
  5. 監控 tmux 會話 — 使用 tmux capture-pane -t <session> -p -S -50 檢查進度
  6. 留意 提示符 — 表示 Claude 正在等待輸入(已完成或提出問題)
  7. 清理 tmux 會話 — 完成後終止會話以避免資源洩漏
  8. 向用戶報告結果 — 完成後,總結 Claude 執行的操作及變更內容
  9. 不要終止運行緩慢的會話 — Claude 可能正在執行多步工作;請改為檢查進度
  10. 使用 --allowedTools — 將功能限制為任務實際所需的範圍