claude-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude 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
    claude
    once to log in (browser OAuth for Pro/Max, or set
    ANTHROPIC_API_KEY
    )
  • Console auth:
    claude auth login --console
    for API key billing
  • SSO auth:
    claude auth login --sso
    for Enterprise
  • Check status:
    claude auth status
    (JSON) or
    claude auth status --text
    (human-readable)
  • Health check:
    claude doctor
    — checks auto-updater and installation health
  • Version check:
    claude --version
    (requires v2.x+)
  • Update:
    claude update
    or
    claude upgrade
  • 安装:
    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

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)

模式1:打印模式(
-p
) — 非交互式(大多数任务首选)

Print 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编排支持。
undefined

Start 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, exit
Handling:
tmux send-keys -t <session> Enter
— default selection is correct.
❯ 1. Yes, I trust this folder    ← 默认选项(直接按Enter)
  2. No, exit
处理方式:
tmux send-keys -t <session> Enter
— 默认选择正确。

Dialog 2: Bypass Permissions Warning (only with --dangerously-skip-permissions)

对话框2:绕过权限警告(仅使用--dangerously-skip-permissions时出现)

❯ 1. No, exit                    ← DEFAULT (WRONG choice!)
  2. Yes, I accept
Handling: 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> Enter

Robust Dialog Handling Pattern

可靠的对话框处理模式

undefined
undefined

Launch 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子命令

SubcommandPurpose
claude
Start interactive REPL
claude "query"
Start REPL with initial prompt
claude -p "query"
Print mode (non-interactive, exits when done)
cat file | claude -p "query"
Pipe content as stdin context
claude -c
Continue the most recent conversation in this directory
claude -r "id"
Resume a specific session by ID or name
claude auth login
Sign in (add
--console
for API billing,
--sso
for Enterprise)
claude auth status
Check login status (returns JSON;
--text
for human-readable)
claude mcp add <name> -- <cmd>
Add an MCP server
claude mcp list
List configured MCP servers
claude mcp remove <name>
Remove an MCP server
claude agents
List configured agents
claude doctor
Run health checks on installation and auto-updater
claude update
/
claude upgrade
Update Claude Code to latest version
claude remote-control
Start server to control Claude from claude.ai or mobile app
claude install [target]
Install native build (stable, latest, or specific version)
claude setup-token
Set up long-lived auth token (requires subscription)
claude plugin
/
claude plugins
Manage Claude Code plugins
claude auto-mode
Inspect auto mode classifier configuration
子命令用途
claude
启动交互式REPL
claude "query"
使用初始提示启动REPL
claude -p "query"
打印模式(非交互式,完成后退出)
cat file | claude -p "query"
将内容作为标准输入上下文传递
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]
安装原生构建版本(稳定版、最新版或特定版本)
claude setup-token
设置长期认证令牌(需要订阅)
claude plugin
/
claude plugins
管理Claude Code插件
claude auto-mode
检查自动模式分类器配置

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:
session_id
for resumption,
num_turns
for agentic loop count,
total_cost_usd
for spend tracking,
subtype
for success/error detection (
success
,
error_max_turns
,
error_budget
).
terminal(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_id
用于恢复会话,
num_turns
用于统计代理循环次数,
total_cost_usd
用于跟踪花费,
subtype
用于检测成功/错误状态(
success
error_max_turns
error_budget
)。

Streaming JSON Output

流式JSON输出

For real-time token streaming, use
stream-json
with
--verbose
:
terminal(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
system/api_retry
with
attempt
,
max_retries
, and
error
fields (e.g.,
rate_limit
,
billing_error
).
如需实时令牌流,结合
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'
流事件包含
system/api_retry
,带有
attempt
max_retries
error
字段(例如
rate_limit
billing_error
)。

Bidirectional 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
re-emits user messages on stdout for acknowledgment.
如需实时输入和输出流式传输:
claude -p "task" --input-format stream-json --output-format stream-json --replay-user-messages
--replay-user-messages
会在标准输出重新发送用户消息以确认接收。

Piped Input

管道输入

undefined
undefined

Pipe 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)
undefined
terminal(command="git diff HEAD~3 | claude -p 'Summarize these changes' --max-turns 1", timeout=60)
undefined

JSON 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
structured_output
from the JSON result. Claude validates output against the schema before returning.
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。

Session Continuation

会话续接

undefined
undefined

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)
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)
undefined
terminal(command="claude -p 'Try a different approach' --resume <id> --fork-session --max-turns 10", workdir="/project", timeout=120)
undefined

