C
发布于 2026/09/03 · 阅读 0

我阅读了Claude Code的源代码:文档中没有告诉你的所有可配置项

  • #Claude Code
  • #AI 工具
  • #配置技巧
  • #Hacker News
  • #buildingbetter.tech
我阅读了Claude Code的源代码:文档中没有告诉你的所有可配置项

我阅读了Claude Code的源代码:文档中没有告诉你的所有可配置项

Claude Code 的自动模式权限系统内部被称为“YOLO Classifier”,这是 yoloClassifier.ts 中实际的变量名。你可以用简单的英文描述你的环境(例如“这是一个 staging 服务器,可以执行破坏性操作”),分类器会根据这些描述决定哪些操作可以自动批准。这些都不在官方文档中。

这只是 Claude Code 源代码中数十个未文档化功能之一。源代码就在你的 node_modules 中,是一个公开分发的 npm 包。官方文档涵盖了基础知识,但源代码揭示了那些能极大扩展你构建能力的字段、响应格式和设置。本文所述的所有功能当前均可用,每个示例都设计为可直接复制到你的项目中。

版本说明: 这些发现基于 @anthropic-ai/claude-code@2.1.87。未文档化的功能可能在不同版本间变化,因此请将其视为当前可用功能的快照。名称中带有“EXPERIMENTAL”的字段已被 Anthropic 工程师明确标记为不稳定,我会单独指出。

开始之前

快速参考各配置的存放位置:

  • 设置:~/.claude/settings.json(个人)或 .claude/settings.json(项目,通过 git 共享)
  • Skills(技能):~/.claude/skills/<name>/SKILL.md(个人)或 .claude/skills/<name>/SKILL.md(项目)
  • Agents(代理):~/.claude/agents/<name>.md(个人)或 .claude/agents/<name>.md(项目)
  • Hook 脚本:建议使用 ~/.claude/hooks/ 目录。别忘了 chmod +x 你的脚本。

项目级别的 .claude/ 文件可以提交到 git 并与团队共享,个人文件在 ~/.claude/ 中则只属于你自己。

你的 Hook 可以回传数据,但没人告诉你如何做

这是文档中最大的空白。文档只告诉你 Hook 通过 stdin 接收 JSON,以及退出码 2 会阻止操作。但它们没有告诉你 Hook 可以通过 stdout 返回 JSON,其中包含特定于事件的字段,可以实时修改 Claude Code 的行为。源代码揭示了每个事件类型接受的字段。

PreToolUse Hook 可以返回:

  • updatedInput - 在工具执行前重写其输入。你可以在命令执行中途修改它。
  • permissionDecision - 强制“允许”或“拒绝”,无需用户提示。
  • permissionDecisionReason - 解释决策(在 UI 中显示)。
  • additionalContext - 向对话上下文注入文本。

SessionStart Hook 可以返回:

  • watchPaths - 设置自动文件监视,触发 FileChanged 事件。
  • initialUserMessage - 在会话的第一条用户消息前添加内容。
  • additionalContext - 注入在整个会话中持续存在的上下文。

PostToolUse Hook 可以返回:

  • updatedMCPToolOutput - 修改 Claude 从 MCP 工具响应中看到的内容。
  • additionalContext - 在工具运行后注入上下文。

PermissionRequest Hook 可以返回:

  • decision - 通过 updatedInputupdatedPermissions 以编程方式允许或拒绝。

这些都是强大的功能。以下是一个 PreToolUse Hook 示例,它在 Claude 执行 git push 之前自动添加 --dry-run 参数。

在你的 settings.json 中:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/dry-run-pushes.sh"
      }]
    }]
  }
}

脚本 ~/.claude/hooks/dry-run-pushes.sh

#!/bin/bash
INPUT=$(jq -r '.tool_input.command' < /dev/stdin)
if echo "$INPUT" | grep -q 'git push'; then
  jq -n --arg cmd "$INPUT --dry-run" '{"updatedInput": {"command": $cmd}}'
fi

Claude 以为自己正在运行 git push origin main,但你的 Hook 悄悄地将其重写为 git push origin main --dry-runupdatedInput 字段在任何文档中都没有出现。

以下是一个 SessionStart Hook 示例,它监视你的配置文件并在每个会话中注入 git 上下文。

settings.json

