目录
  1. 1. 一、命令 vs 工具
  2. 2. 二、命令定义结构
  3. 3. 三、60+ 内置命令分类
    1. 3.1. 3.1 对话控制类
    2. 3.2. 3.2 Git/PR 类
    3. 3.3. 3.3 配置类
    4. 3.4. 3.4 项目分析类
    5. 3.5. 3.5 MCP/插件类
    6. 3.6. 3.6 远程/协作类
    7. 3.7. 3.7 高级功能类
    8. 3.8. 3.8 条件编译命令
  4. 4. 四、命令注册机制
  5. 5. 五、命令执行流程
  6. 6. 六、典型命令实现分析
    1. 6.1. 6.1 /compact — 对话压缩
    2. 6.2. 6.2 /commit — AI 提交
    3. 6.3. 6.3 /init — 项目初始化
  7. 7. 七、命令与工具的交互
  8. 8. 八、Skill-Tool 命令
  9. 9. 涉及源文件
【Claude Code源码剖析】04-命令系统

⚠️ 学习声明:本文档基于 Claude Code 2.1.88 源码分析整理,仅供个人学习研究使用,不做任何商业用途。

用户在 REPL 中输入 /help/commit/compact 等斜杠命令,由命令系统处理。


一、命令 vs 工具

维度 命令 (Command) 工具 (Tool)
触发方 用户 输入 /xxx LLM 决定调用
入口 commands.ts tools.ts
执行环境 REPL 内 Agentic Loop 内
权限 用户自己操作,无需检查 需要权限系统审批
UI 可直接渲染 JSX 通过 setToolJSX 渲染

二、命令定义结构

// types/command.ts (推断的类型)
type Command = {
name: string; // 命令名 (如 "help")
aliases?: string[]; // 别名
description: string; // 描述
isEnabled?: (context) => boolean; // 是否启用
isHidden?: boolean; // 是否隐藏

// 执行函数:返回 CommandResultDisplay
run: (args: string, context: CommandContext) => Promise<CommandResultDisplay>;

// 或者:返回 JSX (用于交互式命令)
renderJSX?: (args, context) => React.ReactNode;

// 自动补全
getCompletions?: (partial: string) => string[];
}

type CommandResultDisplay =
| { type: 'text'; content: string }
| { type: 'jsx'; element: React.ReactNode }
| { type: 'messages'; messages: Message[] } // 注入到对话历史
| { type: 'none' }

三、60+ 内置命令分类

3.1 对话控制类

命令 文件 功能
/help commands/help/ 显示帮助信息
/clear commands/clear/ 清除对话历史
/compact commands/compact/ 手动压缩对话上下文
/resume commands/resume/ 恢复历史会话
/session commands/session/ 会话管理
/cost commands/cost/ 显示当前花费
/status commands/status/ 显示系统状态

3.2 Git/PR 类

命令 文件 功能
/commit commands/commit.ts AI 生成 commit message 并提交
/commit-push-pr commands/commit-push-pr.ts 提交 + 推送 + 创建 PR
/review commands/review.ts AI 代码审查
/diff commands/diff/ 显示文件 diff
/pr_comments commands/pr_comments/ PR 评论管理

3.3 配置类

命令 文件 功能
/config commands/config/ 查看/修改配置
/init commands/init.ts 初始化项目 (生成 CLAUDE.md)
/login commands/login/ 登录认证
/logout commands/logout/ 注销
/theme commands/theme/ 切换主题
/vim commands/vim/ Vim 模式开关
/keybindings commands/keybindings/ 快捷键配置

3.4 项目分析类

命令 文件 功能
/init-verifiers commands/init-verifiers.ts 初始化验证器
/doctor commands/doctor/ 诊断项目问题
/context commands/context/ 查看上下文使用
/memory commands/memory/ 管理 Memory 文件
/security-review commands/security-review.ts 安全审查
/bughunter commands/bughunter/ Bug 搜索

3.5 MCP/插件类

命令 文件 功能
/mcp commands/mcp/ MCP 服务器管理
/skills commands/skills/ 技能管理
/install commands/install.tsx 安装插件

3.6 远程/协作类

命令 文件 功能
/share commands/share/ 分享对话
/teleport commands/teleport/ 会话传送(设备间)
/bridge commands/bridge/ 远程桥接 (feature flag)
/mobile commands/mobile/ 移动端连接
/desktop commands/desktop/ 桌面端交互
/ide commands/ide/ IDE 集成

3.7 高级功能类

命令 文件 功能
/agents commands/agents/ Agent 管理
/tasks commands/tasks/ 后台任务管理
/add-dir commands/add-dir/ 添加工作目录
/branch commands/branch/ 分支管理
/copy commands/copy/ 复制内容到剪贴板
/rename commands/rename/ 重命名会话

3.8 条件编译命令

// 这些命令只在特定 feature flag 下启用
const proactive = feature('PROACTIVE') ? require('./commands/proactive.js') : null;
const briefCommand = feature('KAIROS') ? require('./commands/brief.js') : null;
const voiceCommand = feature('VOICE_MODE') ? require('./commands/voice/index.js') : null;
const bridge = feature('BRIDGE_MODE') ? require('./commands/bridge/index.js') : null;