Bare 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)
--bare
skips hooks, plugins, MCP discovery, and CLAUDE.md loading. Fastest startup. Requires
ANTHROPIC_API_KEY
(skips OAuth).
To selectively load context in bare mode:
To loadFlag
System prompt additions
--append-system-prompt "text"
or
--append-system-prompt-file path
Settings
--settings <file-or-json>
MCP servers
--mcp-config <file-or-json>
Custom agents
--agents '<json>'
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>'

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

会话与环境

FlagEffect
-p, --print
Non-interactive one-shot mode (exits when done)
-c, --continue
Resume most recent conversation in current directory
-r, --resume <id>
Resume specific session by ID or name (interactive picker if no ID)
--fork-session
When resuming, create new session ID instead of reusing original
--session-id <uuid>
Use a specific UUID for the conversation
--no-session-persistence
Don't save session to disk (print mode only)
--add-dir <paths...>
Grant Claude access to additional working directories
-w, --worktree [name]
Run in an isolated git worktree at
.claude/worktrees/<name>
--tmux
Create a tmux session for the worktree (requires
--worktree
)
--ide
Auto-connect to a valid IDE on startup
--chrome
/
--no-chrome
Enable/disable Chrome browser integration for web testing
--from-pr [number]
Resume session linked to a specific GitHub PR
--file <specs...>
File resources to download at startup (format:
file_id:relative_path
)
参数作用
-p, --print
非交互式一次性模式(完成后退出)
-c, --continue
恢复当前目录中最近的对话
-r, --resume <id>
通过ID或名称恢复特定会话(无ID时显示交互式选择器)
--fork-session
恢复会话时创建新会话ID,而非复用原ID
--session-id <uuid>
使用特定UUID作为对话ID
--no-session-persistence
不将会话保存到磁盘(仅适用于打印模式)
--add-dir <paths...>
授予Claude访问额外工作目录的权限
-w, --worktree [name]
在隔离的git工作树
.claude/worktrees/<name>
中运行
--tmux
为工作树创建tmux会话(需要
--worktree
--ide
启动时自动连接到有效的IDE
--chrome
/
--no-chrome
启用/禁用Chrome浏览器集成以进行Web测试
--from-pr [number]
恢复与特定GitHub PR关联的会话
--file <specs...>
启动时下载的文件资源(格式:
file_id:relative_path

Model & Performance

模型与性能

FlagEffect
--model <alias>
Model selection:
sonnet
,
opus
,
haiku
, or full name like
claude-sonnet-4-6
--effort <level>
Reasoning depth:
low
,
medium
,
high
,
max
,
auto
--max-turns <n>
Limit agentic loops (print mode only; prevents runaway)
--max-budget-usd <n>
Cap API spend in dollars (print mode only)
--fallback-model <model>
Auto-fallback when default model is overloaded (print mode only)
--betas <betas...>
Beta headers to include in API requests (API key users only)
参数作用
--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密钥用户可用)

Permission & Safety

权限与安全

FlagEffect
--dangerously-skip-permissions
Auto-approve ALL tool use (file writes, bash, network, etc.)
--allow-dangerously-skip-permissions
Enable bypass as an option without enabling it by default
--permission-mode <mode>
default
,
acceptEdits
,
plan
,
auto
,
dontAsk
,
bypassPermissions
--allowedTools <tools...>
Whitelist specific tools (comma or space-separated)
--disallowedTools <tools...>
Blacklist specific tools
--tools <tools...>
Override built-in tool set (
""
= none,
"default"
= all, or tool names)
参数作用
--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 & Input Format

输出与输入格式

FlagEffect
--output-format <fmt>
text
(default),
json
(single result object),
stream-json
(newline-delimited)
--input-format <fmt>
text
(default) or
stream-json
(real-time streaming input)
--json-schema <schema>
Force structured JSON output matching a schema
--verbose
Full turn-by-turn output
--include-partial-messages
Include partial message chunks as they arrive (stream-json + print)
--replay-user-messages
Re-emit user messages on stdout (stream-json bidirectional)
参数作用
--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
在标准输出重新发送用户消息(双向stream-json)

System Prompt & Context

系统提示与上下文

FlagEffect
--append-system-prompt <text>
Add to the default system prompt (preserves built-in capabilities)
--append-system-prompt-file <path>
Add file contents to the default system prompt
--system-prompt <text>
Replace the entire system prompt (use --append instead usually)
--system-prompt-file <path>
Replace the system prompt with file contents
--bare
Skip hooks, plugins, MCP discovery, CLAUDE.md, OAuth (fastest startup)
--agents '<json>'
Define custom subagents dynamically as JSON
--mcp-config <path>
Load MCP servers from JSON file (repeatable)
--strict-mcp-config
Only use MCP servers from
--mcp-config
, ignoring all other MCP configs
--settings <file-or-json>
Load additional settings from a JSON file or inline JSON
--setting-sources <sources>
Comma-separated sources to load:
user
,
project
,
local
--plugin-dir <paths...>
Load plugins from directories for this session only
--disable-slash-commands
Disable all skills/slash commands
参数作用
--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
禁用所有技能/斜杠命令

Debugging

调试

FlagEffect
-d, --debug [filter]
Enable debug logging with optional category filter (e.g.,
"api,hooks"
,
"!1p,!file"
)
--debug-file <path>
Write debug logs to file (implicitly enables debug mode)
参数作用
-d, --debug [filter]
启用调试日志,可选择类别过滤(例如
"api,hooks"
"!1p,!file"
--debug-file <path>
将调试日志写入文件(隐式启用调试模式)

Agent Teams

代理团队

FlagEffect
--teammate-mode <mode>
How agent teams display:
auto
,
in-process
, or
tmux
--brief
Enable
SendUserMessage
tool for agent-to-user communication
参数作用
--teammate-mode <mode>
代理团队显示方式:
auto
in-process
tmux
--brief
启用
SendUserMessage
工具以实现代理与用户的通信

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 tool
Read                    # 所有文件读取操作
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)

设置优先级(从高到低)

  1. CLI flags — override everything
  2. Local project:
    .claude/settings.local.json
    (personal, gitignored)
  3. Project:
    .claude/settings.json
    (shared, git-tracked)
  4. User:
    ~/.claude/settings.json
    (global)
  1. CLI参数 — 覆盖所有设置
  2. 本地项目:
    .claude/settings.local.json
    (个人使用,git忽略)
  3. 项目:
    .claude/settings.json
    (团队共享,git跟踪)
  4. 用户:
    ~/.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)优先级

  1. Global:
    ~/.claude/CLAUDE.md
    — applies to all projects
  2. Project:
    ./CLAUDE.md
    — project-specific context (git-tracked)
  3. Local:
    .claude/CLAUDE.local.md
    — personal project overrides (gitignored)