{
  "hooks": {
    "SessionStart": [{
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/session-context.sh",
        "statusMessage": "Loading project context..."
      }]
    }]
  }
}

脚本 ~/.claude/hooks/session-context.sh

#!/bin/bash
BRANCH=$(git branch --show-current 2>/dev/null)
CHANGES=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
jq -n \
  --arg branch "$BRANCH" \
  --arg changes "$CHANGES" \
  '{
    "watchPaths": ["package.json", ".env", "tsconfig.json"],
    "additionalContext": "Current branch: \($branch). Uncommitted changes: \($changes) files."
  }'

现在 Claude Code 会自动监视你的 package.json.envtsconfig 文件的变化,并且在你输入任何内容之前,它就知道你当前所在的分支以及有多少未提交的文件。

还有一个自动批准只读 bash 命令而无需提示的示例:

settings.json

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/auto-approve-readonly.sh"
      }]
    }]
  }
}

脚本 ~/.claude/hooks/auto-approve-readonly.sh

#!/bin/bash
CMD=$(jq -r '.tool_input.command' < /dev/stdin)
if echo "$CMD" | grep -qE '^(ls|cat|echo|pwd|whoami|date|git status|git log|git diff)'; then
  echo '{"permissionDecision": "allow", "permissionDecisionReason": "Safe read-only command"}'
fi

你基本上是在用 shell 脚本构建自己的权限分类器。permissionDecision 字段在任何文档中都没有出现。

文档遗漏的三个 Hook 字段

文档中记录的 Hook 字段有 typecommandmatchertimeoutifstatusMessage。但源代码解析器还接受另外三个字段,它们从根本上改变了 Hook 的行为。

once: true:Hook 只触发一次,然后自动移除。非常适合首次会话的设置:

{
  "hooks": {
    "SessionStart": [{
      "hooks": [{
        "type": "command",
        "command": "[ -f .env ] || cp .env.example .env && echo 'Created .env from template'",
        "once": true,
        "statusMessage": "First-time setup..."
      }]
    }]
  }
}

足够简单,可以直接内联。它检查 .env 是否存在,如果不存在则复制模板,并且永远不会再次运行。

async: true:Hook 在后台运行,不会阻塞 Claude。即发即忘:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "jq '{timestamp: now, command: .tool_input.command, session: .session_id}' < /dev/stdin >> ~/.claude/audit.jsonl",
        "async": true
      }]
    }]
  }
}

这会将每个 bash 命令记录到审计文件中,而不会给你的会话增加任何延迟。

asyncRewake: true:这是一个巧妙的设计。它像 async 一样在后台运行,因此在正常路径上不会阻塞。但如果它以退出码 2 结束,则会唤醒模型并阻止操作。一切正常时不阻塞,出现问题时才阻塞:

settings.json

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{
        "type": "command",
        "command": "~/.claude/hooks/scan-secrets.sh",
        "asyncRewake": true,
        "statusMessage": "Scanning for secrets..."
      }]
    }]
  }
}

脚本 ~/.claude/hooks/scan-secrets.sh

#!/bin/bash
FILE=$(jq -r '.tool_input.file_path // .tool_response.filePath' < /dev/stdin)
if grep -qE '(password|secret|api_key)\s*=' "$FILE" 2>/dev/null; then
  exit 2 # Block: secrets detected
fi
exit 0 # Clean: carry on

这会扫描 Claude 写入的每个文件,检查是否存在硬编码的密钥。如果找到,它会阻止并告知 Claude。如果没有,你甚至不会注意到它运行过。

文档未展示的 Skill Frontmatter 字段

官方文档只提到了 namedescriptionallowed-toolsargument-hintwhen_to_usecontext。但源代码中的 frontmatter 解析器还接受另外六个字段。

model:允许你覆盖运行该技能的模型。对于廉价快速的任务使用 haiku,对于复杂分析使用 opus

---
name: quick-lint
description: Fast lint check using the cheapest model
model: haiku
effort: low
allowed-tools: Bash, Read
argument-hint: "[file]"
---
Run the project linter on: $ARGUMENTS
Detect the linter from config (eslint, ruff, clippy) and run it.
Report only errors, not warnings.

这会在 Haiku 上以低 effort 运行,速度快且成本低。对于深度的架构审查,你可能想使用 model: opuseffort: max

effort:控制模型思考的深度。可选值:lowmediumhighmax。这映射到内部控制每次响应推理深度的 effort 系统。

