跳转到内容

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"
---

标准字段说明

字段必需类型用途
descriptionstring命令描述,出现在 / 命令列表中
argument-hintstring参数提示文本,出现在命令输入框中
allowed-toolsarray允许使用的工具列表
hide-from-slash-command-toolboolean是否从通用命令列表中隐藏

工具权限约束

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 命令逐个提问,每次一个问题:

  1. 语言选择(TypeScript / Python)
  2. 项目名称(如果未通过参数提供)
  3. Agent 类型
  4. 起始模板
  5. 包管理器偏好

每个问题等待用户回答后才继续下一个。

模式 2:多阶段工作流(plugin-dev)

/plugin-dev:create-plugin 定义了 8 个阶段,每个阶段加载相应的 Skill:

  1. Discovery → 加载 plugin-structure Skill
  2. Component Planning → 加载 plugin-structure Skill
  3. Detailed Design → 加载所有相关 Skills
  4. Structure Creation → 创建目录
  5. Component Implementation → 按需加载 Skills
  6. Validation → 启动 plugin-validatorskill-reviewer Agents
  7. Testing → 本地测试
  8. Documentation → 完善文档

模式 3:参数解析(hookify)

/hookify 支持两种模式:

  • 有参数/hookify Don't use console.log → 直接从指令创建规则
  • 无参数/hookify → 启动 conversation-analyzer Agent,自动分析对话历史

隐蔽命令

使用 hide-from-slash-command-tool: "true" 隐藏内部命令:

  • /cancel-ralph:取消 Ralph 循环(仅在需要时使用)
  • /hookify:configure:配置已有规则(通常通过 /hookify:list 进入)

这些命令不在 / 列表中显示,但可以通过完整名称调用。

$ARGUMENTS 变量

用户输入的参数通过 $ARGUMENTS 变量传递给命令体:

command-name.md
---
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 的更强推理能力确保命令正确执行。

为什么有的命令隐藏?

隐藏命令通常是辅助性的,只在特定场景下需要。如果所有内部命令都显示在列表中,会污染用户的命令选择体验。

参考来源