Use the
#
prefix in interactive mode to quickly add to memory:
# Always use 2-space indentation
.
  1. 全局:
    ~/.claude/CLAUDE.md
    — 适用于所有项目
  2. 项目:
    ./CLAUDE.md
    — 项目特定上下文(git跟踪)
  3. 本地:
    .claude/CLAUDE.local.md
    — 个人项目覆盖配置(git忽略)
在交互式模式下使用
#
前缀快速添加到内存:
# Always use 2-space indentation

Interactive Session: Slash Commands

交互式会话:斜杠命令

Session & Context

会话与上下文

CommandPurpose
/help
Show all commands (including custom and MCP commands)
/compact [focus]
Compress context to save tokens; CLAUDE.md survives compaction. E.g.,
/compact focus on auth logic
/clear
Wipe conversation history for a fresh start
/context
Visualize context usage as a colored grid with optimization tips
/cost
View token usage with per-model and cache-hit breakdowns
/resume
Switch to or resume a different session
/rewind
Revert to a previous checkpoint in conversation or code
/btw <question>
Ask a side question without adding to context cost
/status
Show version, connectivity, and session info
/todos
List tracked action items from the conversation
/exit
or
Ctrl+D
End session
命令用途
/help
显示所有命令(包括自定义和MCP命令)
/compact [focus]
压缩上下文以节省令牌;CLAUDE.md会保留。例如:
/compact focus on auth logic
/clear
清除对话历史以重新开始
/context
以彩色网格可视化上下文使用情况,并提供优化建议
/cost
查看令牌使用情况,包含按模型和缓存命中的细分
/resume
切换到或恢复不同的会话
/rewind
恢复到对话或代码的先前检查点
/btw <question>
提出附带问题,不增加上下文成本
/status
显示版本、连接性和会话信息
/todos
列出对话中跟踪的行动项
/exit
Ctrl+D
结束会话

