Skip to content

命令路由 (commands.ts)

commands.ts (~754 行) 是 Claude Code 的命令中枢,管理 70+ 个斜杠命令(含内部构建可达 100+)的导入、注册、分类与路由。

命令类型体系

Claude Code 定义了 3 种命令类型(由 CommandBase + 类型联合构成):

typescript
// 命令联合类型 (src/types/command.ts L207)
type Command = CommandBase & (PromptCommand | LocalCommand | LocalJSXCommand)

// 命令基础属性 (L169-L200)
interface CommandBase {
  name: string
  description: string
  aliases?: string[]
  isEnabled?: () => boolean
  isHidden?: boolean
  availability?: CommandAvailability[]
  hasUserSpecifiedDescription?: boolean
  isMcp?: boolean
  argumentHint?: string
  whenToUse?: string
  version?: string
  disableModelInvocation?: boolean
  userInvocable?: boolean
  loadedFrom?: 'commands_DEPRECATED' | 'skills' | 'plugin' | 'managed' | 'bundled' | 'mcp'
  kind?: 'workflow'
  immediate?: boolean
  isSensitive?: boolean
  userFacingName?: () => string
}

// 1. 本地命令 — 懒加载本地模块 (L88-L92)
interface LocalCommand {
  type: 'local'
  supportsNonInteractive: boolean
  load: () => Promise<LocalCommandModule>
}

// 2. 本地 JSX 命令 — 懒加载 JSX 组件模块 (L139-L149)
interface LocalJSXCommand {
  type: 'local-jsx'
  load: () => Promise<LocalJSXCommandModule>
}

// 3. 提示命令 — 发送给 AI 模型的技能 (L24-L52)
interface PromptCommand {
  type: 'prompt'
  progressMessage: string
  contentLength: number
  argNames?: string[]
  allowedTools?: string[]
  model?: string
  source: SettingSource | 'builtin' | 'mcp' | 'plugin' | 'bundled'
  pluginInfo?: { pluginManifest: PluginManifest; repository: string }
  disableNonInteractive?: boolean
  hooks?: HooksSettings
  skillRoot?: string
  context?: 'inline' | 'fork'
  agent?: string
  effort?: EffortValue
  paths?: string[]
  getPromptForCommand(args: string, context: ToolUseContext): Promise<ContentBlockParam[]>
}

注意

文档中曾提到 ResumeEntrypoint 类型,实际代码中 ResumeEntrypoint 是一个字面量联合类型('cli_flag' | 'slash_command_picker' | ...),而非独立的命令类型。

命令导入清单

commands.ts 通过记忆化函数返回 ~73 个基础命令 + 条件命令:

会话管理命令

命令类型文件功能
/initlocalcommands/init.ts项目初始化、CLAUDE.md 创建
/resumelocal-jsxcommands/resume/会话恢复浏览器
/sessionlocal-jsxcommands/session/会话 QR 码 + URL
/branchlocalcommands/branch/工作目录分支
/clearlocalcommands/clear/清除会话
/exitlocalcommands/exit/退出程序
/compactlocalcommands/compact/手动会话压缩

代码操作命令

命令类型文件功能
/commitpromptcommands/commit.tsGit 提交
/commit-push-prpromptcommands/commit-push-pr.ts提交→推送→PR 全流程
/reviewpromptcommands/review.ts代码审查
/security-reviewpromptcommands/security-review.ts安全审查
/difflocal-jsxcommands/diff/差异查看器
/pr_commentslocal-jsxcommands/pr_comments/PR 评论

配置命令

命令类型文件功能
/configlocal-jsxcommands/config/设置编辑器
/permissionslocal-jsxcommands/permissions/权限规则管理
/hookslocal-jsxcommands/hooks/钩子配置
/modellocal-jsxcommands/model/模型选择器
/themelocal-jsxcommands/theme/主题选择
/vimlocalcommands/vim/Vim 模式切换
/voicelocalcommands/voice/语音模式切换

工具命令

命令类型文件功能
/helplocal-jsxcommands/help/帮助文档
/exportlocal-jsxcommands/export/导出会话
/copylocalcommands/copy/复制到剪贴板
/statslocalcommands/stats/会话统计
/costlocalcommands/cost/成本查看
/doctorlocal-jsxcommands/doctor/健康诊断
/memorylocalcommands/memory/内存管理