hooks:定义仅在技能激活时生效的 Hook。当技能触发时注册,完成时注销:

---
name: strict-typescript
description: Write TypeScript with type checking on every save
allowed-tools: Bash, Read, Write, Edit, Grep, Glob
hooks:
  PostToolUse:
    - matcher: "Write|Edit"
      hooks:
        - type: command
          command: "~/.claude/hooks/typecheck-on-save.sh"
          statusMessage: "Type checking..."
        - type: command
          command: "~/.claude/hooks/lint-on-save.sh"
          async: true
---
Write TypeScript with strict enforcement.
Every file you touch gets type-checked and linted automatically.
$ARGUMENTS

脚本 ~/.claude/hooks/typecheck-on-save.sh

#!/bin/bash
FILE=$(jq -r '.tool_input.file_path // .tool_response.filePath' < /dev/stdin)
[[ "$FILE" == *.ts ]] && npx tsc --noEmit 2>&1 || true

脚本 ~/.claude/hooks/lint-on-save.sh

#!/bin/bash
FILE=$(jq -r '.tool_input.file_path // .tool_response.filePath' < /dev/stdin)
[[ "$FILE" == *.ts ]] && npx eslint --fix "$FILE" 2>&1 || true

当该技能运行时,Claude 编写的每个 TypeScript 文件都会同步进行类型检查,并在后台进行 lint。当技能完成时,这些 Hook 会消失。作用域非常清晰。

agent:将技能委托给一个自定义代理:

---
name: deep-review
description: Thorough security review delegated to the review agent
agent: security-review
---
Review the following: $ARGUMENTS

disable-model-invocation: true:阻止自动调用。只有显式的 /skill-name 才能工作。适用于你不希望意外触发的破坏性技能。

shell: bash:指定执行时使用的 shell。

你在任何文档中都找不到的 Agent 字段

位于 .claude/agents/ 目录下的自定义代理支持文档未提及的 frontmatter 字段。

color:设置 UI 颜色,可选值:redorangeyellowgreenbluepurplepinkgray。当多个代理同时运行时,有助于视觉区分。

memory:这是一个大杀器。它为代理提供了跨调用的持久记忆:

  • user - 全局,跨所有项目持久化
  • project - 按项目持久化
  • local - 每个项目私有(被 git 忽略)

这意味着你可以构建一个会学习的代理。一个能追踪过去发现的安全审查员。一个能跨会话记住你代码模式的代码审查员。记忆使用与自动记忆系统相同的 frontmatter 格式。

---
name: codebase-guide
description: Answer questions about the codebase, learning more with each session
tools: [Read, Grep, Glob, Bash]
color: green
memory: project
---
You are a codebase guide with persistent memory.
Check your memory first before exploring the code.
After answering a question, save useful context to memory:
- Architecture decisions (type: project)
- Code locations for common tasks (type: reference)
- Patterns and conventions (type: feedback)

Over time, you should answer faster because you remember where things are.

经过几次会话后,这个代理会建立关于你代码库的知识库,并在 grep 之前就开始从记忆中回答。

omitClaudeMd: true:跳过加载 CLAUDE.md 指令层级。适用于“全新视角”的审查员,使用行业标准而非项目惯例:

---
name: fresh-eyes
description: Review code without project-specific biases
tools: [Read, Grep, Glob]
omitClaudeMd: true
effort: high
color: blue
---
Review this code purely from first principles.
You have no project context.
Focus on correctness, security, performance, and readability by industry standards.

criticalSystemReminder_EXPERIMENTAL:这是一个简短的消息,在每一步都会重新注入作为系统提醒。即使在对话压缩后,它仍然保持在上下文中:

---
name: prod-deployer
description: Manages production deployments with strict safety checks
tools: [Bash, Read, Grep]
color: red
criticalSystemReminder_EXPERIMENTAL: "You are deploying to production. Every command must be safe. Double-check all changes."
---
Deploy the latest version to production.
Follow all safety checks.

(由于原文内容较长,后续部分关于 Auto-Mode 配置、Dream Loops 等内容在此省略,但均基于源代码分析,提供了大量未文档化的配置选项和实用示例。)

0 阅读0 评论0 点赞

评论

登录 / 注册即可发布评论!
暂无评论,成为第一个发表评论的用户吧。