主题
Claude Code 命令系统深度解析
一、概述
Claude Code 的命令系统是用户与 CLI 交互的核心入口之一。用户在 REPL 中输入以 / 为前缀的斜杠命令(Slash Commands),即可触发从代码审查、Git 操作到会话管理等各类功能。命令系统与工具系统(Tool System)并行存在,但职责不同:
| 维度 | 命令系统(Commands) | 工具系统(Tools) |
|---|---|---|
| 触发方式 | 用户手动输入 /command | LLM 自主决策调用 |
| 调用者 | 人类用户 | Claude 模型 |
| 注册位置 | src/commands.ts + src/commands/ | src/tools.ts + src/tools/ |
| 数量 | ~101 个模块 | ~40 个工具 |
| 执行环境 | 本地进程内或委托给 LLM | 本地进程内(由 Agent Loop 编排) |
用户输入 "/review"
│
▼
┌─────────────────────────────────────────────────────────────┐
│ 命令注册表 (commands.ts) │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌──────────────────┐ │
│ │PromptCommand│ │LocalCommand │ │ LocalJSXCommand │ │
│ │ /review │ │ /cost │ │ /doctor │ │
│ │ /commit │ │ /version │ │ /install │ │
│ └──────┬──────┘ └──────┬──────┘ └────────┬─────────┘ │
│ │ │ │ │
└─────────┼────────────────┼───────────────────┼──────────────┘
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────┐ ┌──────────────┐
│ 构造 Prompt │ │ 返回纯文本│ │ 返回 React │
│ → 发送到 LLM │ │ 直接输出 │ │ JSX 组件 │
│ → 执行工具链 │ │ │ │ (Ink 渲染) │
└──────────────┘ └──────────┘ └──────────────┘二、命令类型体系
2.1 三种命令类型
Claude Code 中所有斜杠命令分为三种类型,每种类型的执行路径和能力边界完全不同:
PromptCommand(提示命令)
将用户意图格式化为 Prompt 发送给 LLM,并注入指定工具集。LLM 根据 Prompt 自主决策如何调用工具完成任务。
typescript
const reviewCommand = {
type: 'prompt',
name: 'review',
description: 'AI-powered code review',
progressMessage: 'Reviewing code...',
allowedTools: ['Bash(git diff:*)', 'FileRead(*)', 'Grep(*)'],
source: 'builtin',
async getPromptForCommand(args, context) {
const diff = await getDiff(args);
return [{
type: 'text',
text: `Review the following code changes for quality, correctness,
and security issues:\n\n${diff}`
}];
},
} satisfies Command;特点:
- 需要 LLM 推理能力,执行时会产生 API 调用和 token 消耗
- 可指定
allowedTools限制 LLM 可用的工具子集 - 执行时间不确定,取决于 LLM 的推理轮数
- 典型命令:
/review、/commit、/bughunter、/advisor
LocalCommand(本地命令)
完全在本地进程内执行,返回纯文本字符串。不涉及 LLM 调用。
typescript
const costCommand = {
type: 'local',
name: 'cost',
description: 'Show token usage and cost',
source: 'builtin',
async handler(args, context) {
const usage = context.appState.tokenUsage;
return `Input: ${usage.input} tokens\nOutput: ${usage.output} tokens\nCost: $${usage.cost}`;
},
} satisfies Command;特点:
- 零 token 消耗,即时返回
- 适合查询状态、显示信息类操作
- 典型命令:
/cost、/version、/help
LocalJSXCommand(本地 JSX 命令)
在本地进程内执行,但返回 React JSX 组件,通过 Ink 渲染引擎在终端中渲染富交互界面。
typescript
const doctorCommand = {
type: 'local-jsx',
name: 'doctor',
description: 'Run environment diagnostics',
source: 'builtin',
Component: DoctorScreen, // React 组件
} satisfies Command;特点:
- 零 token 消耗,支持全屏交互界面
- 可使用 React 状态管理和 Ink 布局系统
- 典型命令:
/doctor、/install、/statusline
2.2 命令来源分类
| 来源 (source) | 说明 | 发现机制 |
|---|---|---|
builtin | 内置命令,src/commands/ 下的模块 | 静态注册在 commands.ts |
custom | 用户自定义命令,.claude/commands/*.md | 运行时扫描目录 |
skill | Skill 系统注册,.claude/skills/*/SKILL.md | 运行时扫描 + 自动触发 |
plugin | 插件注册的命令 | 插件系统动态加载 |
mcp | MCP 服务器暴露的 Prompts | MCP 协议动态发现 |
三、命令注册表(src/commands.ts)
3.1 注册表架构
src/commands.ts 是整个命令系统的中央注册表,约 25,000 行代码。它负责:
- 命令注册:静态导入所有内置命令模块并组成命令列表
- 条件加载:通过 Bun 特性标志(Feature Flags)进行死代码消除
- 命令解析:将用户输入的
/xxx匹配到对应的 Command 定义 - 执行调度:根据命令类型分发到不同的执行路径
- 动态发现:运行时扫描自定义命令、Skill 和 MCP Prompts
typescript
// src/commands.ts 注册逻辑示意
import commitCommand from './commands/commit/index.js';
import reviewCommand from './commands/review/index.js';
import compactCommand from './commands/compact/index.js';
// ... 其余 ~100 个命令导入
// 条件导入(Feature Flag 控制)
let voiceCommand: Command | undefined;
if (feature('VOICE_MODE')) {
voiceCommand = require('./commands/voice/index.js').default;
}
const builtinCommands: Command[] = [
commitCommand,
reviewCommand,
compactCommand,
// ...
...(voiceCommand ? [voiceCommand] : []),
];
// 运行时动态发现
async function discoverCustomCommands(projectDir: string): Promise<Command[]> {
const customDir = path.join(projectDir, '.claude/commands');
// 扫描 .md 文件,生成 PromptCommand
}
async function discoverSkillCommands(projectDir: string): Promise<Command[]> {
const skillsDir = path.join(projectDir, '.claude/skills');
// 扫描 SKILL.md 文件,生成带 auto_invocable 的 PromptCommand
}
// 命令查找
function resolveCommand(input: string): Command | undefined {
const name = input.slice(1).split(' ')[0]; // 去掉 "/" 前缀
// 优先级:builtin > skill > custom > plugin > mcp
return allCommands.find(cmd =>
cmd.name === name || cmd.aliases?.includes(name)
);
}3.2 Feature Flag 控制的条件编译
Claude Code 使用 Bun 的 bun:bundle 特性标志实现编译时死代码消除。部分命令仅在特定特性启用时才会被包含在最终构建中:
| Feature Flag | 控制的命令 | 说明 |
|---|---|---|
VOICE_MODE | /voice | 语音输入/输出 |
BRIDGE_MODE | /bridge、/bridge-kick | IDE 集成桥接 |
COORDINATOR_MODE | 多 Agent 协调相关 | 多智能体编排 |
PROACTIVE | 主动行为相关 | 自主触发行为 |
DAEMON | 后台守护相关 | 守护进程模式 |
3.3 命令执行流程
用户输入: "/review --staged"
│
▼
┌─────────────────────────────┐
│ 1. 输入解析 │
│ • 提取命令名: "review" │
│ • 提取参数: "--staged" │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ 2. 命令查找 │
│ • 遍历注册表 │
│ • 检查别名 │
│ • 优先级: builtin > skill │
│ > custom > plugin > mcp │
└──────────────┬──────────────┘
│
▼
┌─────────────────────────────┐
│ 3. 类型判断 & 执行调度 │
│ │
│ ┌─PromptCommand─────────┐ │
│ │ getPromptForCommand() │ │
│ │ → 构造 Prompt │ │
│ │ → 发送到 QueryEngine │ │
│ │ → 进入 Agent Loop │ │
│ └────────────────────────┘ │
│ │
│ ┌─LocalCommand──────────┐ │
│ │ handler() │ │
│ │ → 直接执行 │ │
│ │ → 返回文本 │ │
│ └────────────────────────┘ │
│ │
│ ┌─LocalJSXCommand───────┐ │
│ │ Component │ │
│ │ → Ink 渲染 React 组件 │ │
│ │ → 全屏交互 │ │
│ └────────────────────────┘ │
└─────────────────────────────┘四、完整命令清单(101 个模块)
4.1 Git 与版本控制(10 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/commit | PromptCommand | commit.ts | — | AI 生成 commit message 并提交。分析 staged changes,生成语义化提交信息 |
/commit-push-pr | PromptCommand | commit-push-pr.ts | — | 一键完成 commit → push → 创建 PR 的完整流程 |
/diff | LocalJSXCommand | diff/ | — | 交互式 diff 查看器,支持 staged/unstaged/指定 ref 对比,逐 turn 查看变更 |
/branch | PromptCommand | branch/ | — | 创建或切换 Git 分支,支持基于当前任务自动命名 |
/review | PromptCommand | review.ts | — | AI 代码审查,分析代码质量、正确性和安全性,支持指定 PR 编号 |
/autofix-pr | PromptCommand | autofix-pr/ | — | 自动修复 PR 中的问题(lint 错误、CI 失败等) |
/pr_comments | LocalCommand | pr_comments/ | /pr-comments | 获取并展示 GitHub PR 的评论,自动检测当前分支 PR |
/teleport | LocalCommand | teleport/ | — | 将会话传输到另一台设备(CLI ↔ Web ↔ Desktop) |
/rewind | LocalJSXCommand | rewind/ | /checkpoint | 回退到之前的代码和对话状态点 |
/tag | LocalCommand | tag/ | — | 为当前会话添加标签,便于后续检索 |
/commit 工作原理:
/commit
│
▼
┌────────────────────────────────────┐
│ 1. 收集 git diff --staged 的内容 │
│ 2. 构造 Prompt: "分析变更,生成 │
│ Conventional Commits 格式的 │
│ commit message" │
│ 3. 注入工具: Bash(git *), FileRead │
│ 4. LLM 分析变更 → 生成 message │
│ 5. 展示给用户确认 → git commit │
└────────────────────────────────────┘4.2 会话与历史(8 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/session | LocalJSXCommand | session/ | — | 管理会话:列出、切换、删除、重命名 |
/resume | LocalJSXCommand | resume/ | /continue | 恢复之前的对话会话,支持按 ID 或名称 |
/clear | LocalCommand | clear/ | /reset, /new | 清空对话历史,开始全新会话 |
/compact | PromptCommand | compact/ | — | 压缩对话上下文,可指定保留重点 |
/export | LocalCommand | export/ | — | 导出对话为纯文本文件或复制到剪贴板 |
/share | LocalCommand | share/ | — | 通过链接分享当前会话 |
/summary | PromptCommand | summary/ | — | 生成当前会话的结构化摘要 |
/context | LocalJSXCommand | context/ | — | 可视化上下文窗口使用情况(彩色网格) |
/compact 的上下文压缩机制:
/compact retain the API design decisions
│
▼
┌──────────────────────────────────────────┐
│ 1. 获取当前完整对话历史 │
│ 2. 构造 Prompt: "将以下对话压缩为简洁摘要, │
│ 重点保留: API design decisions" │
│ 3. LLM 生成压缩后的上下文 │
│ 4. 用压缩后的摘要替换原始对话历史 │
│ 5. 释放 token 空间 │
│ │
│ 压缩前: 180K tokens (90% 上下文) │
│ 压缩后: 20K tokens (10% 上下文) │
└──────────────────────────────────────────┘4.3 配置与设置(11 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/config | LocalJSXCommand | config/ | /settings | 打开设置界面(Config 标签页) |
/permissions | LocalJSXCommand | permissions/ | /allowed-tools | 查看或修改工具权限规则 |
/privacy-settings | LocalJSXCommand | privacy-settings/ | — | 管理隐私设置(Pro/Max 用户) |
/theme | LocalCommand | theme/ | — | 切换终端配色主题(明/暗/色盲友好) |
/color | LocalCommand | color/ | — | 开关颜色输出 |
/keybindings | LocalCommand | keybindings/ | — | 查看或自定义按键绑定 |
/vim | LocalCommand | vim/ | — | 切换 Vim 编辑模式 |
/output-style | LocalCommand | output-style/ | — | 切换输出风格(Default / Explanatory / Learning) |
/statusline | LocalJSXCommand | statusline.tsx | — | 配置终端状态栏显示内容 |
/env | LocalCommand | env/ | — | 查看环境变量 |
/terminal-setup | LocalCommand | terminalSetup/ | — | 安装 Shift+Enter 快捷键(iTerm2/VSCode) |
4.4 Agent 与任务管理(5 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/agents | LocalJSXCommand | agents/ | — | 管理子 Agent 配置(查看、添加、删除) |
/tasks | LocalJSXCommand | tasks/ | — | 列出并管理后台任务 |
/brief | LocalCommand | brief.ts | — | 切换简洁输出模式 |
/ultraplan | PromptCommand | ultraplan.tsx | — | 生成详细的多步执行计划(云端并行多 Agent 审查) |
/plan | LocalCommand | plan/ | — | 进入计划模式,Claude 先提议再执行 |
/ultraplan 的多 Agent 编排:
/ultraplan "Refactor the auth module"
│
▼
┌──────────────────────────────────────────┐
│ 1. 主 Agent 分析任务,分解为子任务 │
│ 2. 为每个子任务创建独立的 sub-agent │
│ 3. Sub-agents 并行执行: │
│ • Agent-1: 分析现有架构 │
│ • Agent-2: 审查安全性 │
│ • Agent-3: 规划测试策略 │
│ 4. 汇总所有 sub-agent 的结果 │
│ 5. 生成综合执行计划 │
└──────────────────────────────────────────┘4.5 文件与代码操作(5 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/files | LocalCommand | files/ | — | 列出当前上下文中的文件 |
/add-dir | LocalCommand | add-dir/ | — | 添加额外的工作目录到会话 |
/copy | LocalCommand | copy/ | — | 复制最后一条回复到剪贴板,支持代码块选择器 |
/debug-tool-call | LocalCommand | debug-tool-call/ | — | 调试特定工具调用的执行细节 |
/rename | LocalCommand | rename/ | — | 重命名当前会话,无参数时自动生成名称 |
4.6 开发与调试(6 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/doctor | LocalJSXCommand | doctor/ | — | 全面环境诊断:API 连接、认证、工具可用性、MCP 状态 |
/heapdump | LocalCommand | heapdump/ | — | 导出堆内存快照用于分析内存泄漏 |
/perf-issue | LocalCommand | perf-issue/ | — | 报告性能问题,收集诊断数据 |
/stats | LocalJSXCommand | stats/ | — | 可视化每日使用量、会话历史和连续使用天数 |
/bughunter | PromptCommand | bughunter/ | — | AI 驱动的 Bug 搜索,扫描代码库查找潜在缺陷 |
/ctx_viz | LocalCommand | ctx_viz/ | — | 上下文可视化调试工具(内部调试用) |
/doctor 诊断检查项:
/doctor
│
▼
┌────────────────────────────────────────┐
│ ✓ Node.js / Bun 版本检查 │
│ ✓ API 连接性测试 │
│ ✓ 认证状态验证 │
│ ✓ 工具可用性检查(git, gh, etc.) │
│ ✓ MCP 服务器连接状态 │
│ ✓ 文件系统权限 │
│ ✓ 网络代理配置 │
│ ✓ 磁盘空间检查 │
│ ✓ 配置文件有效性 │
│ ✓ 插件兼容性 │
└────────────────────────────────────────┘4.7 身份认证(3 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/login | LocalJSXCommand | login/ | — | 登录 Anthropic 账户,支持浏览器 OAuth 和手动 token |
/logout | LocalCommand | logout/ | — | 登出当前账户 |
/oauth-refresh | LocalCommand | oauth-refresh/ | — | 刷新 OAuth token |
4.8 扩展与插件(4 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/mcp | LocalJSXCommand | mcp/ | — | 管理 MCP 服务器连接:查看/添加/删除/测试/认证 |
/plugin | LocalJSXCommand | plugin/ | — | 安装、移除、管理插件 |
/reload-plugins | LocalCommand | reload-plugins/ | — | 重新加载所有已安装的插件 |
/skills | LocalCommand | skills/ | — | 列出可用的 Skill |
/mcp 的 MCP 服务器管理:
/mcp
│
├── 查看所有已配置的 MCP 服务器及连接状态
├── 添加新服务器: /mcp add <name> -- <command>
├── 删除服务器: /mcp remove <name>
├── 测试连接: /mcp test <name>
├── 查看日志: /mcp logs <name>
├── OAuth 认证: /mcp auth <name>
└── 查看工具/Prompts: /mcp tools <name>4.9 工作区(3 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/plan | LocalCommand | plan/ | — | 进入计划模式,Claude 先展示行动方案再执行 |
/sandbox-toggle | LocalCommand | sandbox-toggle/ | /sandbox | 切换沙箱模式,隔离文件系统和网络 |
/init | LocalCommand | init.ts | — | 初始化项目,创建 CLAUDE.md 指导文件 |
4.10 信息与帮助(8 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/help | LocalCommand | help/ | — | 显示所有可用命令列表 |
/version | LocalCommand | version.ts | — | 显示 Claude Code 版本号 |
/cost | LocalCommand | cost/ | — | 显示当前会话的 token 使用量和估算费用 |
/usage | LocalCommand | usage/ | — | 显示计划使用限额和速率限制状态 |
/extra-usage | LocalCommand | extra-usage/ | — | 配置速率限制时的额外用量 |
/release-notes | LocalCommand | release-notes/ | — | 查看完整更新日志 |
/status | LocalJSXCommand | status/ | — | 显示版本、模型、账户和连接信息 |
/insights | PromptCommand | insights.ts | — | 分析 Claude Code 使用会话,生成洞察报告 |
4.11 平台集成(8 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/desktop | LocalCommand | desktop/ | /app | 将会话转移到 Claude Code Desktop 应用 |
/mobile | LocalCommand | mobile/ | — | 将会话转移到移动端 |
/chrome | LocalCommand | chrome/ | — | 配置 Chrome 浏览器集成 |
/ide | LocalCommand | ide/ | — | 管理 IDE 集成(VS Code / JetBrains)状态 |
/install | LocalJSXCommand | install.tsx | — | 安装或更新 Claude Code |
/install-github-app | LocalCommand | install-github-app/ | — | 设置 Claude GitHub Actions 自动 PR 审查 |
/install-slack-app | LocalCommand | install-slack-app/ | — | 安装 Slack 应用集成 |
/bridge | LocalCommand | bridge/ | — | 管理 IDE 桥接连接 |
4.12 记忆与知识(2 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/memory | LocalJSXCommand | memory/ | — | 编辑 CLAUDE.md 记忆文件,切换自动记忆功能 |
/good-claude | LocalCommand | good-claude/ | — | 彩蛋:表扬 Claude(正向反馈机制) |
/memory 的记忆层级:
/memory
│
├── ~/.claude/CLAUDE.md ← 用户级全局记忆
├── /project/.claude/CLAUDE.md ← 项目级记忆
├── /project/CLAUDE.md ← 项目根记忆
└── /project/src/CLAUDE.md ← 目录级记忆(嵌套索引)4.13 模型与性能(6 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/model | LocalJSXCommand | model/ | — | 切换活跃模型(sonnet / opus / haiku) |
/effort | LocalJSXCommand | effort/ | — | 调节推理努力程度滑块(low / medium / high / xhigh / max) |
/fast | LocalCommand | fast/ | — | 切换快速模式(同模型,更快输出) |
/thinkback | LocalCommand | thinkback/ | — | 回放 Claude 的思考过程 |
/thinkback-play | LocalCommand | thinkback-play/ | — | 动画形式回放思考过程 |
/advisor | PromptCommand | advisor.ts | — | 获取架构设计或技术选型建议 |
4.14 代码质量(2 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/review | PromptCommand | review.ts | — | AI 代码审查:质量、正确性、安全性 |
/security-review | PromptCommand | security-review.ts | — | 安全专项审查:注入、认证、数据暴露 |
4.15 特殊操作与杂项(20 个)
| 命令 | 类型 | 源文件 | 别名 | 说明 |
|---|---|---|---|---|
/voice | LocalJSXCommand | voice/ | — | 切换语音输入模式 |
/remote-setup | LocalCommand | remote-setup/ | — | 设置远程会话 |
/remote-env | LocalCommand | remote-env/ | — | 配置远程环境 |
/stickers | LocalCommand | stickers/ | — | 彩蛋:贴纸 |
/feedback | LocalCommand | feedback/ | /bug | 提交反馈或 Bug 报告给 Anthropic |
/onboarding | LocalJSXCommand | onboarding/ | — | 首次使用引导向导 |
/passes | LocalCommand | passes/ | — | 多轮执行模式 |
/exit | LocalCommand | exit/ | /quit | 退出 Claude Code |
/fork | LocalCommand | — | — | 从当前对话分叉为新会话 |
/hooks | LocalJSXCommand | hooks/ | — | 配置和管理生命周期 Hooks |
/bridge-kick | LocalCommand | bridge-kick.ts | — | 强制重启 IDE 桥接 |
/x402 | LocalCommand | x402/ | — | x402 支付协议集成 |
/issue | LocalCommand | issue/ | — | 提交 GitHub Issue |
/remote-control | LocalCommand | — | /rc | 使会话可从 claude.ai 远程控制 |
4.16 内部 / 调试命令(10 个)
这些命令主要供 Anthropic 内部团队或高级调试场景使用:
| 命令 | 类型 | 源文件 | 说明 |
|---|---|---|---|
/ant-trace | LocalCommand | ant-trace/ | Anthropic 内部追踪 |
/backfill-sessions | LocalCommand | backfill-sessions/ | 回填会话数据 |
/break-cache | LocalCommand | break-cache/ | 使缓存失效 |
/btw | LocalCommand | btw/ | "顺便说一下" 插入提示 |
/mock-limits | LocalCommand | mock-limits/ | 模拟速率限制(测试用) |
/reset-limits | LocalCommand | reset-limits/ | 重置速率限制计数器 |
/init-verifiers | LocalCommand | init-verifiers.ts | 设置验证器 Hooks |
/upgrade | LocalCommand | upgrade/ | 升级到最新版本 |
/rate-limit-options | LocalCommand | rate-limit-options/ | 查看速率限制配置 |
/less-permission-prompts | LocalCommand | — | 分析常用审批模式,建议权限白名单 |
五、命令定义结构(Command 接口)
5.1 TypeScript 接口定义
typescript
// 基础 Command 接口
interface BaseCommand {
name: string; // 命令名称(不含 /)
description: string; // 描述文本(显示在 /help 中)
aliases?: string[]; // 别名列表
source: 'builtin' | 'custom' | 'skill' | 'plugin' | 'mcp';
isAvailable?: (context: AppContext) => boolean; // 可用性检查
}
// PromptCommand:发送到 LLM
interface PromptCommand extends BaseCommand {
type: 'prompt';
progressMessage: string; // 执行时的进度提示
allowedTools: string[]; // 允许 LLM 使用的工具列表
getPromptForCommand(
args: string,
context: CommandContext
): Promise<ContentBlock[]>; // 构造发送给 LLM 的 Prompt
}
// LocalCommand:本地执行,返回纯文本
interface LocalCommand extends BaseCommand {
type: 'local';
handler(
args: string,
context: CommandContext
): Promise<string>; // 执行逻辑,返回纯文本
}
// LocalJSXCommand:本地执行,返回 React 组件
interface LocalJSXCommand extends BaseCommand {
type: 'local-jsx';
Component: React.ComponentType<CommandProps>; // React/Ink 组件
}
type Command = PromptCommand | LocalCommand | LocalJSXCommand;5.2 命令模块目录结构
每个命令是 src/commands/ 下的一个独立模块(目录或单文件):
src/commands/
├── commit.ts ← 单文件命令
├── commit-push-pr.ts
├── review.ts
├── security-review.ts
├── advisor.ts
├── brief.ts
├── version.ts
├── insights.ts
├── install.tsx ← JSX 组件命令(.tsx)
├── ultraplan.tsx
├── statusline.tsx
├── init.ts
├── init-verifiers.ts
├── bridge-kick.ts
│
├── compact/ ← 目录形式命令
│ ├── index.ts ← 导出 Command 定义
│ ├── compactLogic.ts ← 压缩逻辑
│ └── utils.ts
│
├── doctor/
│ ├── index.ts
│ ├── DoctorScreen.tsx ← 全屏诊断界面
│ ├── checks/ ← 各项检查逻辑
│ │ ├── apiCheck.ts
│ │ ├── authCheck.ts
│ │ ├── toolCheck.ts
│ │ └── mcpCheck.ts
│ └── components/ ← UI 子组件
│
├── mcp/
│ ├── index.ts
│ ├── McpManager.tsx
│ ├── addServer.ts
│ ├── removeServer.ts
│ └── testConnection.ts
│
├── bughunter/
│ ├── index.ts
│ ├── scanStrategies.ts
│ └── reportGenerator.ts
│
└── ... (其余 ~90 个命令模块)六、自定义命令
6.1 用户自定义斜杠命令(Legacy)
在 .claude/commands/ 目录下创建 Markdown 文件,即可注册为 PromptCommand:
.claude/commands/
├── deploy.md → /deploy
├── test-e2e.md → /test-e2e
└── team/
├── standup.md → /team:standup (命名空间)
└── retro.md → /team:retromarkdown
<!-- .claude/commands/deploy.md -->
Deploy the application to the specified environment.
## Steps
1. Run `npm test` to verify all tests pass
2. Run `npm run build` for production
3. Execute `./scripts/deploy.sh $ARGUMENTS`
4. Verify health check at the deployment URL
## Rules
- Never deploy to production on Friday
- Always verify the test suite passes first$ARGUMENTS占位符会被替换为用户传入的参数- 支持项目级(
.claude/commands/)和个人级(~/.claude/commands/) - 目录结构会映射为命名空间:
team/standup.md→/team:standup
6.2 Skills 系统命令(推荐)
Skills 是自定义命令的升级形态,支持自动触发、多文件、和更丰富的配置:
.claude/skills/
└── code-review/
├── SKILL.md ← 主定义文件
├── checklist.md ← 辅助资源
└── examples/
└── good-review.md ← 示例文件markdown
<!-- .claude/skills/code-review/SKILL.md -->
---
name: code-review
description: "Thorough code review following team standards.
Use when the user asks for a code review or mentions reviewing code."
user_invocable: true # 允许 /code-review 手动调用
auto_invocable: true # 允许 Claude 自动触发
model: opus # 强制使用特定模型
tools: # 限制可用工具
- Read
- Grep
- Glob
---
# Code Review Standards
## Review Checklist
1. **Logic correctness** — Are there off-by-one errors, race conditions?
2. **Error handling** — Are all error paths covered?
3. **Security** — Any injection, auth bypass, or data exposure risks?
4. **Performance** — N+1 queries, unnecessary allocations?
5. **Readability** — Clear naming, appropriate abstractions?Skills vs Legacy Commands 对比:
| 特性 | Legacy Commands | Skills |
|---|---|---|
| 位置 | .claude/commands/name.md | .claude/skills/name/SKILL.md |
| 触发方式 | 仅手动 /name | 手动 + 自动触发 |
| 辅助文件 | 不支持 | 支持(模板、脚本、示例) |
| Frontmatter | 可选 | 完整控制(模型、工具、触发条件) |
| 同名优先级 | 低 | 高(Skill 优先于 Command) |
6.3 MCP Prompts 命令
MCP 服务器可以暴露 Prompts,自动注册为斜杠命令:
json
// MCP 服务器返回的 Prompt 定义
{
"name": "analyze-db",
"description": "Analyze database schema and suggest optimizations",
"arguments": [
{ "name": "table", "description": "Table name to analyze", "required": true }
]
}使用时直接 /analyze-db users,Claude Code 会调用 MCP 服务器的 getPrompt 方法获取完整 Prompt。
6.4 插件命令
插件可以通过插件 API 注册自定义命令:
typescript
// 插件注册命令示例
export default {
name: 'my-plugin',
commands: [
{
type: 'local',
name: 'lint-fix',
description: 'Auto-fix lint errors',
source: 'plugin',
async handler(args, ctx) {
// 插件逻辑
return 'Fixed 12 lint errors';
}
}
]
};七、命令权限模型
7.1 工具权限(allowedTools)
PromptCommand 通过 allowedTools 字段限制 LLM 可以调用的工具子集:
typescript
// /review 命令只允许只读操作
{
allowedTools: [
'Bash(git diff:*)', // 只允许 git diff 系列命令
'Bash(git log:*)', // 只允许 git log 系列命令
'FileRead(*)', // 允许读取任意文件
'Grep(*)', // 允许搜索
'Glob(*)', // 允许文件匹配
]
}
// /commit 命令允许 Git 写操作
{
allowedTools: [
'Bash(git *)', // 允许所有 git 命令
'FileRead(*)',
]
}7.2 权限模式匹配语法
Tool(pattern)
模式说明:
Bash(git diff:*) → 允许 bash 执行 "git diff" 开头的命令
FileRead(*) → 允许读取任何文件
FileRead(src/*.ts) → 只允许读取 src/ 下的 .ts 文件
Edit(*) → 允许编辑任何文件
SlashCommand:/commit → 精确匹配 /commit 命令
SlashCommand:/review-pr:* → 匹配 /review-pr 及其所有参数八、CLI 标志与命令的关系
CLI 标志(Flags)在启动时设置,影响整个会话的行为。部分标志直接关联到斜杠命令:
| CLI Flag | 对应命令 | 说明 |
|---|---|---|
claude -c | /resume | 恢复最近的会话 |
claude -r <id> | /resume <id> | 恢复指定会话 |
claude --model opus | /model opus | 设置模型 |
claude --add-dir ../lib | /add-dir ../lib | 添加工作目录 |
claude --mcp-config ./mcp.json | /mcp | MCP 配置 |
claude --init | /init | 初始化项目 |
claude --chrome | /chrome | Chrome 集成 |
claude --ide | /ide | IDE 集成 |
非交互模式(Print Mode)
-p 标志启用非交互模式,命令直接执行并退出:
bash
# 等价于在 REPL 中输入 "/review" 但无需交互
claude -p "Review the last commit for security issues" \
--output-format json \
--max-turns 5 \
--max-budget-usd 2.00
# 管道模式
cat error.log | claude -p "What caused this crash?"
# 结构化输出
claude -p --output-format json --json-schema '{"type":"object"}' "Analyze this code"九、快捷键体系
Claude Code 的快捷键系统与命令系统互补,提供无需输入 / 的快速操作:
9.1 核心快捷键
| 快捷键 | 功能 | 等价命令 |
|---|---|---|
Escape | 取消当前生成 | — |
Escape × 2 | 回退/撤销 Claude 的操作 | /rewind |
Ctrl+C × 2 | 退出会话 | /exit |
Ctrl+R | 反向搜索历史 | — |
Ctrl+T | 切换任务列表 | /tasks |
Shift+Tab | 循环切换权限模式 | /permissions |
Ctrl+O | 切换详细输出 | — |
Ctrl+B | 后台运行任务 | — |
Ctrl+G | 用外部编辑器编辑 Prompt | — |
Alt+P / Option+P | 切换模型 | /model |
Alt+T / Option+T | 切换扩展思考 | — |
9.2 输入前缀
| 前缀 | 功能 | 示例 |
|---|---|---|
/ | 执行斜杠命令 | /compact retain error patterns |
! | 直接执行 Bash 命令 | ! git status |
@ | 文件路径自动补全 | @src/main.ts |
十、命令系统设计原则
10.1 分层架构
┌─────────────────────────────────────────────────────┐
│ 用户层 │
│ /command │ 快捷键 │ CLI flags │ 自定义命令 │
├─────────────────────────────────────────────────────┤
│ 命令层 │
│ commands.ts 注册表 │ 命令解析 │ 类型路由 │
├─────────────────────────────────────────────────────┤
│ 执行层 │
│ PromptCommand │ LocalCommand │ LocalJSXCommand│
│ → QueryEngine │ → 直接返回 │ → Ink 渲染 │
├─────────────────────────────────────────────────────┤
│ 基础设施层 │
│ AppState │ Permission │ Config │ Telemetry │
└─────────────────────────────────────────────────────┘10.2 设计决策
- 模块化目录结构:每个命令独立一个模块(目录或文件),便于维护和条件编译
- 三类型分离:严格区分需要 LLM 的操作(PromptCommand)和本地操作(Local/LocalJSX)
- 多来源统一接口:内置、自定义、Skill、插件、MCP 五种来源通过统一的 Command 接口抽象
- 权限最小化:每个 PromptCommand 显式声明允许的工具子集,防止越权
- 懒加载 + Feature Flags:通过 Bun 特性标志和动态 import 控制加载,优化启动性能
- React/Ink 渲染:利用 React 组件模型构建复杂终端 UI,实现全屏交互界面
- 别名系统:常用命令支持多别名(如
/clear→/reset//new),降低记忆成本
10.3 扩展性设计
Claude Code 的命令系统支持四种扩展机制,按优先级排列:
优先级(高 → 低):
1. 内置命令 (builtin) ← src/commands/
2. Skill 命令 (skill) ← .claude/skills/
3. 自定义命令 (custom) ← .claude/commands/
4. 插件命令 (plugin) ← 插件系统
5. MCP 命令 (mcp) ← MCP 服务器 Prompts当同名命令存在于多个来源时,高优先级来源胜出。
十一、实用命令速查表
日常开发高频命令
| 场景 | 命令 | 说明 |
|---|---|---|
| 上下文快满了 | /compact retain key decisions | 保留重要信息,释放 token |
| 切换新任务 | /clear | 彻底清空,避免旧上下文干扰 |
| 查看花费 | /cost | 监控 token 消耗 |
| 代码审查 | /review 或 /review 42 | 审查当前变更或指定 PR |
| 提交代码 | /commit | AI 生成语义化 commit message |
| 一键发 PR | /commit-push-pr | commit → push → create PR |
| 看上下文 | /context | 可视化上下文窗口占用 |
| 切换模型 | /model opus | 复杂任务用 Opus |
| 恢复会话 | /resume | 继续昨天的工作 |
| 环境诊断 | /doctor | 排查连接、认证等问题 |
效率提升组合技
bash
# 组合 1:高效代码审查
/model opus # 切换到强模型
/review # 执行代码审查
/model sonnet # 切换回经济模型
# 组合 2:上下文管理
/context # 查看使用量
/compact retain the auth flow and test results
/cost # 确认节省
# 组合 3:自动化 CI
claude -p --max-budget-usd 1.00 \
--allowedTools "Bash(git *)" "Read" "Grep" \
"Review the last commit for security issues" \
--output-format json