高级/实验命令

命令类型条件功能
/agentslocal-jsxAgent 管理界面
/taskslocal-jsx后台任务管理
/bridgelocal-jsxBRIDGE_MODEBridge 双向控制
/mcplocalMCP 服务器管理
/ultraplanpromptULTRAPLAN超级计划模式
/statuslineprompt状态栏设置
/insightslocal会话分析洞察

命令过滤系统

3 种过滤列表

typescript
// 远程模式安全命令 (L619, Set<Command>, 17个)
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 模式安全命令 (L651, Set<Command>, 6个)
const BRIDGE_SAFE_COMMANDS: Set<Command> = new Set([
  compact, clear, cost, summary, releaseNotes, files
])

// 内部专用命令 (L225, 31个, process.env.USER_TYPE === 'ant')
const INTERNAL_ONLY_COMMANDS: Command[] = [
  backfillSessions, breakCache, bughunter, commit, commitPushPr,
  ctx_viz, goodClaude, issue, initVerifiers, mockLimits,
  bridgeKick, version, resetLimits, resetLimitsNonInteractive,
  onboarding, share, summary, teleport, antTrace, perfIssue,
  env, oauthRefresh, debugToolCall, agentsPlatform, autofixPr,
  // + 条件性: forceSnip, ultraplan, subscribePr
]

命令可用性检查

typescript
function meetsAvailabilityRequirement(command: Command): boolean {
  // 根据 command.availability 检查
  // 处理 'claude-ai' 和 'console' 两种可用性类型
  // 认证状态可能在会话中间改变,所以不做 memoize
}

命令发现流程

typescript
// loadAllCommands() — 记忆化加载所有命令源(需要 cwd 参数)
const loadAllCommands = memoize(async (cwd: string): Promise<Command[]> => {
  // 合并所有命令源: 内置 + 技能 + 插件 + 工作流 + bundled
})

// getCommands() — 获取过滤后的最终命令列表
async function getCommands(cwd: string): Promise<Command[]> {
  const commands = await loadAllCommands(cwd)

  // 1. 过滤 meetsAvailabilityRequirement
  // 2. 过滤 isCommandEnabled
  // 3. 处理动态技能去重
  return filteredCommands
}

// 相关辅助函数
getMcpSkillCommands()        // L545 — 过滤 MCP prompt 类型命令
getSkillToolCommands()       // L563 — 获取所有可调用的 prompt 命令
getSlashCommandToolSkills()  // L584 — 过滤为纯技能
isBridgeSafeCommand()        // L676 — 检查 Bridge 模式安全性

命令执行上下文

注意

代码中不存在 CommandContext 接口。LocalJSXCommandContextsrc/types/command.ts)是最接近的类型,用于本地JSX命令。各命令使用解构的参数对象(字段因命令而异)。

clearConversation() — 会话清除流程

会话清除是最复杂的命令操作之一。实际函数接受解构参数对象 { setMessages, readFileState, discoveredSkillNames, loadedNestedMemoryPaths, getAppState, setAppState, setConversationId, ... },而非 CommandContext

主要步骤:

  1. 运行 SessionEnd hooks(executeSessionEndHooks('clear', ...)
  2. 计算需保留的后台任务 agentId
  3. 清除消息(setMessages(() => [])
  4. 清除会话缓存(clearSessionCaches(preservedAgentIds)
  5. 重置工作目录、文件状态、技能缓存
  6. 清理 AppState(保留后台任务,清除前台任务)
  7. 重新生成 session ID(regenerateSessionId({ setCurrentAsParent: true })
  8. 保存 worktree 状态
  9. 运行 SessionStart hooks(processSessionStartHooks('clear')

clearSessionCaches() — 20+ 缓存清除

contextCache          → 清除
commandsCache         → 清除
skillsCache           → 清除
promptCacheBreaker    → 清除
imagePathCache        → 清除
sessionIngressCache   → 清除
lspDiagnosticsCache   → 清除
completionCache       → 清除
toolSchemaCache       → 清除
mcpOutputStorage      → 清除
growthBookCache       → 清除
fileReadCache         → 清除
fileStateCache        → 清除
readFileTimestamps    → 清除
systemPromptSections  → 重置
...