Development & Review

开发与评审

CommandPurpose
/review
Request code review of current changes
/security-review
Perform security analysis of current changes
/plan [description]
Enter Plan mode with auto-start for task planning
/loop [interval]
Schedule recurring tasks within the session
/batch
Auto-create worktrees for large parallel changes (5-30 worktrees)
命令用途
/review
请求对当前更改进行代码评审
/security-review
对当前更改执行安全分析
/plan [description]
进入计划模式并自动启动任务规划
/loop [interval]
在会话中安排重复任务
/batch
自动创建工作树以进行大规模并行更改(5-30个工作树)

Configuration & Tools

配置与工具

CommandPurpose
/model [model]
Switch models mid-session (use arrow keys to adjust effort)
/effort [level]
Set reasoning effort:
low
,
medium
,
high
,
max
, or
auto
/init
Create a CLAUDE.md file for project memory
/memory
Open CLAUDE.md for editing
/config
Open interactive settings configuration
/permissions
View/update tool permissions
/agents
Manage specialized subagents
/mcp
Interactive UI to manage MCP servers
/add-dir
Add additional working directories (useful for monorepos)
/usage
Show plan limits and rate limit status
/voice
Enable push-to-talk voice mode (20 languages; hold Space to record, release to send)
/release-notes
Interactive picker for version release notes
命令用途
/model [model]
会话中切换模型(使用箭头键调整推理强度)
/effort [level]
设置推理强度:
low
medium
high
max
auto
/init
为项目内存创建CLAUDE.md文件
/memory
打开CLAUDE.md进行编辑
/config
打开交互式设置配置
/permissions
查看/更新工具权限
/agents
管理专用子代理
/mcp
交互式UI管理MCP服务器
/add-dir
添加额外的工作目录(适用于单体仓库)
/usage
显示计划限制和速率限制状态
/voice
启用一键通语音模式(支持20种语言;按住Space录制,松开发送)
/release-notes
交互式选择版本发布说明

Custom Slash Commands

自定义斜杠命令

Create
.claude/commands/<name>.md
(project-shared) or
~/.claude/commands/<name>.md
(personal):
markdown
undefined
创建
.claude/commands/<name>.md
(项目共享)或
~/.claude/commands/<name>.md
(个人使用):
markdown
undefined

.claude/commands/deploy.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)

Usage: `/deploy production` — `$ARGUMENTS` is replaced with the user's input.
运行部署流水线:
  1. 运行所有测试
  2. 构建Docker镜像
  3. 推送到镜像仓库
  4. 更新$ARGUMENTS环境(默认:staging)

使用方式:`/deploy production` — `$ARGUMENTS`会替换为用户输入内容。

Skills (Natural Language Invocation)

技能(自然语言调用)

Unlike slash commands (manually invoked), skills in
.claude/skills/
are markdown guides that Claude invokes automatically via natural language when the task matches:
markdown
undefined
与手动调用的斜杠命令不同,
.claude/skills/
中的技能是Markdown指南,当任务匹配时,Claude会通过自然语言自动调用:
markdown
undefined

