claude-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClaude Code — Hermes Orchestration Guide
Claude Code — Hermes编排指南
Delegate coding tasks to Claude Code (Anthropic's autonomous coding agent CLI) via the Hermes terminal. Claude Code v2.x can read files, write code, run shell commands, spawn subagents, and manage git workflows autonomously.
通过Hermes终端将编码任务委托给Claude Code(Anthropic的自主编码代理CLI)。Claude Code v2.x可以自主读取文件、编写代码、运行shell命令、生成子代理以及管理git工作流。
Prerequisites
前提条件
- Install:
npm install -g @anthropic-ai/claude-code - Auth: run once to log in (browser OAuth for Pro/Max, or set
claude)ANTHROPIC_API_KEY - Console auth: for API key billing
claude auth login --console - SSO auth: for Enterprise
claude auth login --sso - Check status: (JSON) or
claude auth status(human-readable)claude auth status --text - Health check: — checks auto-updater and installation health
claude doctor - Version check: (requires v2.x+)
claude --version - Update: or
claude updateclaude upgrade
- 安装:
npm install -g @anthropic-ai/claude-code - 认证: 运行一次进行登录(Pro/Max版本使用浏览器OAuth,或设置
claude)ANTHROPIC_API_KEY - 控制台认证: 使用进行API密钥计费
claude auth login --console - SSO认证: 企业用户使用
claude auth login --sso - 检查状态: (返回JSON格式)或
claude auth status(人类可读格式)claude auth status --text - 健康检查: — 检查自动更新器和安装状态
claude doctor - 版本检查: (需要v2.x及以上版本)
claude --version - 更新: 或
claude updateclaude upgrade
Two Orchestration Modes
两种编排模式
Hermes interacts with Claude Code in two fundamentally different ways. Choose based on the task.
Hermes与Claude Code的交互分为两种完全不同的模式,可根据任务类型选择。
Mode 1: Print Mode (-p
) — Non-Interactive (PREFERRED for most tasks)
-p模式1:打印模式(-p
) — 非交互式(大多数任务首选)
-pPrint mode runs a one-shot task, returns the result, and exits. No PTY needed. No interactive prompts. This is the cleanest integration path.
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)When to use print mode:
- One-shot coding tasks (fix a bug, add a feature, refactor)
- CI/CD automation and scripting
- Structured data extraction with
--json-schema - Piped input processing ()
cat file | claude -p "analyze this" - Any task where you don't need multi-turn conversation
Print mode skips ALL interactive dialogs — no workspace trust prompt, no permission confirmations. This makes it ideal for automation.
打印模式执行一次性任务,返回结果后退出,无需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)适用场景:
- 一次性编码任务(修复bug、添加功能、重构)
- CI/CD自动化与脚本
- 使用进行结构化数据提取
--json-schema - 管道输入处理()
cat file | claude -p "analyze this" - 无需多轮对话的任何任务
打印模式会跳过所有交互式对话框 — 无工作区信任提示,无权限确认,非常适合自动化场景。
Mode 2: Interactive PTY via tmux — Multi-Turn Sessions
模式2:通过tmux实现交互式PTY — 多轮会话
Interactive mode gives you a full conversational REPL where you can send follow-up prompts, use slash commands, and watch Claude work in real time. Requires tmux orchestration.
undefined交互式模式提供完整的对话式REPL,你可以发送后续提示、使用斜杠命令,并实时查看Claude的工作过程。需要tmux编排支持。
undefinedStart a tmux session
启动tmux会话
terminal(command="tmux new-session -d -s claude-work -x 140 -y 40")
terminal(command="tmux new-session -d -s claude-work -x 140 -y 40")
Launch Claude Code inside it
在会话中启动Claude Code
terminal(command="tmux send-keys -t claude-work 'cd /path/to/project && claude' Enter")
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)
(欢迎界面加载需约3-5秒)
terminal(command="sleep 5 && tmux send-keys -t claude-work 'Refactor the auth module to use JWT tokens' Enter")
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")
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")
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")
**When to use interactive mode:**
- Multi-turn iterative work (refactor → review → fix → test cycle)
- Tasks requiring human-in-the-loop decisions
- Exploratory coding sessions
- When you need to use Claude's slash commands (`/compact`, `/review`, `/model`)terminal(command="tmux send-keys -t claude-work '/exit' Enter")
**适用场景:**
- 多轮迭代工作(重构→评审→修复→测试循环)
- 需要人工介入决策的任务
- 探索性编码会话
- 需要使用Claude斜杠命令的场景(`/compact`、`/review`、`/model`)PTY Dialog Handling (CRITICAL for Interactive Mode)
PTY对话框处理(交互式模式必备)
Claude Code presents up to two confirmation dialogs on first launch. You MUST handle these via tmux send-keys:
Claude Code首次启动时会显示最多两个确认对话框,你必须通过tmux send-keys处理:
Dialog 1: Workspace Trust (first visit to a directory)
对话框1:工作区信任(首次访问目录)
❯ 1. Yes, I trust this folder ← DEFAULT (just press Enter)
2. No, exitHandling: — default selection is correct.
tmux send-keys -t <session> Enter❯ 1. Yes, I trust this folder ← 默认选项(直接按Enter)
2. No, exit处理方式: — 默认选择正确。
tmux send-keys -t <session> EnterDialog 2: Bypass Permissions Warning (only with --dangerously-skip-permissions)
对话框2:绕过权限警告(仅使用--dangerously-skip-permissions时出现)
❯ 1. No, exit ← DEFAULT (WRONG choice!)
2. Yes, I acceptHandling: Must navigate DOWN first, then Enter:
tmux send-keys -t <session> Down && sleep 0.3 && tmux send-keys -t <session> Enter❯ 1. No, exit ← 默认选项(错误选择!)
2. Yes, I accept处理方式: 必须先向下导航,再按Enter:
tmux send-keys -t <session> Down && sleep 0.3 && tmux send-keys -t <session> EnterRobust Dialog Handling Pattern
可靠的对话框处理模式
undefinedundefinedLaunch with permissions bypass
启动时绕过权限检查
terminal(command="tmux send-keys -t claude-work 'claude --dangerously-skip-permissions "your task"' Enter")
terminal(command="tmux send-keys -t claude-work 'claude --dangerously-skip-permissions "your task"' Enter")
Handle trust dialog (Enter for default "Yes")
处理信任对话框(按Enter选择默认的"Yes")
terminal(command="sleep 4 && tmux send-keys -t claude-work Enter")
terminal(command="sleep 4 && tmux send-keys -t claude-work Enter")
Handle permissions dialog (Down then Enter for "Yes, I accept")
处理权限对话框(先按Down再按Enter选择"Yes, I accept")
terminal(command="sleep 3 && tmux send-keys -t claude-work Down && sleep 0.3 && tmux send-keys -t claude-work Enter")
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
等待Claude执行任务
terminal(command="sleep 15 && tmux capture-pane -t claude-work -p -S -60")
**Note:** After the first trust acceptance for a directory, the trust dialog won't appear again. Only the permissions dialog recurs each time you use `--dangerously-skip-permissions`.terminal(command="sleep 15 && tmux capture-pane -t claude-work -p -S -60")
**注意:** 首次接受目录信任后,信任对话框不会再次出现。每次使用`--dangerously-skip-permissions`时,权限对话框会重复出现。CLI Subcommands
CLI子命令
| Subcommand | Purpose |
|---|---|
| Start interactive REPL |
| Start REPL with initial prompt |
| Print mode (non-interactive, exits when done) |
| Pipe content as stdin context |
| Continue the most recent conversation in this directory |
| Resume a specific session by ID or name |
| Sign in (add |
| Check login status (returns JSON; |
| Add an MCP server |
| List configured MCP servers |
| Remove an MCP server |
| List configured agents |
| Run health checks on installation and auto-updater |
| Update Claude Code to latest version |
| Start server to control Claude from claude.ai or mobile app |
| Install native build (stable, latest, or specific version) |
| Set up long-lived auth token (requires subscription) |
| Manage Claude Code plugins |
| Inspect auto mode classifier configuration |
| 子命令 | 用途 |
|---|---|
| 启动交互式REPL |
| 使用初始提示启动REPL |
| 打印模式(非交互式,完成后退出) |
| 将内容作为标准输入上下文传递 |
| 继续当前目录中最近的对话 |
| 通过ID或名称恢复特定会话 |
| 登录(添加 |
| 检查登录状态(返回JSON格式; |
| 添加MCP服务器 |
| 列出已配置的MCP服务器 |
| 删除MCP服务器 |
| 列出已配置的代理 |
| 对安装和自动更新器运行健康检查 |
| 将Claude Code更新到最新版本 |
| 启动服务器以从claude.ai或移动应用控制Claude |
| 安装原生构建版本(稳定版、最新版或特定版本) |
| 设置长期认证令牌(需要订阅) |
| 管理Claude Code插件 |
| 检查自动模式分类器配置 |
Print Mode Deep Dive
打印模式深入解析
Structured JSON Output
结构化JSON输出
terminal(command="claude -p 'Analyze auth.py for security issues' --output-format json --max-turns 5", workdir="/project", timeout=120)Returns a JSON object with:
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 } }
}Key fields: for resumption, for agentic loop count, for spend tracking, for success/error detection (, , ).
session_idnum_turnstotal_cost_usdsubtypesuccesserror_max_turnserror_budgetterminal(command="claude -p 'Analyze auth.py for security issues' --output-format json --max-turns 5", workdir="/project", timeout=120)返回JSON对象:
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_idnum_turnstotal_cost_usdsubtypesuccesserror_max_turnserror_budgetStreaming JSON Output
流式JSON输出
For real-time token streaming, use with :
stream-json--verboseterminal(command="claude -p 'Write a summary' --output-format stream-json --verbose --include-partial-messages", timeout=60)Returns newline-delimited JSON events. Filter with jq for live text:
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'Stream events include with , , and fields (e.g., , ).
system/api_retryattemptmax_retrieserrorrate_limitbilling_error如需实时令牌流,结合和使用:
stream-json--verboseterminal(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'流事件包含,带有、和字段(例如、)。
system/api_retryattemptmax_retrieserrorrate_limitbilling_errorBidirectional Streaming
双向流式传输
For real-time input AND output streaming:
claude -p "task" --input-format stream-json --output-format stream-json --replay-user-messages--replay-user-messages如需实时输入和输出流式传输:
claude -p "task" --input-format stream-json --output-format stream-json --replay-user-messages--replay-user-messagesPiped Input
管道输入
undefinedundefinedPipe a file for analysis
管道传输文件进行分析
terminal(command="cat src/auth.py | claude -p 'Review this code for bugs' --max-turns 1", timeout=60)
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)
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)
undefinedterminal(command="git diff HEAD~3 | claude -p 'Summarize these changes' --max-turns 1", timeout=60)
undefinedJSON Schema for Structured Extraction
用于结构化提取的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)Parse from the JSON result. Claude validates output against the schema before returning.
structured_outputterminal(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结果中解析。Claude会在返回前验证输出是否符合Schema。
structured_outputSession Continuation
会话续接
undefinedundefinedStart a task
启动任务
terminal(command="claude -p 'Start refactoring the database layer' --output-format json --max-turns 10 > /tmp/session.json", workdir="/project", timeout=180)
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
使用会话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)
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)
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)
分支会话(新ID,保留历史记录)
terminal(command="claude -p 'Try a different approach' --resume <id> --fork-session --max-turns 10", workdir="/project", timeout=120)
undefinedterminal(command="claude -p 'Try a different approach' --resume <id> --fork-session --max-turns 10", workdir="/project", timeout=120)
undefinedBare Mode for CI/Scripting
适用于CI/脚本的裸模式
terminal(command="claude --bare -p 'Run all tests and report failures' --allowedTools 'Read,Bash' --max-turns 10", workdir="/project", timeout=180)--bareANTHROPIC_API_KEYTo selectively load context in bare mode:
| To load | Flag |
|---|---|
| System prompt additions | |
| Settings | |
| MCP servers | |
| Custom agents | |
terminal(command="claude --bare -p 'Run all tests and report failures' --allowedTools 'Read,Bash' --max-turns 10", workdir="/project", timeout=180)--bareANTHROPIC_API_KEY在裸模式下选择性加载上下文:
| 加载内容 | 参数 |
|---|---|
| 系统提示补充内容 | |
| 设置 | |
| MCP服务器 | |
| 自定义代理 | |
Fallback Model for Overload
过载时的 fallback 模型
terminal(command="claude -p 'task' --fallback-model haiku --max-turns 5", timeout=90)Automatically falls back to the specified model when the default is overloaded (print mode only).
terminal(command="claude -p 'task' --fallback-model haiku --max-turns 5", timeout=90)当默认模型过载时,自动切换到指定模型(仅适用于打印模式)。
Complete CLI Flags Reference
完整CLI参数参考
Session & Environment
会话与环境
| Flag | Effect |
|---|---|
| Non-interactive one-shot mode (exits when done) |
| Resume most recent conversation in current directory |
| Resume specific session by ID or name (interactive picker if no ID) |
| When resuming, create new session ID instead of reusing original |
| Use a specific UUID for the conversation |
| Don't save session to disk (print mode only) |
| Grant Claude access to additional working directories |
| Run in an isolated git worktree at |
| Create a tmux session for the worktree (requires |
| Auto-connect to a valid IDE on startup |
| Enable/disable Chrome browser integration for web testing |
| Resume session linked to a specific GitHub PR |
| File resources to download at startup (format: |
| 参数 | 作用 |
|---|---|
| 非交互式一次性模式(完成后退出) |
| 恢复当前目录中最近的对话 |
| 通过ID或名称恢复特定会话(无ID时显示交互式选择器) |
| 恢复会话时创建新会话ID,而非复用原ID |
| 使用特定UUID作为对话ID |
| 不将会话保存到磁盘(仅适用于打印模式) |
| 授予Claude访问额外工作目录的权限 |
| 在隔离的git工作树 |
| 为工作树创建tmux会话(需要 |
| 启动时自动连接到有效的IDE |
| 启用/禁用Chrome浏览器集成以进行Web测试 |
| 恢复与特定GitHub PR关联的会话 |
| 启动时下载的文件资源(格式: |
Model & Performance
模型与性能
| Flag | Effect |
|---|---|
| Model selection: |
| Reasoning depth: |
| Limit agentic loops (print mode only; prevents runaway) |
| Cap API spend in dollars (print mode only) |
| Auto-fallback when default model is overloaded (print mode only) |
| Beta headers to include in API requests (API key users only) |
| 参数 | 作用 |
|---|---|
| 模型选择: |
| 推理深度: |
| 限制代理循环次数(仅适用于打印模式;防止失控) |
| 限制API花费(美元,仅适用于打印模式) |
| 默认模型过载时自动切换(仅适用于打印模式) |
| API请求中包含的Beta头(仅API密钥用户可用) |
Permission & Safety
权限与安全
| Flag | Effect |
|---|---|
| Auto-approve ALL tool use (file writes, bash, network, etc.) |
| Enable bypass as an option without enabling it by default |
| |
| Whitelist specific tools (comma or space-separated) |
| Blacklist specific tools |
| Override built-in tool set ( |
| 参数 | 作用 |
|---|---|
| 自动批准所有工具使用(文件写入、bash、网络等) |
| 将绕过权限设置为可选,但默认不启用 |
| 权限模式: |
| 白名单特定工具(逗号或空格分隔) |
| 黑名单特定工具 |
| 覆盖内置工具集( |
Output & Input Format
输出与输入格式
| Flag | Effect |
|---|---|
| |
| |
| Force structured JSON output matching a schema |
| Full turn-by-turn output |
| Include partial message chunks as they arrive (stream-json + print) |
| Re-emit user messages on stdout (stream-json bidirectional) |
| 参数 | 作用 |
|---|---|
| 输出格式: |
| 输入格式: |
| 强制输出符合指定Schema的结构化JSON |
| 完整的逐轮输出 |
| 包含到达的部分消息块(stream-json + 打印模式) |
| 在标准输出重新发送用户消息(双向stream-json) |
System Prompt & Context
系统提示与上下文
| Flag | Effect |
|---|---|
| Add to the default system prompt (preserves built-in capabilities) |
| Add file contents to the default system prompt |
| Replace the entire system prompt (use --append instead usually) |
| Replace the system prompt with file contents |
| Skip hooks, plugins, MCP discovery, CLAUDE.md, OAuth (fastest startup) |
| Define custom subagents dynamically as JSON |
| Load MCP servers from JSON file (repeatable) |
| Only use MCP servers from |
| Load additional settings from a JSON file or inline JSON |
| Comma-separated sources to load: |
| Load plugins from directories for this session only |
| Disable all skills/slash commands |
| 参数 | 作用 |
|---|---|
| 添加到默认系统提示(保留内置功能) |
| 添加文件内容到默认系统提示 |
| 替换整个系统提示(通常建议使用--append) |
| 替换系统提示为文件内容 |
| 跳过钩子、插件、MCP发现、CLAUDE.md、OAuth(启动速度最快) |
| 动态定义自定义子代理(JSON格式) |
| 从JSON文件加载MCP服务器(可重复使用) |
| 仅使用 |
| 从JSON文件或内联JSON加载额外设置 |
| 逗号分隔的加载来源: |
| 仅在本次会话中从指定目录加载插件 |
| 禁用所有技能/斜杠命令 |
Debugging
调试
| Flag | Effect |
|---|---|
| Enable debug logging with optional category filter (e.g., |
| Write debug logs to file (implicitly enables debug mode) |
| 参数 | 作用 |
|---|---|
| 启用调试日志,可选择类别过滤(例如 |
| 将调试日志写入文件(隐式启用调试模式) |
Agent Teams
代理团队
| Flag | Effect |
|---|---|
| How agent teams display: |
| Enable |
| 参数 | 作用 |
|---|---|
| 代理团队显示方式: |
| 启用 |
Tool Name Syntax for --allowedTools / --disallowedTools
--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 toolRead # 所有文件读取操作
Edit # 文件编辑(现有文件)
Write # 文件创建(新文件)
Bash # 所有shell命令
Bash(git *) # 仅git命令
Bash(git commit *) # 仅git commit命令
Bash(npm run lint:*) # 带通配符的模式匹配
WebSearch # Web搜索功能
WebFetch # Web页面抓取
mcp__<server>__<tool> # 特定MCP工具Settings & Configuration
设置与配置
Settings Hierarchy (highest to lowest priority)
设置优先级(从高到低)
- CLI flags — override everything
- Local project: (personal, gitignored)
.claude/settings.local.json - Project: (shared, git-tracked)
.claude/settings.json - User: (global)
~/.claude/settings.json
- CLI参数 — 覆盖所有设置
- 本地项目: (个人使用,git忽略)
.claude/settings.local.json - 项目: (团队共享,git跟踪)
.claude/settings.json - 用户: (全局)
~/.claude/settings.json
Permissions in Settings
设置中的权限配置
json
{
"permissions": {
"allow": ["Bash(npm run lint:*)", "WebSearch", "Read"],
"ask": ["Write(*.ts)", "Bash(git push*)"],
"deny": ["Read(.env)", "Bash(rm -rf *)"]
}
}json
{
"permissions": {
"allow": ["Bash(npm run lint:*)", "WebSearch", "Read"],
"ask": ["Write(*.ts)", "Bash(git push*)"],
"deny": ["Read(.env)", "Bash(rm -rf *)"]
}
}Memory Files (CLAUDE.md) Hierarchy
内存文件(CLAUDE.md)优先级
- Global: — applies to all projects
~/.claude/CLAUDE.md - Project: — project-specific context (git-tracked)
./CLAUDE.md - Local: — personal project overrides (gitignored)
.claude/CLAUDE.local.md
Use the prefix in interactive mode to quickly add to memory: .
## Always use 2-space indentation- 全局: — 适用于所有项目
~/.claude/CLAUDE.md - 项目: — 项目特定上下文(git跟踪)
./CLAUDE.md - 本地: — 个人项目覆盖配置(git忽略)
.claude/CLAUDE.local.md
在交互式模式下使用前缀快速添加到内存:。
## Always use 2-space indentationInteractive Session: Slash Commands
交互式会话:斜杠命令
Session & Context
会话与上下文
| Command | Purpose |
|---|---|
| Show all commands (including custom and MCP commands) |
| Compress context to save tokens; CLAUDE.md survives compaction. E.g., |
| Wipe conversation history for a fresh start |
| Visualize context usage as a colored grid with optimization tips |
| View token usage with per-model and cache-hit breakdowns |
| Switch to or resume a different session |
| Revert to a previous checkpoint in conversation or code |
| Ask a side question without adding to context cost |
| Show version, connectivity, and session info |
| List tracked action items from the conversation |
| End session |
| 命令 | 用途 |
|---|---|
| 显示所有命令(包括自定义和MCP命令) |
| 压缩上下文以节省令牌;CLAUDE.md会保留。例如: |
| 清除对话历史以重新开始 |
| 以彩色网格可视化上下文使用情况,并提供优化建议 |
| 查看令牌使用情况,包含按模型和缓存命中的细分 |
| 切换到或恢复不同的会话 |
| 恢复到对话或代码的先前检查点 |
| 提出附带问题,不增加上下文成本 |
| 显示版本、连接性和会话信息 |
| 列出对话中跟踪的行动项 |
| 结束会话 |
Development & Review
开发与评审
| Command | Purpose |
|---|---|
| Request code review of current changes |
| Perform security analysis of current changes |
| Enter Plan mode with auto-start for task planning |
| Schedule recurring tasks within the session |
| Auto-create worktrees for large parallel changes (5-30 worktrees) |
| 命令 | 用途 |
|---|---|
| 请求对当前更改进行代码评审 |
| 对当前更改执行安全分析 |
| 进入计划模式并自动启动任务规划 |
| 在会话中安排重复任务 |
| 自动创建工作树以进行大规模并行更改(5-30个工作树) |
Configuration & Tools
配置与工具
| Command | Purpose |
|---|---|
| Switch models mid-session (use arrow keys to adjust effort) |
| Set reasoning effort: |
| Create a CLAUDE.md file for project memory |
| Open CLAUDE.md for editing |
| Open interactive settings configuration |
| View/update tool permissions |
| Manage specialized subagents |
| Interactive UI to manage MCP servers |
| Add additional working directories (useful for monorepos) |
| Show plan limits and rate limit status |
| Enable push-to-talk voice mode (20 languages; hold Space to record, release to send) |
| Interactive picker for version release notes |
| 命令 | 用途 |
|---|---|
| 会话中切换模型(使用箭头键调整推理强度) |
| 设置推理强度: |
| 为项目内存创建CLAUDE.md文件 |
| 打开CLAUDE.md进行编辑 |
| 打开交互式设置配置 |
| 查看/更新工具权限 |
| 管理专用子代理 |
| 交互式UI管理MCP服务器 |
| 添加额外的工作目录(适用于单体仓库) |
| 显示计划限制和速率限制状态 |
| 启用一键通语音模式(支持20种语言;按住Space录制,松开发送) |
| 交互式选择版本发布说明 |
Custom Slash Commands
自定义斜杠命令
Create (project-shared) or (personal):
.claude/commands/<name>.md~/.claude/commands/<name>.mdmarkdown
undefined创建(项目共享)或(个人使用):
.claude/commands/<name>.md~/.claude/commands/<name>.mdmarkdown
undefined.claude/commands/deploy.md
.claude/commands/deploy.md
Run the deploy pipeline:
- Run all tests
- Build the Docker image
- Push to registry
- Update the $ARGUMENTS environment (default: staging)
Usage: `/deploy production` — `$ARGUMENTS` is replaced with the user's input.运行部署流水线:
- 运行所有测试
- 构建Docker镜像
- 推送到镜像仓库
- 更新$ARGUMENTS环境(默认:staging)
使用方式:`/deploy production` — `$ARGUMENTS`会替换为用户输入内容。Skills (Natural Language Invocation)
技能(自然语言调用)
Unlike slash commands (manually invoked), skills in are markdown guides that Claude invokes automatically via natural language when the task matches:
.claude/skills/markdown
undefined与手动调用的斜杠命令不同,中的技能是Markdown指南,当任务匹配时,Claude会通过自然语言自动调用:
.claude/skills/markdown
undefined.claude/skills/database-migration.md
.claude/skills/database-migration.md
When asked to create or modify database migrations:
- Use Alembic for migration generation
- Always create a rollback function
- Test migrations against a local database copy
undefined当被要求创建或修改数据库迁移时:
- 使用Alembic生成迁移
- 始终创建回滚函数
- 在本地数据库副本上测试迁移
undefinedInteractive Session: Keyboard Shortcuts
交互式会话:键盘快捷键
General Controls
通用控制
| Key | Action |
|---|---|
| Cancel current input or generation |
| Exit session |
| Reverse search command history |
| Background a running task |
| Paste image into conversation |
| Transcript mode — see Claude's thinking process |
| Open prompt in external editor |
| Rewind conversation or code state / summarize |
| 按键 | 操作 |
|---|---|
| 取消当前输入或生成过程 |
| 退出会话 |
| 反向搜索命令历史 |
| 将运行中的任务后台化 |
| 将图片粘贴到对话中 |
| 转录模式 — 查看Claude的思考过程 |
| 在外部编辑器中打开提示 |
| 恢复对话或代码状态 / 总结内容 |
Mode Toggles
模式切换
| Key | Action |
|---|---|
| Cycle permission modes (Normal → Auto-Accept → Plan) |
| Switch model |
| Toggle thinking mode |
| Toggle Fast Mode |
| 按键 | 操作 |
|---|---|
| 循环切换权限模式(普通→自动接受→计划) |
| 切换模型 |
| 切换思考模式 |
| 切换快速模式 |
Multiline Input
多行输入
| Key | Action |
|---|---|
| Quick newline |
| Newline (alternative) |
| Newline (alternative) |
| 按键 | 操作 |
|---|---|
| 快速换行 |
| 换行(替代方式) |
| 换行(替代方式) |
Input Prefixes
输入前缀
| Prefix | Action |
|---|---|
| Execute bash directly, bypassing AI (e.g., |
| Reference files/directories with autocomplete (e.g., |
| Quick add to CLAUDE.md memory (e.g., |
| Slash commands |
| 前缀 | 操作 |
|---|---|
| 直接执行bash命令,绕过AI(例如 |
| 引用文件/目录并自动补全(例如 |
| 快速添加到CLAUDE.md内存(例如 |
| 斜杠命令 |
Pro Tip: "ultrathink"
专业技巧:"ultrathink"
Use the keyword "ultrathink" in your prompt for maximum reasoning effort on a specific turn. This triggers the deepest thinking mode regardless of the current setting.
/effort在提示中使用关键词"ultrathink",可针对特定轮次启用最大推理强度。无论当前设置如何,这都会触发最深层次的思考模式。
/effortPR Review Pattern
PR评审模式
Quick Review (Print Mode)
快速评审(打印模式)
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)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)Deep Review (Interactive + 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")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") # 信任对话框
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 Review from Number
通过PR编号进行评审
terminal(command="claude -p 'Review this PR thoroughly' --from-pr 42 --max-turns 10", workdir="/path/to/repo", timeout=120)terminal(command="claude -p 'Review this PR thoroughly' --from-pr 42 --max-turns 10", workdir="/path/to/repo", timeout=120)Claude Worktree with tmux
结合tmux的Claude工作树
terminal(command="claude -w feature-x --tmux", workdir="/path/to/repo")Creates an isolated git worktree at AND a tmux session for it. Uses iTerm2 native panes when available; add for traditional tmux.
.claude/worktrees/feature-x--tmux=classicterminal(command="claude -w feature-x --tmux", workdir="/path/to/repo")在创建隔离的git工作树,并为其创建tmux会话。如果可用,使用iTerm2原生面板;添加可使用传统tmux。
.claude/worktrees/feature-x--tmux=classicParallel Claude Instances
并行Claude实例
Run multiple independent Claude tasks simultaneously:
undefined同时运行多个独立的Claude任务:
undefinedTask 1: Fix backend
任务1:修复后端
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")
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
任务2:编写测试
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")
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
任务3:更新文档
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")
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")
undefinedterminal(command="sleep 30 && for s in task1 task2 task3; do echo '=== '$s' ==='; tmux capture-pane -t $s -p -S -5 2>/dev/null; done")
undefinedCLAUDE.md — Project Context File
CLAUDE.md — 项目上下文文件
Claude Code auto-loads from the project root. Use it to persist project context:
CLAUDE.mdmarkdown
undefinedClaude Code会自动加载项目根目录下的,用于持久化项目上下文:
CLAUDE.mdmarkdown
undefinedProject: My API
项目:My API
Architecture
架构
- FastAPI backend with SQLAlchemy ORM
- PostgreSQL database, Redis cache
- pytest for testing with 90% coverage target
- 基于FastAPI后端和SQLAlchemy ORM
- PostgreSQL数据库,Redis缓存
- 使用pytest进行测试,覆盖率目标90%
Key Commands
关键命令
- — run full test suite
make test - — ruff + mypy
make lint - — start dev server on :8000
make dev
- — 运行完整测试套件
make test - — ruff + mypy
make lint - — 在:8000启动开发服务器
make dev
Code Standards
代码规范
- Type hints on all public functions
- Docstrings in Google style
- 2-space indentation for YAML, 4-space for Python
- No wildcard imports
**Be specific.** Instead of "Write good code", use "Use 2-space indentation for JS" or "Name test files with `.test.ts` suffix." Specific instructions save correction cycles.- 所有公共函数添加类型提示
- 使用Google风格的文档字符串
- YAML使用2空格缩进,Python使用4空格缩进
- 禁止通配符导入
**要具体明确**。不要使用“编写优质代码”这类模糊表述,而是使用“JS使用2空格缩进”或“测试文件以`.test.ts`为后缀”这类具体指令。具体说明可减少修正循环。Rules Directory (Modular CLAUDE.md)
规则目录(模块化CLAUDE.md)
For projects with many rules, use the rules directory instead of one massive CLAUDE.md:
- Project rules: — team-shared, git-tracked
.claude/rules/*.md - User rules: — personal, global
~/.claude/rules/*.md
Each file in the rules directory is loaded as additional context. This is cleaner than cramming everything into a single CLAUDE.md.
.md对于有大量规则的项目,使用规则目录替代单个庞大的CLAUDE.md:
- 项目规则: — 团队共享,git跟踪
.claude/rules/*.md - 用户规则: — 个人使用,全局生效
~/.claude/rules/*.md
规则目录中的每个文件都会作为额外上下文加载。这比将所有内容塞进单个CLAUDE.md更清晰。
.mdAuto-Memory
自动内存
Claude automatically stores learned project context in .
~/.claude/projects/<project>/memory/- Limit: 25KB or 200 lines per project
- This is separate from CLAUDE.md — it's Claude's own notes about the project, accumulated across sessions
Claude会自动将学习到的项目上下文存储在中。
~/.claude/projects/<project>/memory/- 限制: 每个项目最多25KB或200行
- 这与CLAUDE.md分离 — 是Claude在多个会话中积累的关于项目的自有笔记
Custom Subagents
自定义子代理
Define specialized agents in (project), (personal), or via CLI flag (session):
.claude/agents/~/.claude/agents/--agents在(项目级)、(个人级)或通过 CLI参数(会话级)定义专用代理:
.claude/agents/~/.claude/agents/--agentsAgent Location Priority
代理位置优先级
- — project-level, team-shared
.claude/agents/ - CLI flag — session-specific, dynamic
--agents - — user-level, personal
~/.claude/agents/
- — 项目级,团队共享
.claude/agents/ - CLI参数 — 会话级,动态定义
--agents - — 用户级,个人使用
~/.claude/agents/
Creating an Agent
创建代理
markdown
undefinedmarkdown
undefined.claude/agents/security-reviewer.md
.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
Invoke via: `@security-reviewer review the auth module`name: security-reviewer description: Security-focused code review model: opus tools: [Read, Bash]
你是一名资深安全工程师。评审代码时需检查:
- 注入漏洞(SQL、XSS、命令注入)
- 认证/授权缺陷
- 代码中的密钥
- 不安全的反序列化
调用方式:`@security-reviewer review the auth module`Dynamic Agents via CLI
通过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 can orchestrate multiple agents: "Use @db-expert to optimize queries, then @security to audit the changes."
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 — Automation on Events
钩子 — 事件触发的自动化
Configure in (project) or (global):
.claude/settings.json~/.claude/settings.jsonjson
{
"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"}]
}]
}
}在(项目级)或(全局)中配置:
.claude/settings.json~/.claude/settings.jsonjson
{
"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"}]
}]
}
}All 8 Hook Types
所有8种钩子类型
| Hook | When it fires | Common use |
|---|---|---|
| Before Claude processes a user prompt | Input validation, logging |
| Before tool execution | Security gates, block dangerous commands (exit 2 = block) |
| After a tool finishes | Auto-format code, run linters |
| On permission requests or input waits | Desktop notifications, alerts |
| When Claude finishes a response | Completion logging, status updates |
| When a subagent completes | Agent orchestration |
| Before context memory is cleared | Backup session transcripts |
| When a session begins | Load dev context (e.g., |
| 钩子 | 触发时机 | 常见用途 |
|---|---|---|
| Claude处理用户提示之前 | 输入验证、日志记录 |
| 工具执行之前 | 安全网关、阻止危险命令(exit 2 = 阻止) |
| 工具执行完成之后 | 自动格式化代码、运行代码检查工具 |
| 权限请求或输入等待时 | 桌面通知、警报 |
| Claude完成响应时 | 完成日志记录、状态更新 |
| 子代理完成时 | 代理编排 |
| 上下文内存清除之前 | 备份会话记录 |
| 会话开始时 | 加载开发上下文(例如 |
Hook Environment Variables
钩子环境变量
| Variable | Content |
|---|---|
| Current project path |
| Files being modified |
| Tool parameters as JSON |
| 变量 | 内容 |
|---|---|
| 当前项目路径 |
| 正在修改的文件 |
| 工具参数(JSON格式) |
Security Hook Examples
安全钩子示例
json
{
"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"}]
}]
}json
{
"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 Integration
MCP集成
Add external tool servers for databases, APIs, and services:
undefined添加用于数据库、API和服务的外部工具服务器:
undefinedGitHub integration
GitHub集成
terminal(command="claude mcp add -s user github -- npx @modelcontextprotocol/server-github", timeout=30)
terminal(command="claude mcp add -s user github -- npx @modelcontextprotocol/server-github", timeout=30)
PostgreSQL queries
PostgreSQL查询
terminal(command="claude mcp add -s local postgres -- npx @anthropic-ai/server-postgres --connection-string postgresql://localhost/mydb", timeout=30)
terminal(command="claude mcp add -s local postgres -- npx @anthropic-ai/server-postgres --connection-string postgresql://localhost/mydb", timeout=30)
Puppeteer for web testing
Puppeteer用于Web测试
terminal(command="claude mcp add puppeteer -- npx @anthropic-ai/server-puppeteer", timeout=30)
undefinedterminal(command="claude mcp add puppeteer -- npx @anthropic-ai/server-puppeteer", timeout=30)
undefinedMCP Scopes
MCP作用域
| Flag | Scope | Storage |
|---|---|---|
| Global (all projects) | |
| This project (personal) | |
| This project (team-shared) | |
| 参数 | 作用域 | 存储位置 |
|---|---|---|
| 全局(所有项目) | |
| 当前项目(个人使用) | |
| 当前项目(团队共享) | |
MCP in Print/CI Mode
打印/CI模式下的MCP
terminal(command="claude --bare -p 'Query database' --mcp-config mcp-servers.json --strict-mcp-config", timeout=60)--strict-mcp-config--mcp-configReference MCP resources in chat:
@github:issue://123terminal(command="claude --bare -p 'Query database' --mcp-config mcp-servers.json --strict-mcp-config", timeout=60)--strict-mcp-config--mcp-config在聊天中引用MCP资源:
@github:issue://123MCP Limits & Tuning
MCP限制与调优
- Tool descriptions: 2KB cap per server for tool descriptions and server instructions
- Result size: Default capped; use annotation to allow up to 500K characters for large outputs
maxResultSizeChars - Output tokens: — cap output from MCP servers to prevent context flooding
export MAX_MCP_OUTPUT_TOKENS=50000 - Transports: (local process),
stdio(remote),http(server-sent events)sse
- 工具描述: 每个服务器的工具描述和服务器说明上限为2KB
- 结果大小: 默认有上限;使用注释可允许最大500K字符的大输出
maxResultSizeChars - 输出令牌: — 限制MCP服务器的输出令牌数,防止上下文溢出
export MAX_MCP_OUTPUT_TOKENS=50000 - 传输方式: (本地进程)、
stdio(远程)、http(服务器发送事件)sse
Monitoring Interactive Sessions
监控交互式会话
Reading the TUI Status
读取TUI状态
undefinedundefinedPeriodic capture to check if Claude is still working or waiting for input
定期捕获以检查Claude是否仍在工作或等待输入
terminal(command="tmux capture-pane -t dev -p -S -10")
Look for these indicators:
- `❯` at bottom = waiting for your input (Claude is done or asking a question)
- `●` lines = Claude is actively using tools (reading, writing, running commands)
- `⏵⏵ bypass permissions on` = status bar showing permissions mode
- `◐ medium · /effort` = current effort level in status bar
- `ctrl+o to expand` = tool output was truncated (can be expanded interactively)terminal(command="tmux capture-pane -t dev -p -S -10")
注意以下指示器:
- 底部的`❯` = 等待你的输入(Claude已完成或正在提问)
- `●`行 = Claude正在主动使用工具(读取、写入、运行命令)
- `⏵⏵ bypass permissions on` = 状态栏显示权限模式
- `◐ medium · /effort` = 状态栏显示当前推理强度
- `ctrl+o to expand` = 工具输出已截断(可交互式展开)Context Window Health
上下文窗口健康状况
Use in interactive mode to see a colored grid of context usage. Key thresholds:
/context- < 70% — Normal operation, full precision
- 70-85% — Precision starts dropping, consider
/compact - > 85% — Hallucination risk spikes significantly, use or
/compact/clear
在交互式模式下使用查看上下文使用情况的彩色网格。关键阈值:
/context- < 70% — 正常运行,精度完整
- 70-85% — 精度开始下降,考虑使用
/compact - > 85% — 幻觉风险显著升高,使用或
/compact/clear
Environment Variables
环境变量
| Variable | Effect |
|---|---|
| API key for authentication (alternative to OAuth) |
| Default effort: |
| Cap thinking tokens (set to |
| Cap output from MCP servers (default varies; set e.g., |
| Enable alt-screen rendering to eliminate terminal flicker |
| Strip credentials from sub-processes for security |
| 变量 | 作用 |
|---|---|
| 认证用API密钥(OAuth的替代方案) |
| 默认推理强度: |
| 限制思考令牌数(设置为 |
| 限制MCP服务器的输出令牌数(默认值可变;例如设置为 |
| 启用替代屏幕渲染以消除终端闪烁 |
| 从子进程中清除凭据以保障安全 |
Cost & Performance Tips
成本与性能技巧
- Use in print mode to prevent runaway loops. Start with 5-10 for most tasks.
--max-turns - Use for cost caps. Note: minimum ~$0.05 for system prompt cache creation.
--max-budget-usd - Use for simple tasks (faster, cheaper).
--effort loworhighfor complex reasoning.max - Use for CI/scripting to skip plugin/hook discovery overhead.
--bare - Use to restrict to only what's needed (e.g.,
--allowedToolsonly for reviews).Read - Use in interactive sessions when context gets large.
/compact - Pipe input instead of having Claude read files when you just need analysis of known content.
- Use for simple tasks (cheaper) and
--model haikufor complex multi-step work.--model opus - Use in print mode to gracefully handle model overload.
--fallback-model haiku - Start new sessions for distinct tasks — sessions last 5 hours; fresh context is more efficient.
- Use in CI to avoid accumulating saved sessions on disk.
--no-session-persistence
- 在打印模式下使用— 防止失控循环。大多数任务起始设置为5-10。
--max-turns - 使用设置成本上限。注意:系统提示缓存创建的最低成本约为$0.05。
--max-budget-usd - 简单任务使用— 更快、更便宜。复杂推理使用
--effort low或high。max - CI/脚本使用— 跳过插件/钩子发现的开销。
--bare - 使用限制仅使用必要工具(例如评审仅使用
--allowedTools)。Read - 交互式会话中使用— 当上下文过大时。
/compact - 管道输入 — 当仅需分析已知内容时,避免让Claude读取文件。
- 简单任务使用(更便宜),复杂多步骤工作使用
--model haiku。--model opus - 打印模式下使用— 优雅处理模型过载。
--fallback-model haiku - 不同任务启动新会话 — 会话持续5小时;新鲜上下文更高效。
- CI中使用— 避免在磁盘上积累保存的会话。
--no-session-persistence
Pitfalls & Gotchas
陷阱与注意事项
- Interactive mode REQUIRES tmux — Claude Code is a full TUI app. Using alone in Hermes terminal works but tmux gives you
pty=truefor monitoring andcapture-panefor input, which is essential for orchestration.send-keys - dialog defaults to "No, exit" — you must send Down then Enter to accept. Print mode (
--dangerously-skip-permissions) skips this entirely.-p - minimum is ~$0.05 — system prompt cache creation alone costs this much. Setting lower will error immediately.
--max-budget-usd - is print-mode only — ignored in interactive sessions.
--max-turns - Claude may use instead of
python— on systems without apython3symlink, Claude's bash commands will fail on first try but it self-corrects.python - Session resumption requires same directory — finds the most recent session for the current working directory.
--continue - needs enough
--json-schema— Claude must read files before producing structured output, which takes multiple turns.--max-turns - Trust dialog only appears once per directory — first-time only, then cached.
- Background tmux sessions persist — always clean up with when done.
tmux kill-session -t <name> - Slash commands (like ) only work in interactive mode — in
/commitmode, describe the task in natural language instead.-p - skips OAuth — requires
--bareenv var or anANTHROPIC_API_KEYin settings.apiKeyHelper - Context degradation is real — AI output quality measurably degrades above 70% context window usage. Monitor with and proactively
/context./compact
- 交互式模式必须使用tmux — Claude Code是完整的TUI应用。在Hermes终端中单独使用可以工作,但tmux提供
pty=true用于监控和capture-pane用于输入,这对编排至关重要。send-keys - 对话框默认选择"No, exit" — 必须先按Down再按Enter才能接受。打印模式(
--dangerously-skip-permissions)会完全跳过此对话框。-p - 最低约为$0.05 — 仅系统提示缓存创建就需要此成本。设置更低会立即报错。
--max-budget-usd - 仅适用于打印模式 — 在交互式会话中会被忽略。
--max-turns - Claude可能使用而非
python— 在没有python3符号链接的系统上,Claude的bash命令首次尝试会失败,但会自我纠正。python - 会话续接需要相同目录 — 会查找当前工作目录中最近的会话。
--continue - 需要足够的
--json-schema— Claude必须先读取文件才能生成结构化输出,这需要多个轮次。--max-turns - 信任对话框每个目录仅出现一次 — 首次出现后会被缓存。
- 后台tmux会话会持续存在 — 完成后务必使用清理。
tmux kill-session -t <name> - 斜杠命令(如)仅在交互式模式下有效 — 在
/commit模式下,用自然语言描述任务即可。-p - 会跳过OAuth — 需要
--bare环境变量或设置中的ANTHROPIC_API_KEY。apiKeyHelper - 上下文退化是真实存在的 — 上下文窗口使用率超过70%时,AI输出质量会明显下降。使用监控并主动使用
/context。/compact
Rules for Hermes Agents
Hermes代理规则
- Prefer print mode () for single tasks — cleaner, no dialog handling, structured output
-p - Use tmux for multi-turn interactive work — the only reliable way to orchestrate the TUI
- Always set — keep Claude focused on the right project directory
workdir - Set in print mode — prevents infinite loops and runaway costs
--max-turns - Monitor tmux sessions — use to check progress
tmux capture-pane -t <session> -p -S -50 - Look for the prompt — indicates Claude is waiting for input (done or asking a question)
❯ - Clean up tmux sessions — kill them when done to avoid resource leaks
- Report results to user — after completion, summarize what Claude did and what changed
- Don't kill slow sessions — Claude may be doing multi-step work; check progress instead
- Use — restrict capabilities to what the task actually needs
--allowedTools
- 单任务首选打印模式() — 更简洁,无需处理对话框,结构化输出
-p - 多轮交互式工作使用tmux — 这是编排TUI的唯一可靠方式
- 始终设置— 让Claude专注于正确的项目目录
workdir - 打印模式下设置— 防止无限循环和失控成本
--max-turns - 监控tmux会话 — 使用检查进度
tmux capture-pane -t <session> -p -S -50 - 注意提示符 — 表示Claude正在等待输入(已完成或正在提问)
❯ - 清理tmux会话 — 完成后关闭会话以避免资源泄漏
- 向用户报告结果 — 完成后总结Claude的操作和更改内容
- 不要终止慢速会话 — Claude可能在执行多步骤工作;先检查进度
- 使用— 将功能限制为任务实际需要的范围
--allowedTools