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 update或claude 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 用於成功/錯誤檢測(success、error_max_turns、error_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'
流事件包括帶有 attempt、max_retries 和 error 字段(例如 rate_limit、billing_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> | 模型選擇:sonnet、opus、haiku,或完整名稱如 claude-sonnet-4-6 |
--effort <level> | 推理深度:low、medium、high、max、auto |
--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> | default、acceptEdits、plan、auto、dontAsk、bypassPermissions |
--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> | 要加載的源,逗號分隔:user、project、local |
--plugin-dir <paths...> | 僅為此會話從目錄加載插件 |
--disable-slash-commands | 禁用所有技能/斜槓命令 |
調試
| 標誌 | 效果 |
|---|---|
-d, --debug [filter] | 啟用調試日誌記錄,帶有可選類別過濾器(例如 "api,hooks"、"!1p,!file") |
--debug-file <path> | 將調試日誌寫入文件(隱式啟用調試模式) |
代理團隊
| 標誌 | 效果 |
|---|---|
--teammate-mode <mode> | 代理團隊顯示方式:auto、in-process 或 tmux |
--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
設置與配置
設置層級(優先級從高到低)
- CLI 標誌 — 覆蓋所有內容
- 本地項目:
.claude/settings.local.json(個人,被 git 忽略) - 項目:
.claude/settings.json(共享,受 git 跟蹤) - 用戶:
~/.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) 層級
- 全局:
~/.claude/CLAUDE.md— 適用於所有項目 - 項目:
./CLAUDE.md— 項目特定上下文(受 git 跟蹤) - 本地:
.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 | 列出對話中跟蹤的行動項 |
/exit 或 Ctrl+D | 結束會話 |
開發與審查
| 命令 | 用途 |
|---|---|
/review | 請求對當前更改進行代碼審查 |
/security-review | 對當前更改執行安全分析 |
/plan [description] | 進入計劃模式並自動開始任務規劃 |
/loop [interval] | 在會話中安排重複任務 |
/batch | 為大型並行更改自動創建工作樹(5-30 個工作樹) |
配置與工具
| 命令 | 用途 |
|---|---|
/model [model] | 在會話中途切換模型(使用方向鍵調整推理力度) |
/effort [level] | 設置推理力度:low、medium、high、max 或 auto |
/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+G 或 Ctrl+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 標誌(會話)定義:
代理位置優先級
.claude/agents/— 項目級,團隊共享--agentsCLI 標誌 — 會話特定,動態~/.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 | 默認努力程度:low、medium、high、max 或 auto |
MAX_THINKING_TOKENS | 限制思考 token(設置為 0 以完全禁用思考) |
MAX_MCP_OUTPUT_TOKENS | 限制來自 MCP 服務器的輸出(默認值各異;例如設置為 50000) |
CLAUDE_CODE_NO_FLICKER=1 | 啟用備用屏幕渲染以消除終端閃爍 |
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB | 從子進程中剝離憑據以確保安全 |
成本與性能技巧
- 在打印模式中使用
--max-turns以防止無限循環。大多數任務從 5-10 次開始。 - 使用
--max-budget-usd設置成本上限。注意:創建系統提示緩存最低需要約 $0.05。 - 對於簡單任務使用
--effort low(更快、更便宜)。對於複雜推理使用high或max。 - 對於 CI/腳本編寫使用
--bare以跳過插件/hook 發現開銷。 - 使用
--allowedTools僅限制為所需的工具(例如,審查時僅允許Read)。 - 在交互式會話中,當上下文變大時使用
/compact。 - 當你只需要分析已知內容時,管道輸入 而不是讓 Claude 讀取文件。
- 對於簡單任務使用
--model haiku(更便宜),對於複雜的多步驟工作使用--model opus。 - 在打印模式中使用
--fallback-model haiku以優雅地處理模型過載。 - 為不同的任務開始新會話 — 會話持續 5 小時;新鮮的上下文更高效。
- 在 CI 中使用
--no-session-persistence以避免在磁盤上累積保存的會話。
陷阱與注意事項
- 交互模式需要 tmux — Claude Code 是一個完整的 TUI 應用程序。在 Hermes 終端中僅使用
pty=true雖然可行,但 tmux 提供了用於監控的capture-pane和用於輸入的send-keys,這對於編排至關重要。 --dangerously-skip-permissions對話框默認為“No, exit” — 你必須發送 Down(下箭頭)然後 Enter(回車)來接受。打印模式(-p)會完全跳過此步驟。--max-budget-usd的最小值約為 $0.05 — 僅系統提示緩存創建就會消耗這麼多費用。設置更低的值會立即報錯。--max-turns僅適用於打印模式 — 在交互會話中會被忽略。- Claude 可能使用
python而非python3— 在沒有python符號鏈接的系統上,Claude 的 bash 命令首次嘗試時會失敗,但它會自動修正。 - 會話恢復需要相同的目錄 —
--continue會查找當前工作目錄最近的會話。 --json-schema需要足夠的--max-turns— Claude 必須在生成結構化輸出之前讀取文件,這需要多個回合。- 信任對話框每個目錄僅出現一次 — 僅在首次使用時出現,之後會被緩存。
- 後臺 tmux 會話會持續存在 — 完成後務必使用
tmux kill-session -t <name>進行清理。 - 斜槓命令(如
/commit)僅在交互模式下有效 — 在-p模式下,請用自然語言描述任務。 --bare跳過 OAuth — 需要設置ANTHROPIC_API_KEY環境變量或在設置中配置apiKeyHelper。- 上下文退化是真實存在的 — 當上下文窗口使用率超過 70% 時,AI 輸出質量會顯著下降。請使用
/context監控並主動使用/compact壓縮上下文。
Hermes Agent 規則
- 單個任務優先使用打印模式(
-p) — 更乾淨,無需處理對話框,支持結構化輸出 - 多輪交互工作使用 tmux — 這是編排 TUI 的唯一可靠方式
- 始終設置
workdir— 讓 Claude 專注於正確的項目目錄 - 在打印模式中設置
--max-turns— 防止無限循環和成本失控 - 監控 tmux 會話 — 使用
tmux capture-pane -t <session> -p -S -50檢查進度 - 留意
❯提示符 — 表示 Claude 正在等待輸入(已完成或提出問題) - 清理 tmux 會話 — 完成後終止會話以避免資源洩漏
- 向用戶報告結果 — 完成後,總結 Claude 執行的操作及變更內容
- 不要終止運行緩慢的會話 — Claude 可能正在執行多步工作;請改為檢查進度
- 使用
--allowedTools— 將功能限制為任務實際所需的範圍