02-Command 斜杠命令设计
Command 斜杠命令设计
学习目标
本章将掌握 Claude Code 斜杠命令的设计规范,通过官方插件中的命令实例,掌握:
- Frontmatter 协议的标准字段
- 工具权限约束的精确语法
- 三种交互式设计模式
- 隐蔽命令的使用场景
前置知识
项目实践
Frontmatter 协议
每个 Command .md 文件以 YAML frontmatter 开头:
---description: "命令的一句话描述"argument-hint: "参数提示文本"allowed-tools: ["Bash", "Read", "Write"]hide-from-slash-command-tool: "true"---标准字段说明:
| 字段 | 必需 | 类型 | 用途 |
|---|---|---|---|
description | 是 | string | 命令描述,出现在 / 命令列表中 |
argument-hint | 否 | string | 参数提示文本,出现在命令输入框中 |
allowed-tools | 否 | array | 允许使用的工具列表 |
hide-from-slash-command-tool | 否 | boolean | 是否从通用命令列表中隐藏 |
工具权限约束
allowed-tools 使用精确匹配语法:
# 允许所有 Bash 命令allowed-tools: ["Bash"]
# 仅允许执行插件内的特定脚本allowed-tools: ["Bash(${CLAUDE_PLUGIN_ROOT}/scripts/setup-ralph-loop.sh:*)"]
# 允许多个精确匹配allowed-tools: [ "Bash(test -f .claude/ralph-loop.local.md:*)", "Bash(rm .claude/ralph-loop.local.md)", "Read(.claude/ralph-loop.local.md)"]匹配语法:ToolName(pattern:pattern) 中,第一个 pattern 匹配工具参数,第二个匹配工具输出。使用 * 作为通配符。
三种交互式设计模式
模式 1:单步确认(agent-sdk-dev)
/new-sdk-app 命令逐个提问,每次一个问题:
- 语言选择(TypeScript / Python)
- 项目名称(如果未通过参数提供)
- Agent 类型
- 起始模板
- 包管理器偏好
每个问题等待用户回答后才继续下一个。
模式 2:多阶段工作流(plugin-dev)
/plugin-dev:create-plugin 定义了 8 个阶段,每个阶段加载相应的 Skill:
- Discovery → 加载
plugin-structureSkill - Component Planning → 加载
plugin-structureSkill - Detailed Design → 加载所有相关 Skills
- Structure Creation → 创建目录
- Component Implementation → 按需加载 Skills
- Validation → 启动
plugin-validator和skill-reviewerAgents - Testing → 本地测试
- Documentation → 完善文档
模式 3:参数解析(hookify)
/hookify 支持两种模式:
- 有参数:
/hookify Don't use console.log→ 直接从指令创建规则 - 无参数:
/hookify→ 启动conversation-analyzerAgent,自动分析对话历史
隐蔽命令
使用 hide-from-slash-command-tool: "true" 隐藏内部命令:
/cancel-ralph:取消 Ralph 循环(仅在需要时使用)/hookify:configure:配置已有规则(通常通过/hookify:list进入)
这些命令不在 / 列表中显示,但可以通过完整名称调用。
$ARGUMENTS 变量
用户输入的参数通过 $ARGUMENTS 变量传递给命令体:
---description: "My command"argument-hint: "Required argument"---
The user provided: $ARGUMENTS
Based on this argument, do the following...陷阱与对策
| 陷阱 | 表现 | 对策 |
|---|---|---|
allowed-tools 过窄 | 命令执行中需要但未被允许的工具会失败 | 测试命令的完整执行路径,确保所有必需工具都被允许 |
| Frontmatter 字段拼写错误 | 字段被静默忽略 | 使用 plugin-validator Agent 验证 |
argument-hint 与实际参数不匹配 | 用户不知道如何传参 | 在命令体中明确说明参数格式 |
设计取舍
为什么 Command 默认使用 Opus 模型?
Command 通常编排复杂工作流,需要深度推理来理解用户意图、协调多个步骤、处理边界情况。Opus 的更强推理能力确保命令正确执行。
为什么有的命令隐藏?
隐藏命令通常是辅助性的,只在特定场景下需要。如果所有内部命令都显示在列表中,会污染用户的命令选择体验。
参考来源
- Claude Code Plugin Development 文档
- 源码:
plugins/*/commands/*.md目录下所有命令定义