.claude/skills/database-migration.md

.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
undefined
当被要求创建或修改数据库迁移时:
  1. 使用Alembic生成迁移
  2. 始终创建回滚函数
  3. 在本地数据库副本上测试迁移
undefined

Interactive Session: Keyboard Shortcuts

交互式会话:键盘快捷键

General Controls

通用控制

KeyAction
Ctrl+C
Cancel current input or generation
Ctrl+D
Exit session
Ctrl+R
Reverse search command history
Ctrl+B
Background a running task
Ctrl+V
Paste image into conversation
Ctrl+O
Transcript mode — see Claude's thinking process
Ctrl+G
or
Ctrl+X Ctrl+E
Open prompt in external editor
Esc Esc
Rewind conversation or code state / summarize
按键操作
Ctrl+C
取消当前输入或生成过程
Ctrl+D
退出会话
Ctrl+R
反向搜索命令历史
Ctrl+B
将运行中的任务后台化
Ctrl+V
将图片粘贴到对话中
Ctrl+O
转录模式 — 查看Claude的思考过程
Ctrl+G
Ctrl+X Ctrl+E
在外部编辑器中打开提示
Esc Esc
恢复对话或代码状态 / 总结内容

Mode Toggles

模式切换

KeyAction
Shift+Tab
Cycle permission modes (Normal → Auto-Accept → Plan)
Alt+P
Switch model
Alt+T
Toggle thinking mode
Alt+O
Toggle Fast Mode
按键操作
Shift+Tab
循环切换权限模式(普通→自动接受→计划)
Alt+P
切换模型
Alt+T
切换思考模式
Alt+O
切换快速模式

Multiline Input

多行输入

KeyAction
\
+
Enter
Quick newline
Shift+Enter
Newline (alternative)
Ctrl+J
Newline (alternative)
按键操作
\
+
Enter
快速换行
Shift+Enter
换行(替代方式)
Ctrl+J
换行(替代方式)

Input Prefixes

输入前缀

