目录
  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. 九、命令系统的设计模式
    1. 9.1. 11.1 Command Pattern 的实现
    2. 9.2. 11.2 60+ 命令的分类
    3. 9.3. 11.3 命令 vs 工具
  10. 10. 十、命令生命周期与中间件
    1. 10.1. 12.1 命令执行管道
    2. 10.2. 12.2 命令中间件
  11. 11. 十一、命令自动补全与发现机制
    1. 11.1. 13.1 命令注册流程
    2. 11.2. 13.2 动态命令
    3. 11.3. 13.3 与 VSCode Command Palette 的对比
  12. 12. 十二、命令实现的工程规范
    1. 12.1. 14.1 命令文件的组织结构
    2. 12.2. 14.2 错误处理模式
  13. 13. 涉及源文件
【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 })]
};
}
}));
}

九、命令系统的设计模式

11.1 Command Pattern 的实现

Claude Code 的命令系统是经典 Command Pattern(Gamma et al., 1994, Design Patterns)的现代 TypeScript 实现:

interface Command {
name: string; // 命令名(如 /compact, /review)
description: string; // 显示在 help 中
args?: CommandArg[]; // 参数定义
handler: (context: CommandContext) => Promise<void> | void;
isHidden?: boolean; // 是否在 help 中隐藏
requiresAuth?: boolean; // 是否需要认证
}

11.2 60+ 命令的分类

命令分类:
├─ 会话管理 (8个)
│ /compact, /clear, /context, /resume, /save, /load, /init, /status

├─ 文件操作 (6个)
│ /add-dir, /ide, /vim, /cat, /doctor, /update

├─ 权限控制 (5个)
│ /permissions, /login, /logout, /whoami, /bug

├─ Agent 管理 (10个)
│ /agents, /task, /swarm, /team, /todo, /delegate, /fork, /merge

├─ 配置管理 (8个)
│ /config, /model, /theme, /output-style, /memory, /hooks, /mcp, /plugin

├─ 调试/诊断 (7个)
│ /doctor, /debug, /api-usage, /token-usage, /cost, /stats

├─ 代码审查 (4个)
│ /review, /pr, /diff, /test

└─ 其他 (约 12个)
/bashes, /export, /mcp, /teleport, /vim, /web-search

11.3 命令 vs 工具

维度 命令 (Commands) 工具 (Tools)
触发者 用户(通过 /command) LLM(通过 tool_use)
执行时机 用户输入时 LLM 请求时
权限 用户自身权限 Agent 权限(可能受限)
示例 /compact, /review FileEdit, BashTool

命令是用户的手段,工具是 Agent 的手段。两者互补。


十、命令生命周期与中间件

12.1 命令执行管道

用户输入 "/compact"

├─ 1. 解析: Commander.js 匹配 /compact 命令
├─ 2. 认证检查: requiresAuth? → 验证 token
├─ 3. 参数验证: Zod schema 校验参数
├─ 4. 前置钩子: runPreCommandHooks()
├─ 5. 命令执行: command.handler(context)
├─ 6. 后置钩子: runPostCommandHooks()
└─ 7. UI 更新: 响应返回给 REPL

12.2 命令中间件

类似 Express.js 的中间件模式:

type CommandMiddleware = (
cmd: Command,
ctx: CommandContext,
next: () => Promise<void>
) => Promise<void>;

// 日志中间件
const loggingMiddleware: CommandMiddleware = async (cmd, ctx, next) => {
logger.info(`Command: /${cmd.name}`, { args: ctx.args });
await next();
logger.info(`Command /${cmd.name} completed`);
};

// 权限中间件
const authMiddleware: CommandMiddleware = async (cmd, ctx, next) => {
if (cmd.requiresAuth && !ctx.isAuthenticated) {
throw new AuthError('Login required');
}
await next();
};


十一、命令自动补全与发现机制

13.1 命令注册流程

启动时:
1. 扫描 commands/ 目录下所有子目录
2. 每个子目录的 index.ts 导出 Command 对象
3. 注册到 Commander.js program 实例
4. 构建命令索引(用于自动补全)

运行时:
1. 用户输入 "/" 触发补全菜单
2. 基于前缀匹配 + 上下文排序
3. 最近使用的命令排在前面

13.2 动态命令

部分命令不是静态注册的,而是根据上下文动态生成:

  • /mcp__<server>__<tool> 命令由 MCP 服务器动态注入
  • 插件可以注册新的命令(plugin.registerCommand()
  • 技能(Skills)可以添加带命名空间的命令

13.3 与 VSCode Command Palette 的对比

维度 CC Commands VSCode Command Palette
触发方式 /command 文本输入 Ctrl+Shift+P GUI
发现性 / 触发自动补全 搜索 + 分类浏览
扩展性 MCP + 插件 + 技能 扩展 API
上下文感知 项目类型/语言 文件类型/workspace

十二、命令实现的工程规范

14.1 命令文件的组织结构

commands/<command-name>/
├─ index.ts # 命令注册入口(export default command)
├─ handler.ts # 核心逻辑
└─ utils.ts # 辅助函数

每个命令不到 200 行,职责单一。

14.2 错误处理模式

// 统一的命令错误处理
async function executeCommand(cmd: Command, ctx: CommandContext): Promise<void> {
try {
await cmd.handler(ctx);
} catch (err) {
if (err instanceof UserFacingError) {
ctx.reply(`❌ ${err.message}`); // 用户可理解的错误
} else {
logger.error(`Command /${cmd.name} failed`, err);
ctx.reply('❌ Internal error. Check logs for details.');
}
}
}

涉及源文件

  • 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/
打赏
  • 微信
  • 支付宝

评论