Claude Code Command System 深度分析
分析源码路径:
/home/sujie/dev/github/claude-code-source-snap/claude-code/src/分析日期: 2026-04-01 命令总数: 101 个 (src/commands/ 目录下文件/子目录)
1. 系统架构总览
Command System 是 Claude Code CLI 的核心交互层,用户通过 /command [args] 触发功能。系统由三层构成:
- 命令定义层 (
src/types/command.ts) — 类型定义 - 命令注册层 (
src/commands.ts) — 注册表、过滤、查找 - 命令分派层 (
src/utils/processUserInput/processSlashCommand.tsx) — 解析、路由、执行
用户输入 "/commit"
│
▼
parseSlashCommand() ──→ { commandName: "commit", args: "", isMcp: false }
│
▼
findCommand() ──→ Command 对象
│
▼
┌─────────────────────────────────────────────┐
│ switch (command.type): │
│ ├─ "prompt" → getPromptForCommand() │
│ │ 注入到 conversation context │
│ ├─ "local" → mod.call(args, ctx) │
│ │ 返回文本/compaction/skip │
│ └─ "local-jsx" → mod.call(onDone, ctx) │
│ 渲染 React/Ink UI 组件 │
└─────────────────────────────────────────────┘
2. 命令类型定义
文件: src/types/command.ts:1-216
2.1 Command 联合类型
// src/types/command.ts:205-206
export type Command = CommandBase &
(PromptCommand | LocalCommand | LocalJSXCommand)
2.2 CommandBase — 公共属性
// src/types/command.ts:175-203
export type CommandBase = {
availability?: CommandAvailability[] // 'claude-ai' | 'console'
description: string
hasUserSpecifiedDescription?: boolean
isEnabled?: () => boolean // 动态启用检查
isHidden?: boolean // 从 typeahead/help 隐藏
name: string
aliases?: string[]
argumentHint?: string // 参数提示文本
whenToUse?: string // 使用场景描述 (来自 Skill spec)
version?: string
disableModelInvocation?: boolean // 是否禁止模型调用
userInvocable?: boolean // 用户能否通过 /name 触发
loadedFrom?: 'commands_DEPRECATED' | 'skills' | 'plugin' | 'managed' | 'bundled' | 'mcp'
kind?: 'workflow' // workflow 类型标记
immediate?: boolean // 是否绕过队列立即执行
isSensitive?: boolean // 参数是否脱敏显示
userFacingName?: () => string // 用户可见名称覆盖
}
2.3 三种命令类型
PromptCommand — 注入给模型的提示型命令
// src/types/command.ts:25-57
export type PromptCommand = {
type: 'prompt'
progressMessage: string
contentLength: number // 字符数 (token 估算用)
argNames?: string[]
allowedTools?: string[] // 限定可用工具
model?: string // 模型覆盖
source: SettingSource | 'builtin' | 'mcp' | 'plugin' | 'bundled'
pluginInfo?: { pluginManifest: PluginManifest; repository: string }
disableNonInteractive?: boolean
hooks?: HooksSettings // 技能注册的 hooks
skillRoot?: string // 技能资源根目录
context?: 'inline' | 'fork' // inline = 当前会话; fork = 子 agent
agent?: string // fork 模式下的 agent 类型
effort?: EffortValue // 执行力度
paths?: string[] // glob 模式限定适用文件
getPromptForCommand(
args: string,
context: ToolUseContext,
): Promise<ContentBlockParam[]> // 返回 prompt 内容块
}
特点:getPromptForCommand() 返回 ContentBlockParam[],直接注入到会话上下文中,模型看到这些内容并据此执行操作。支持 allowedTools 白名单限制工具调用。
LocalCommand — 本地执行型命令
// src/types/command.ts:74-78
type LocalCommand = {
type: 'local'
supportsNonInteractive: boolean
load: () => Promise<LocalCommandModule> // 懒加载
}
// src/types/command.ts:62-66
export type LocalCommandCall = (
args: string,
context: LocalJSXCommandContext,
) => Promise<LocalCommandResult>
// src/types/command.ts:16-23
export type LocalCommandResult =
| { type: 'text'; value: string }
| { type: 'compact'; compactionResult: CompactionResult; displayText?: string }
| { type: 'skip' }
特点:直接执行函数返回结果,不经过模型。三种返回类型:text(显示文本)、compact(上下文压缩)、skip(不显示)。
LocalJSXCommand — 渲染 UI 型命令
// src/types/command.ts:144-152
type LocalJSXCommand = {
type: 'local-jsx'
load: () => Promise<LocalJSXCommandModule> // 懒加载
}
// src/types/command.ts:131-135
export type LocalJSXCommandCall = (
onDone: LocalJSXCommandOnDone, // 完成回调
context: ToolUseContext & LocalJSXCommandContext,
args: string,
) => Promise<React.ReactNode> // 返回 Ink UI 组件
特点:返回 React/Ink 渲染的交互式 UI(选择器、表单、面板等)。通过 onDone 回调通知完成,支持 display: 'skip'|'system'|'user' 控制显示方式。
3. 命令注册与加载
3.1 内置命令注册表
文件: src/commands.ts:258-346
const COMMANDS = memoize((): Command[] => [
addDir, advisor, agents, branch, btw, chrome, clear, color,
compact, config, copy, desktop, context, contextNonInteractive,
cost, diff, doctor, effort, exit, fast, files, heapDump, help,
ide, init, keybindings, installGitHubApp, installSlackApp, mcp,
memory, mobile, model, outputStyle, remoteEnv, plugin,
pr_comments, releaseNotes, reloadPlugins, rename, resume,
session, skills, stats, status, statusline, stickers, tag,
theme, feedback, review, ultrareview, rewind, securityReview,
terminalSetup, upgrade, extraUsage, extraUsageNonInteractive,
rateLimitOptions, usage, usageReport, vim,
// 条件命令:
...(webCmd ? [webCmd] : []),
...(forkCmd ? [forkCmd] : []),
...(buddy ? [buddy] : []),
// ... 更多 feature-gated 命令
// 内部命令 (仅 ant/employee):
...(process.env.USER_TYPE === 'ant' ? INTERNAL_ONLY_COMMANDS : []),
])
3.2 五层命令源合并
// src/commands.ts:449-469
const loadAllCommands = memoize(async (cwd: string): Promise<Command[]> => {
const [
{ skillDirCommands, pluginSkills, bundledSkills, builtinPluginSkills },
pluginCommands,
workflowCommands,
] = await Promise.all([
getSkills(cwd), // .claude/skills/ + plugin skills
getPluginCommands(), // plugin manifest 命令
getWorkflowCommands(cwd), // workflow 脚本
])
return [
...bundledSkills, // 1. 内置 bundled skills
...builtinPluginSkills, // 2. 内置 plugin skills
...skillDirCommands, // 3. .claude/skills/ 目录
...workflowCommands, // 4. workflow 脚本
...pluginCommands, // 5. plugin 命令
...pluginSkills, // plugin skills
...COMMANDS(), // 6. 内置命令 (最后,优先级最低)
]
})
3.3 可见性过滤
// src/commands.ts:476-517
export async function getCommands(cwd: string): Promise<Command[]> {
const allCommands = await loadAllCommands(cwd)
const baseCommands = allCommands.filter(
_ => meetsAvailabilityRequirement(_) && isCommandEnabled(_),
)
// 动态 skills 插入...
}
两层过滤:
meetsAvailabilityRequirement()— 检查 auth/provider 环境(claude-ai/console)isCommandEnabled()— 检查isEnabled()回调(feature flags、env vars、platform)
4. 命令分派机制
文件: src/utils/processUserInput/processSlashCommand.tsx
4.1 解析
// src/utils/slashCommandParsing.ts:25-59
export function parseSlashCommand(input: string): ParsedSlashCommand | null {
const withoutSlash = input.trim().slice(1)
const words = withoutSlash.split(' ')
let commandName = words[0]
let isMcp = false
let argsStartIndex = 1
// MCP 命令检测: "/mcp:tool (MCP) arg1"
if (words.length > 1 && words[1] === '(MCP)') {
commandName = commandName + ' (MCP)'
isMcp = true
argsStartIndex = 2
}
return { commandName, args: words.slice(argsStartIndex).join(' '), isMcp }
}
4.2 分派逻辑
// src/utils/processUserInput/processSlashCommand.tsx:549-748
switch (command.type) {
case 'local-jsx':
return new Promise<SlashCommandResult>(resolve => {
const onDone = (result?, options?) => {
// 处理 display: 'skip'|'system'|'user'
// 处理 shouldQuery, metaMessages, nextInput
}
command.load().then(mod =>
mod.call(onDone, { ...context, canUseTool }, args)
).then(jsx => {
// 渲染 Ink UI 组件
setToolJSX({ jsx, shouldHidePromptInput: true, ... })
})
})
case 'local':
const mod = await command.load()
const result = await mod.call(args, context)
// result.type === 'text' → createCommandInputMessage(...)
// result.type === 'compact' → buildPostCompactMessages(...)
// result.type === 'skip' → return empty messages
case 'prompt':
if (command.context === 'fork') {
return await executeForkedSlashCommand(...) // 子 agent 执行
}
return await getMessagesForPromptSlashCommand(...) // inline 注入
}
4.3 Fork 模式 (子 agent 执行)
文件: src/utils/processUserInput/processSlashCommand.tsx:62-120
对于设置了 context: 'fork' 的 prompt 命令,系统会启动一个独立的子 agent 执行:
async function executeForkedSlashCommand(command, args, context, ...) {
const agentId = createAgentId()
const { skillContent, modifiedGetAppState, baseAgent, promptMessages } =
await prepareForkedCommandContext(command, args, context)
// KAIROS 模式: 后台执行,不阻塞用户输入
if (feature('KAIROS') && kairosEnabled) {
void runAgent(...) // fire-and-forget
return { messages: [], shouldQuery: false, ... }
}
// 普通模式: 同步执行,显示进度
const result = await runAgent(agentDefinition, ...)
return { messages: resultMessages, shouldQuery: true, ... }
}
5. 命令分类详解
5.1 Git / PR 相关 (9 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/commit | prompt | commands/commit.ts | 创建 git commit |
/commit-push-pr | prompt | commands/commit-push-pr.ts | commit + push + PR |
/review | prompt | commands/review.ts | PR review |
/ultrareview | local-jsx | commands/review.ts | 远程 bug 审查 |
/security-review | prompt | commands/security-review.ts | 安全审查 |
/autofix-pr | prompt | commands/autofix-pr/ | 自动修复 PR |
/branch | local-jsx | commands/branch/ | 分支管理 |
/pr_comments | prompt | commands/pr_comments/ | PR 评论 |
/issue | prompt | commands/issue/ | Issue 管理 |
5.2 配置 / 设置 (13 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/config | local-jsx | commands/config/ | 配置面板 (别名: /settings) |
/model | local-jsx | commands/model/ | 切换 AI 模型 |
/theme | local-jsx | commands/theme/ | 终端主题 |
/color | local-jsx | commands/color/ | Agent 颜色 |
/vim | local-jsx | commands/vim/ | Vim 模式 |
/keybindings | local-jsx | commands/keybindings/ | 快捷键管理 |
/permissions | local-jsx | commands/permissions/ | 工具权限规则 (别名: /allowed-tools) |
/privacy-settings | local-jsx | commands/privacy-settings/ | 隐私设置 |
/effort | local-jsx | commands/effort/ | 执行力度 |
/fast | local-jsx | commands/fast/ | 快速模式 |
/statusline | local-jsx | commands/statusline.tsx | 状态栏 |
/output-style | local-jsx | commands/output-style/ | 输出样式 |
/sandbox-toggle | local-jsx | commands/sandbox-toggle/ | Sandbox 开关 |
5.3 会话管理 (6 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/session | local-jsx | commands/session/ | 远程会话 URL/QR (别名: /remote) |
/resume | local-jsx | commands/resume/ | 恢复历史会话 (别名: /continue) |
/clear | local | commands/clear/ | 清空对话 (别名: /reset, /new) |
/compact | local | commands/compact/ | 上下文压缩 |
/exit | local-jsx | commands/exit/ | 退出 REPL (别名: /quit) |
/rewind | local-jsx | commands/rewind/ | 回退对话 |
5.4 MCP 管理 (1 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/mcp | local-jsx | commands/mcp/ | MCP 服务器管理 |
5.5 诊断 / 监控 (7 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/doctor | local-jsx | commands/doctor/ | 安装诊断 |
/usage | prompt | commands/usage/ | 使用情况 |
/cost | local-jsx | commands/cost/ | 会话费用 |
/stats | local-jsx | commands/stats/ | 统计 |
/extra-usage | local-jsx | commands/extra-usage/ | 额外使用情况 |
/rate-limit-options | local-jsx | commands/rate-limit-options/ | 速率限制选项 |
/insights | prompt | commands/insights.ts | 会话分析报告 |
5.6 开发工具 (6 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/ide | local-jsx | commands/ide/ | IDE 扩展管理 |
/desktop | local-jsx | commands/desktop/ | 桌面应用 |
/terminal-setup | local-jsx | commands/terminalSetup/ | 终端配置 |
/hooks | local-jsx | commands/hooks/ | Hooks 管理 |
/files | local-jsx | commands/files/ | 跟踪文件列表 |
/tag | local-jsx | commands/tag/ | 标签管理 |
5.7 代码 / 上下文 (5 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/context | local-jsx | commands/context/ | 上下文信息 |
/ctx_viz | local-jsx | commands/ctx_viz/ | 上下文可视化 |
/diff | local-jsx | commands/diff/ | Diff 查看 |
/copy | local-jsx | commands/copy/ | 复制最后消息 |
/export | local-jsx | commands/export/ | 导出对话 |
5.8 认证 / 平台 (7 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/login | local-jsx | commands/login/ | 登录 (非 3P 服务) |
/logout | local-jsx | commands/logout/ | 登出 |
/upgrade | local-jsx | commands/upgrade/ | 升级订阅 |
/agents | local-jsx | commands/agents/ | Agent 管理 |
/mobile | local-jsx | commands/mobile/ | 移动端 QR 码 |
/install-github-app | local-jsx | commands/install-github-app/ | GitHub App 安装 |
/install-slack-app | local-jsx | commands/install-slack-app/ | Slack App 安装 |
5.9 初始化 / 项目 (4 个)
| 命令 | 类型 | 文件 | 说明 |
|---|---|---|---|
/init | prompt | commands/init.ts | 生成 CLAUDE.md |
/memory | local-jsx | commands/memory/ | 编辑记忆文件 |
/skills | local-jsx | commands/skills/ | 技能管理 |
/plugin | local-jsx | commands/plugin/ | 插件管理 |
5.10 其他 / 杂项 (约 42 个)
包含: /advisor, /btw, /chrome, /heapdump, /stickers, /help, /status, /version, /feedback, /summary, /release-notes, /onboarding, /teleport, /rename, /plan, /thinkback, /passes, /tasks, /permissions, /privacy-settings, /env, /remote-env, /oauth-refresh, /debug-tool-call, /bughunter, /perf-issue, /ant-trace, 等。
6. 代表性命令实现分析
6.1 /commit — Prompt 命令典型
文件: src/commands/commit.ts:1-92
const ALLOWED_TOOLS = [
'Bash(git add:*)',
'Bash(git status:*)',
'Bash(git commit:*)',
]
const command = {
type: 'prompt',
name: 'commit',
description: 'Create a git commit',
allowedTools: ALLOWED_TOOLS,
contentLength: 0,
progressMessage: 'creating commit',
source: 'builtin',
async getPromptForCommand(_args, context) {
const promptContent = getPromptContent()
// executeShellCommandsInPrompt 处理 !`cmd` 语法
const finalContent = await executeShellCommandsInPrompt(
promptContent,
{
...context,
getAppState() {
const appState = context.getAppState()
return {
...appState,
toolPermissionContext: {
...appState.toolPermissionContext,
alwaysAllowRules: {
...appState.toolPermissionContext.alwaysAllowRules,
command: ALLOWED_TOOLS, // 自动允许 git 操作
},
},
}
},
},
'/commit',
)
return [{ type: 'text', text: finalContent }]
},
}
关键设计:
- prompt 模板包含
!\git status`语法 —executeShellCommandsInPrompt()` 在返回前先执行 shell 命令并替换为结果 allowedTools限制模型只能使用git add,git status,git commit- 通过修改
alwaysAllowRules实现自动授权,用户无需手动批准 git 操作
6.2 /review — Prompt 命令 + UltraReview JSX
文件: src/commands/review.ts:1-57
const LOCAL_REVIEW_PROMPT = (args: string) => `
You are an expert code reviewer. Follow these steps:
1. If no PR number is provided, run \`gh pr list\`
2. If a PR number is provided, run \`gh pr view <number>\`
3. Run \`gh pr diff <number>\` to get the diff
4. Analyze and provide thorough code review...
PR number: ${args}
`
const review: Command = {
type: 'prompt',
name: 'review',
description: 'Review a pull request',
progressMessage: 'reviewing pull request',
source: 'builtin',
async getPromptForCommand(args) {
return [{ type: 'text', text: LOCAL_REVIEW_PROMPT(args) }]
},
}
const ultrareview: Command = {
type: 'local-jsx',
name: 'ultrareview',
description: '~10–20 min · Finds and verifies bugs...',
isEnabled: () => isUltrareviewEnabled(),
load: () => import('./review/ultrareviewCommand.js'),
}
关键设计:
- 同一功能两个入口:
/review是本地 prompt 型(用ghCLI),/ultrareview是 remote JSX 型(用 CCR) - review 的 prompt 依赖模型的
ghCLI 调用能力,不预设allowedTools - ultrareview 通过
isEnabled()按条件显示
6.3 /compact — Local 命令 + compaction 返回
文件: src/commands/compact/index.ts, src/commands/compact/compact.ts
// index.ts
const compact = {
type: 'local',
name: 'compact',
description: 'Clear conversation history but keep a summary...',
isEnabled: () => !isEnvTruthy(process.env.DISABLE_COMPACT),
supportsNonInteractive: true,
argumentHint: '<optional custom summarization instructions>',
load: () => import('./compact.js'),
}
// compact.ts — call 函数核心逻辑
export const call: LocalCommandCall = async (args, context) => {
const customInstructions = args.trim()
// 1. 尝试 session memory compaction (无自定义指令时)
if (!customInstructions) {
const sessionMemoryResult = await trySessionMemoryCompaction(messages, agentId)
if (sessionMemoryResult) {
return { type: 'compact', compactionResult: sessionMemoryResult }
}
}
// 2. 尝试 microcompact (短上下文)
if (shouldMicrocompact) {
const result = await microcompactMessages(...)
if (result) return { type: 'compact', compactionResult: result }
}
// 3. 完整 compaction (调用模型总结)
const result = await compactConversation(messages, customInstructions, ...)
return { type: 'compact', compactionResult: result }
}
关键设计:
- 三级压缩策略:session memory → microcompact → full compact
- 返回
{ type: 'compact' }触发分派层的 compaction 消息重建逻辑 supportsNonInteractive: true支持 SDK /-p模式下的非交互调用- 分派层处理 compaction 结果时调用
resetMicrocompactState()清理状态
6.4 /config — Local-JSX 命令典型
文件: src/commands/config/index.ts
const config = {
aliases: ['settings'],
type: 'local-jsx',
name: 'config',
description: 'Open config panel',
load: () => import('./config.js'),
} satisfies Command
关键设计:
- 懒加载:
load()返回Promise<LocalJSXCommandModule>,只有用户输入/config时才加载 UI 组件 - JSX 组件通过
onDone回调通知完成 - 别名机制:
/settings等价于/config
6.5 /mcp — Local-JSX + immediate
文件: src/commands/mcp/index.ts
const mcp = {
type: 'local-jsx',
name: 'mcp',
description: 'Manage MCP servers',
immediate: true, // 立即执行,不排队
argumentHint: '[enable|disable [server-name]]',
load: () => import('./mcp.js'),
} satisfies Command
关键设计:
immediate: true绕过命令队列,在 REPL 队列阻塞时也能执行argumentHint在自动补全中显示参数提示
6.6 /init — Prompt 命令 + feature-gated 内容
文件: src/commands/init.ts:226-256
const command = {
type: 'prompt',
name: 'init',
get description() {
return feature('NEW_INIT') && isAntOrFlag
? 'Initialize new CLAUDE.md file(s) and optional skills/hooks...'
: 'Initialize a new CLAUDE.md file with codebase documentation'
},
contentLength: 0,
progressMessage: 'analyzing your codebase',
source: 'builtin',
async getPromptForCommand() {
maybeMarkProjectOnboardingComplete()
return [{
type: 'text',
text: feature('NEW_INIT') && isAntOrFlag
? NEW_INIT_PROMPT // 8 阶段完整流程 (~200 行 prompt)
: OLD_INIT_PROMPT, // 简单 prompt
}]
},
}
关键设计:
- 动态
description— 根据 feature flag 显示不同描述 - 两个 prompt 版本:旧版是简单分析,新版是 8 阶段交互式工作流
- NEW_INIT_PROMPT 包含
AskUserQuestion工具调用,实现交互式配置
6.7 /resume — Local-JSX + 别名
文件: src/commands/resume/index.ts
const resume: Command = {
type: 'local-jsx',
name: 'resume',
description: 'Resume a previous conversation',
aliases: ['continue'],
argumentHint: '[conversation id or search term]',
load: () => import('./resume.js'),
}
关键设计:
- 别名
/continue等价于/resume argumentHint支持传入会话 ID 或搜索关键词- JSX 组件会渲染会话选择列表
6.8 /doctor — 条件禁用
文件: src/commands/doctor/index.ts
const doctor: Command = {
name: 'doctor',
description: 'Diagnose and verify your Claude Code installation and settings',
isEnabled: () => !isEnvTruthy(process.env.DISABLE_DOCTOR_COMMAND),
type: 'local-jsx',
load: () => import('./doctor.js'),
}
关键设计:
- 通过
isEnabled()+ 环境变量实现开关 - 懒加载重型诊断 UI(
doctor.tsx包含大量检查逻辑)
7. 命令与工具的交互模式
7.1 Prompt 命令 → 模型 → 工具
用户: /commit
│
├─ getPromptForCommand() → { text: "基于当前 git status 创建 commit..." }
├─ 注入到 conversation context
├─ 模型看到 prompt + git status 输出
├─ 模型调用 Bash("git add ...") → Bash("git commit ...")
└─ commit 完成
Prompt 命令通过 allowedTools 控制模型可用的工具范围。commit 命令只允许 git add/status/commit。
7.2 SkillTool — 模型主动调用命令
文件: src/tools/SkillTool/SkillTool.ts
模型可以通过 SkillTool 主动调用 prompt 类型的命令(skills):
// SkillTool.ts 中获取可用技能
const allCommands = await getCommands(cwd)
return allCommands.filter(cmd =>
cmd.type === 'prompt' &&
!cmd.disableModelInvocation &&
cmd.source !== 'builtin' &&
(cmd.loadedFrom === 'skills' || cmd.loadedFrom === 'bundled' || ...)
)
这意味着:
- 模型可以在对话中发现并使用
.claude/skills/下的技能 disableModelInvocation: true的技能只能用户手动触发userInvocable: false的技能只能模型通过 SkillTool 调用
7.3 安全边界
远程安全命令集 (REMOTE_SAFE_COMMANDS):
// src/commands.ts:619-637
export const REMOTE_SAFE_COMMANDS: Set<Command> = new Set([
session, exit, clear, help, theme, color, vim, cost,
usage, copy, btw, feedback, plan, keybindings, statusline,
stickers, mobile,
])
Bridge 安全命令集 (BRIDGE_SAFE_COMMANDS):
// src/commands.ts:651-660
export const BRIDGE_SAFE_COMMANDS: Set<Command> = new Set([
compact, clear, cost, summary, releaseNotes, files,
])
三类型安全判定:
local-jsx→ 始终阻塞 (渲染 Ink UI)prompt→ 始终放行 (展开为文本)local→ 需要显式列入BRIDGE_SAFE_COMMANDS
8. 参数解析
8.1 解析层
参数解析极其简单 — parseSlashCommand() 只做空格分割:
/commit fix: auth bug
→ { commandName: "commit", args: "fix: auth bug", isMcp: false }
/mcp:tool (MCP) arg1 arg2
→ { commandName: "mcp:tool (MCP)", args: "arg1 arg2", isMcp: true }
8.2 使用层
参数由各命令自行处理:
- prompt 命令:
args作为getPromptForCommand(args, context)的参数,拼接到 prompt 模板中 - local 命令:
args作为call(args, context)的参数,在命令内部解析 - local-jsx 命令:
args作为call(onDone, context, args)的参数,由 JSX 组件处理
8.3 argumentHint
仅用于 UI 显示(自动补全提示),不参与解析:
argumentHint: '[conversation id or search term]' // /resume
argumentHint: '[enable|disable [server-name]]' // /mcp
argumentHint: '<optional custom summarization instructions>' // /compact
9. 命令发现与扩展
9.1 来源优先级 (低 → 高)
- 内置命令 (
COMMANDS()) — 最后加载,优先级最低 - Plugin 命令 (
getPluginCommands()) - Workflow 命令 (
getWorkflowCommands()) - Skills 目录 (
getSkillDirCommands()—.claude/skills/) - Bundled Skills (
getBundledSkills()) - Builtin Plugin Skills (
getBuiltinPluginSkillCommands()) - 动态 Skills (
getDynamicSkills()) — 运行时发现
同名命令先到先得,后加载的被忽略。
9.2 缓存管理
// src/commands.ts:523-539
export function clearCommandMemoizationCaches(): void {
loadAllCommands.cache?.clear?.()
getSkillToolCommands.cache?.clear?.()
getSlashCommandToolSkills.cache?.clear?.()
clearSkillIndexCache?.()
}
使用 lodash memoize 缓存,按 cwd 分键。auth 状态变化(如 /login)会触发重新过滤但不重新加载。
9.3 Plugin 命令
通过 loadPluginCommands.ts 从 plugin manifest 加载。Plugin 命令带有 pluginInfo,在 UI 中显示来源:
// src/commands.ts:728-753
export function formatDescriptionWithSource(cmd: Command): string {
if (cmd.source === 'plugin') {
const pluginName = cmd.pluginInfo?.pluginManifest.name
if (pluginName) return `(${pluginName}) ${cmd.description}`
}
if (cmd.source === 'bundled') return `${cmd.description} (bundled)`
// ...
}
10. 关键设计模式总结
| 模式 | 用途 | 示例 |
|---|---|---|
| 懒加载 | load() 延迟加载重型模块 | 所有 local / local-jsx 命令 |
| Feature Gate | feature('XXX') + 条件导入 | proactive, brief, bridge, voice |
| Env Gate | isEnabled() + 环境变量 | /doctor, /compact, /session |
| Auth Gate | availability 字段 | 限定 claude-ai/console 用户 |
| Shell Expansion | !\cmd`` 在 prompt 中执行 | /commit 中的 git 状态 |
| Fork 模式 | context: 'fork' 子 agent 执行 | 复杂 skills |
| Immediate | immediate: true 绕过队列 | /mcp, /exit, /status |
| Memoize | lodash memoize 缓存加载结果 | COMMANDS(), loadAllCommands() |
| Lazy Shim | 重型模块延迟 import | /insights (113KB) |
附录: 完整命令列表 (101 个)
以下按字母排序列出 src/commands/ 中的所有条目:
add-dir/ advisor.ts agents/ ant-trace/
autofix-pr/ backfill-sessions/ branch/ break-cache/
bridge/ bridge-kick.ts brief.ts btw/
bughunter/ chrome/ clear/ color/
commit-push-pr.ts commit.ts compact/ config/
context/ copy/ cost/ createMovedToPluginCommand.ts
ctx_viz/ debug-tool-call/ desktop/ diff/
doctor/ effort/ env/ exit/
export/ extra-usage/ fast/ feedback/
files/ good-claude/ heapdump/ help/
hooks/ ide/ init-verifiers.ts init.ts
insights.ts install-github-app/ install-slack-app/ install.tsx
issue/ keybindings/ login/ logout/
mcp/ memory/ mobile/ mock-limits/
model/ oauth-refresh/ onboarding/ output-style/
passes/ perf-issue/ permissions/ plan/
plugin/ pr_comments/ privacy-settings/ rate-limit-options/
release-notes/ reload-plugins/ remote-env/ remote-setup/
rename/ reset-limits/ resume/ review/
review.ts rewind/ sandbox-toggle/ security-review.ts
session/ share/ skills/ stats/
status/ statusline.tsx stickers/ summary/
tag/ tasks/ teleport/ terminalSetup/
theme/ thinkback/ thinkback-play/ ultraplan.tsx
upgrade/ usage/ version.ts vim/
voice/