PrefixAction
!
Execute bash directly, bypassing AI (e.g.,
!npm test
). Use
!
alone to toggle shell mode.
@
Reference files/directories with autocomplete (e.g.,
@./src/api/
)
#
Quick add to CLAUDE.md memory (e.g.,
# Use 2-space indentation
)
/
Slash commands
前缀操作
!
直接执行bash命令,绕过AI(例如
!npm test
)。单独使用
!
可切换shell模式。
@
引用文件/目录并自动补全(例如
@./src/api/
#
快速添加到CLAUDE.md内存(例如
# Use 2-space indentation
/
斜杠命令

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
/effort
setting.
在提示中使用关键词"ultrathink",可针对特定轮次启用最大推理强度。无论当前
/effort
设置如何,这都会触发最深层次的思考模式。

PR 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
.claude/worktrees/feature-x
AND a tmux session for it. Uses iTerm2 native panes when available; add
--tmux=classic
for traditional tmux.
terminal(command="claude -w feature-x --tmux", workdir="/path/to/repo")
.claude/worktrees/feature-x
创建隔离的git工作树,并为其创建tmux会话。如果可用,使用iTerm2原生面板;添加
--tmux=classic
可使用传统tmux。

Parallel Claude Instances

并行Claude实例

Run multiple independent Claude tasks simultaneously:
undefined
同时运行多个独立的Claude任务:
undefined

Task 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")
undefined
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")
undefined

CLAUDE.md — Project Context File

CLAUDE.md — 项目上下文文件

Claude Code auto-loads
CLAUDE.md
from the project root. Use it to persist project context:
markdown
undefined
Claude Code会自动加载项目根目录下的
CLAUDE.md
,用于持久化项目上下文:
markdown
undefined

Project: 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

关键命令

  • make test
    — run full test suite
  • make lint
    — ruff + mypy
  • make dev
    — start dev server on :8000
  • make test
    — 运行完整测试套件
  • make lint
    — ruff + mypy
  • make dev
    — 在: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

**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:
    .claude/rules/*.md
    — team-shared, git-tracked
  • User rules:
    ~/.claude/rules/*.md
    — personal, global
Each
.md
file in the rules directory is loaded as additional context. This is cleaner than cramming everything into a single CLAUDE.md.
对于有大量规则的项目,使用规则目录替代单个庞大的CLAUDE.md:
  • 项目规则:
    .claude/rules/*.md
    — 团队共享,git跟踪
  • 用户规则:
    ~/.claude/rules/*.md
    — 个人使用,全局生效
规则目录中的每个
.md
文件都会作为额外上下文加载。这比将所有内容塞进单个CLAUDE.md更清晰。

Auto-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
.claude/agents/
(project),
~/.claude/agents/
(personal), or via
--agents
CLI flag (session):
.claude/agents/
(项目级)、
~/.claude/agents/
(个人级)或通过
--agents
CLI参数(会话级)定义专用代理:

Agent Location Priority

代理位置优先级

  1. .claude/agents/
    — project-level, team-shared
  2. --agents
    CLI flag — session-specific, dynamic
  3. ~/.claude/agents/
    — user-level, personal
  1. .claude/agents/
    — 项目级,团队共享
  2. --agents
    CLI参数 — 会话级,动态定义
  3. ~/.claude/agents/
    — 用户级,个人使用

Creating an Agent

创建代理

markdown
undefined
markdown
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
.claude/settings.json
(project) or
~/.claude/settings.json
(global):
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"}]
    }]
  }
}
.claude/settings.json
(项目级)或
~/.claude/settings.json
(全局)中配置:
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"}]
    }]
  }
}

All 8 Hook Types

所有8种钩子类型

HookWhen it firesCommon use
UserPromptSubmit
Before Claude processes a user promptInput validation, logging
PreToolUse
Before tool executionSecurity gates, block dangerous commands (exit 2 = block)
PostToolUse
After a tool finishesAuto-format code, run linters
Notification
On permission requests or input waitsDesktop notifications, alerts
Stop
When Claude finishes a responseCompletion logging, status updates
SubagentStop
When a subagent completesAgent orchestration
PreCompact
Before context memory is clearedBackup session transcripts
SessionStart
When a session beginsLoad dev context (e.g.,
git status
)
钩子触发时机常见用途
UserPromptSubmit
Claude处理用户提示之前输入验证、日志记录
PreToolUse
工具执行之前安全网关、阻止危险命令(exit 2 = 阻止)
PostToolUse
工具执行完成之后自动格式化代码、运行代码检查工具
Notification
权限请求或输入等待时桌面通知、警报
Stop
Claude完成响应时完成日志记录、状态更新
SubagentStop
子代理完成时代理编排
PreCompact
上下文内存清除之前备份会话记录
SessionStart
会话开始时加载开发上下文(例如
git status

Hook Environment Variables

钩子环境变量

VariableContent
CLAUDE_PROJECT_DIR
Current project path
CLAUDE_FILE_PATHS
Files being modified
CLAUDE_TOOL_INPUT
Tool parameters as JSON
变量内容
CLAUDE_PROJECT_DIR
当前项目路径
CLAUDE_FILE_PATHS
正在修改的文件
CLAUDE_TOOL_INPUT
工具参数(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和服务的外部工具服务器:
undefined

GitHub 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)
undefined
terminal(command="claude mcp add puppeteer -- npx @anthropic-ai/server-puppeteer", timeout=30)
undefined

MCP Scopes

MCP作用域

FlagScopeStorage
-s user
Global (all projects)
~/.claude.json
-s local
This project (personal)
.claude/settings.local.json
(gitignored)
-s project
This project (team-shared)
.claude/settings.json
(git-tracked)
参数作用域存储位置
-s user
全局(所有项目)
~/.claude.json
-s local
当前项目(个人使用)
.claude/settings.local.json
(git忽略)
-s project
当前项目(团队共享)
.claude/settings.json
(git跟踪)

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
ignores all MCP servers except those from
--mcp-config
.
Reference MCP resources in chat:
@github:issue://123
terminal(command="claude --bare -p 'Query database' --mcp-config mcp-servers.json --strict-mcp-config", timeout=60)
--strict-mcp-config
会忽略除
--mcp-config
之外的所有MCP服务器。
在聊天中引用MCP资源:
@github:issue://123

MCP Limits & Tuning

MCP限制与调优

  • Tool descriptions: 2KB cap per server for tool descriptions and server instructions
  • Result size: Default capped; use
    maxResultSizeChars
    annotation to allow up to 500K characters for large outputs
  • Output tokens:
    export MAX_MCP_OUTPUT_TOKENS=50000
    — cap output from MCP servers to prevent context flooding
  • Transports:
    stdio
    (local process),
    http
    (remote),
    sse
    (server-sent events)
  • 工具描述: 每个服务器的工具描述和服务器说明上限为2KB
  • 结果大小: 默认有上限;使用
    maxResultSizeChars
    注释可允许最大500K字符的大输出
  • 输出令牌:
    export MAX_MCP_OUTPUT_TOKENS=50000
    — 限制MCP服务器的输出令牌数,防止上下文溢出
  • 传输方式:
    stdio
    (本地进程)、
    http
    (远程)、
    sse
    (服务器发送事件)

Monitoring Interactive Sessions

监控交互式会话

Reading the TUI Status

读取TUI状态

undefined
undefined

Periodic 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
/context
in interactive mode to see a colored grid of context usage. Key thresholds:
  • < 70% — Normal operation, full precision
  • 70-85% — Precision starts dropping, consider
    /compact
  • > 85% — Hallucination risk spikes significantly, use
    /compact
    or
    /clear
在交互式模式下使用
/context
查看上下文使用情况的彩色网格。关键阈值:
  • < 70% — 正常运行,精度完整
  • 70-85% — 精度开始下降,考虑使用
    /compact
  • > 85% — 幻觉风险显著升高,使用
    /compact
    /clear

Environment Variables

环境变量

VariableEffect
ANTHROPIC_API_KEY
API key for authentication (alternative to OAuth)
CLAUDE_CODE_EFFORT_LEVEL
Default effort:
low
,
medium
,
high
,
max
, or
auto
MAX_THINKING_TOKENS
Cap thinking tokens (set to
0
to disable thinking entirely)
MAX_MCP_OUTPUT_TOKENS
Cap output from MCP servers (default varies; set e.g.,
50000
)
CLAUDE_CODE_NO_FLICKER=1
Enable alt-screen rendering to eliminate terminal flicker
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB
Strip credentials from sub-processes for security
变量作用
ANTHROPIC_API_KEY
认证用API密钥(OAuth的替代方案)
CLAUDE_CODE_EFFORT_LEVEL
默认推理强度:
low
medium
high
max
auto
MAX_THINKING_TOKENS
限制思考令牌数(设置为
0
可完全禁用思考)
MAX_MCP_OUTPUT_TOKENS
限制MCP服务器的输出令牌数(默认值可变;例如设置为
50000
CLAUDE_CODE_NO_FLICKER=1
启用替代屏幕渲染以消除终端闪烁
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB
从子进程中清除凭据以保障安全

Cost & Performance Tips

成本与性能技巧

  1. Use
    --max-turns
    in print mode to prevent runaway loops. Start with 5-10 for most tasks.
  2. Use
    --max-budget-usd
    for cost caps. Note: minimum ~$0.05 for system prompt cache creation.
  3. Use
    --effort low
    for simple tasks (faster, cheaper).
    high
    or
    max
    for complex reasoning.
  4. Use
    --bare
    for CI/scripting to skip plugin/hook discovery overhead.
  5. Use
    --allowedTools
    to restrict to only what's needed (e.g.,
    Read
    only for reviews).
  6. Use
    /compact
    in interactive sessions when context gets large.
  7. Pipe input instead of having Claude read files when you just need analysis of known content.
  8. Use
    --model haiku
    for simple tasks (cheaper) and
    --model opus
    for complex multi-step work.
  9. Use
    --fallback-model haiku
    in print mode to gracefully handle model overload.
  10. Start new sessions for distinct tasks — sessions last 5 hours; fresh context is more efficient.
  11. Use
    --no-session-persistence
    in CI to avoid accumulating saved sessions on disk.
  1. 在打印模式下使用
    --max-turns
    — 防止失控循环。大多数任务起始设置为5-10。
  2. 使用
    --max-budget-usd
    设置成本上限。注意:系统提示缓存创建的最低成本约为$0.05。
  3. 简单任务使用
    --effort low
    — 更快、更便宜。复杂推理使用
    high
    max
  4. CI/脚本使用
    --bare
    — 跳过插件/钩子发现的开销。
  5. 使用
    --allowedTools
    限制仅使用必要工具(例如评审仅使用
    Read
    )。
  6. 交互式会话中使用
    /compact
    — 当上下文过大时。
  7. 管道输入 — 当仅需分析已知内容时,避免让Claude读取文件。
  8. 简单任务使用
    --model haiku
    (更便宜),复杂多步骤工作使用
    --model opus
  9. 打印模式下使用
    --fallback-model haiku
    — 优雅处理模型过载。
  10. 不同任务启动新会话 — 会话持续5小时;新鲜上下文更高效。
  11. CI中使用
    --no-session-persistence
    — 避免在磁盘上积累保存的会话。

Pitfalls & Gotchas

陷阱与注意事项

  1. Interactive mode REQUIRES tmux — Claude Code is a full TUI app. Using
    pty=true
    alone in Hermes terminal works but tmux gives you
    capture-pane
    for monitoring and
    send-keys
    for input, which is essential for orchestration.
  2. --dangerously-skip-permissions
    dialog defaults to "No, exit"
    — you must send Down then Enter to accept. Print mode (
    -p
    ) skips this entirely.
  3. --max-budget-usd
    minimum is ~$0.05
    — system prompt cache creation alone costs this much. Setting lower will error immediately.
  4. --max-turns
    is print-mode only
    — ignored in interactive sessions.
  5. Claude may use
    python
    instead of
    python3
    — on systems without a
    python
    symlink, Claude's bash commands will fail on first try but it self-corrects.
  6. Session resumption requires same directory
    --continue
    finds the most recent session for the current working directory.
  7. --json-schema
    needs enough
    --max-turns
    — Claude must read files before producing structured output, which takes multiple turns.
  8. Trust dialog only appears once per directory — first-time only, then cached.
  9. Background tmux sessions persist — always clean up with
    tmux kill-session -t <name>
    when done.
  10. Slash commands (like
    /commit
    ) only work in interactive mode
    — in
    -p
    mode, describe the task in natural language instead.
  11. --bare
    skips OAuth
    — requires
    ANTHROPIC_API_KEY
    env var or an
    apiKeyHelper
    in settings.
  12. Context degradation is real — AI output quality measurably degrades above 70% context window usage. Monitor with
    /context
    and proactively
    /compact
    .
  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

Rules for Hermes Agents

Hermes代理规则

  1. Prefer print mode (
    -p
    ) for single tasks
    — cleaner, no dialog handling, structured output
  2. Use tmux for multi-turn interactive work — the only reliable way to orchestrate the TUI
  3. Always set
    workdir
    — keep Claude focused on the right project directory
  4. Set
    --max-turns
    in print mode
    — prevents infinite loops and runaway costs
  5. Monitor tmux sessions — use
    tmux capture-pane -t <session> -p -S -50
    to check progress
  6. Look for the
    prompt
    — indicates Claude is waiting for input (done or asking a question)
  7. Clean up tmux sessions — kill them when done to avoid resource leaks
  8. Report results to user — after completion, summarize what Claude did and what changed
  9. Don't kill slow sessions — Claude may be doing multi-step work; check progress instead
  10. Use
    --allowedTools
    — restrict capabilities to what the task actually needs
  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
    — 将功能限制为任务实际需要的范围