四、命令注册机制

// commands.ts
export function getCommands(): Command[] {
return [
addDir, autofixPr, backfillSessions, btw, goodClaude,
issue, feedback, clear, color, commit, copy, desktop,
commitPushPr, compact, config, context, cost, diff,
// ... 60+ 命令
].filter(cmd => cmd != null); // 过滤掉条件编译为 null 的命令
}

// 命令查找
export function getCommand(name: string): Command | undefined {
return getCommands().find(
cmd => cmd.name === name || cmd.aliases?.includes(name)
);
}

// 过滤远程模式不可用的命令
export function filterCommandsForRemoteMode(commands: Command[]): Command[] {
// 远程模式下禁用本地文件操作相关命令
}

五、命令执行流程

用户输入: /commit -m "fix: bug"


processUserInput() (utils/processUserInput/)

├─ 检测 "/" 前缀 → isSlashCommand()
├─ 解析命令名: "commit"
├─ 解析参数: "-m \"fix: bug\""


getCommand("commit")

├─ 找到 commit 命令定义

command.run(args, context)

├─ commit.ts:
│ 1. 获取 git diff
│ 2. 调用 Claude API 生成 commit message
│ 3. 执行 git commit
│ 4. 返回 { type: 'text', content: '已提交: ...' }


CommandResultDisplay → 渲染到 UI

六、典型命令实现分析

6.1 /compact — 对话压缩

// commands/compact/ (简化)
export default {
name: 'compact',
description: '压缩对话历史以释放上下文空间',
run: async (args, { messages, model, tools, ... }) => {
// 1. 调用压缩引擎
const result = await compactConversation(messages, {
model,
customPrompt: args || undefined, // 用户可提供压缩指引
});

// 2. 替换消息历史
replaceMessages(result.compactedMessages);

// 3. 返回压缩报告
return {
type: 'text',
content: `已压缩 ${result.removedCount} 条消息,节省约 ${result.savedTokens} tokens`
};
}
};

6.2 /commit — AI 提交

// commands/commit.ts (简化)
export default {
name: 'commit',
description: '生成并执行 git commit',
run: async (args, context) => {
// 1. 获取 staged changes
const diff = await exec('git diff --staged');

// 2. 如果没有 staged changes,先 stage 所有修改
if (!diff) await exec('git add .');

// 3. 调用 Claude 生成 commit message
const commitMsg = await generateCommitMessage(diff, context);

// 4. 执行 commit
await exec(`git commit -m "${commitMsg}"`);

return { type: 'text', content: `Committed: ${commitMsg}` };
}
};

6.3 /init — 项目初始化

// commands/init.ts (简化)
export default {
name: 'init',
description: '为项目生成 CLAUDE.md 文件',
run: async (args, context) => {
// 1. 分析项目结构
const projectInfo = await analyzeProject(context.cwd);

// 2. 调用 Claude 生成 CLAUDE.md 内容
const content = await generateClaudeMd(projectInfo);

// 3. 写入文件
await writeFile('CLAUDE.md', content);

return { type: 'text', content: '已创建 CLAUDE.md' };
}
};

七、命令与工具的交互

某些命令会将自己转化为 注入到对话中的消息,从而触发 LLM 使用工具:

// 返回 messages 类型的结果会注入到对话历史
return {
type: 'messages',
messages: [
createUserMessage({
content: `请帮我 review 下面的 diff:\n${diff}`
})
]
};
// → LLM 会看到这条消息,然后可能使用 FileRead/Grep 等工具来分析代码

八、Skill-Tool 命令

部分命令实际上是 “Skill” 的入口,它们注入特定的 prompt 来触发 LLM 的特定行为:

// 通过 getSkillToolCommands() 动态生成
// 例如用户自定义的 "fix-tests" 技能会变成 /fix-tests 命令
export function getSlashCommandToolSkills(): Command[] {
return loadedSkills
.filter(skill => skill.slashCommand)
.map(skill => ({
name: skill.slashCommand,
description: skill.description,
run: async (args) => {
return {
type: 'messages',
messages: [createUserMessage({ content: skill.prompt + '\n' + args })]
};
}
}));
}

涉及源文件

  • bridge/index.js
  • commands/add-dir/
  • commands/agents/
  • commands/branch/
  • commands/bridge/
  • commands/bughunter/
  • commands/clear/
  • commands/commit-push-pr.ts
  • commands/commit.ts
  • commands/compact/
  • commands/config/
  • commands/context/
  • commands/copy/
  • commands/cost/
  • commands/desktop/
  • commands/diff/
  • commands/doctor/
  • commands/help/
  • commands/ide/
  • commands/init-verifiers.ts
  • commands/init.ts
  • commands/install.tsx
  • commands/keybindings/
  • commands/login/
  • commands/logout/
  • commands/mcp/
  • commands/memory/
  • commands/mobile/
  • commands/pr_comments/
  • commands/rename/
  • commands/resume/
  • commands/review.ts
  • commands/security-review.ts
  • commands/session/
  • commands/share/
  • commands/skills/
  • commands/status/
  • commands/tasks/
  • commands/teleport/
  • commands/theme/
  • commands/vim/
打赏
  • 微信
  • 支付宝

评论