# 斜杠命令

所有界面共用一个注册表、一种文件格式、一个菜单。别的项目怎么做：[参考实现](https://fzkuji.github.io/OpenProgram/docs/reference/design/cli/slash-commands-references.zh.html)。

## 来源层

| 层，优先级从低到高 | 来源 | 作者 | 重新加载 |
| --- | --- | --- | --- |
| L0 builtin | 源码 | OpenProgram | 重启 |
| L1 plugin | `~/.openprogram/plugins/<pkg>/...` 下的 `entrypoints.commands` | 插件作者 | 插件重载 |
| L2 mcp | 已连接服务器的 `list_prompts()` | MCP 服务器 | 会话重连、`/api/commands?refresh=mcp` |
| L3 skill | `~/.openprogram/skills/<name>/SKILL.md` | skill 作者、用户 | watcher |
| L4 user | `~/.openprogram/commands/**/*.md` | 当前用户 | watcher |
| L5 project | `<cwd>/.openprogram/commands/**/*.md` | 项目维护者 | watcher |

- 同名时后面的层胜出。被覆盖的命令仍可用 `/(plugin)name`、`/(mcp:linear)name`、`/(skill)name`、`/(user)name`、`/(project)name` 调用。
- 同一来源内，相同 realpath 只加载一次。
- 菜单里的冲突：主条目标 `(+2 more)`；⇥ 切换来源。
- 来源标签始终由 loader 写入；frontmatter 不能自称。

## 文件格式

```
---
name: review              # 默认：文件名
aliases: [r, rev]
description: 按团队规范审查当前 diff
when-to-use: |
  用户想对未提交的修改做一轮风格和 bug 审查时使用。
hidden: false
arguments:
  - name: target
    description: 文件路径或目录；默认当前 diff
    required: false
argument-hint: "[target]"
type: prompt
context: inline
agent: general-purpose    # 仅 context: fork 时生效
model: inherit
effort: medium
allowed-tools: [Read, Grep]
paths: ["src/**/*.{ts,tsx}", "**/*.py"]
requires:
  any-bins: [git]
  config: [openai_api_key]
hooks:
  PreToolUse: ...
version: 1.0.0
---
请审查 {{target}} 的代码。

补充上下文：
$ARGUMENTS

最近提交：
!`git log -5 --oneline`

当前 diff：
@`git diff --staged`
```

| 字段 | 类型 | 默认 | 含义 | 来自 |
| --- | --- | --- | --- | --- |
| `name` | string | 文件名 | 命令名 | 通用 |
| `aliases` | string[] | [] | 同样受覆盖规则约束 | claude-code |
| `description` | string | "" | 一行，显示在菜单 | 通用 |
| `when-to-use` | string | "" | 详情面板 | claude-code |
| `hidden` | bool | false | 不进补全，仍可触发 | claude-code |
| `arguments` | list | [] | 位置参数声明。数字名被拒绝：与 `$0` 冲突 | opencode |
| `argument-hint` | string | 自动生成 | 菜单里的灰色提示 | claude-code |
| `type` | enum | prompt | 执行模式 | claude-code |
| `context` | enum | inline | `inline` 或 `fork` | claude-code |
| `agent` | string | general-purpose | fork 时的 `subagent_type` | claude-code |
| `model` | string | inherit | `inherit`、`opus`、`sonnet`、`haiku` 或完整 id | claude-code |
| `effort` | enum、int | inherit | `low`、`medium`、`high`、`max` 或数字 | claude-code |
| `allowed-tools` | string[] | inherit | fork 模式的工具白名单 | claude-code |
| `paths` | string[] | null | 按 glob 条件激活 | claude-code |
| `requires` | object | {} | 前置条件 | openclaw |
| `hooks` | object | {} | 临时 hook | claude-code |
| `version` | semver | null | 用于升级提示 | claude-code |
| `user-invocable` | bool | true | false 时只有模型能调用 | claude-code |
| `shell` | enum | inherit | `bash` 或 `powershell`，用于 `!` 块 | claude-code |

未声明的字段进入 `extras` 字典，不报错。

## 正文模板

| 语法 | 含义 | 来自 |
| --- | --- | --- |
| `$ARGUMENTS` | 命令后的全部文本 | claude-code |
| `$0`..`$9` | 第 N 个位置参数；缺失为空 | opencode |
| `{{name}}` | `arguments:` 声明的命名参数 | opencode |
| `${OPENPROGRAM_COMMAND_DIR}` | 命令文件所在目录 | claude-code |
| `${OPENPROGRAM_SESSION_ID}` | 当前会话 id | claude-code |
| `${OPENPROGRAM_CWD}` | 当前工作目录 | OpenProgram |
| `` !`cmd` `` 或 ```` ```! ```` 代码块 | 在宿主 shell 执行，stdout 拼入；2 秒超时 | claude-code、hermes |
| `` @`path` `` | 拼入文件内容 | OpenProgram |
| `<<command-name>>name<</command-name>>` | 展开另一个命令，最多 3 层 | OpenProgram |

参数按 shell 规则切分，失败时按空白切分。

## 执行

| 模式 | 效果 |
| --- | --- |
| `type: prompt`（默认） | 渲染后的模板作为用户消息，走正常 agent 循环 |
| `type: local` | 调用宿主的 handler；用于 `/compact`、`/clear`、`/new`、`/web`、`/model` 等内建命令 |
| `type: local-jsx` | 接口预留给服务端推送的结构化事件 |
| `context: inline`（默认） | 渲染结果进入当前会话 |
| `context: fork` | 作为一次 `agent(prompt=...)` 子 agent 运行：`agent` 决定 `subagent_type`，`allowed-tools` 决定工具。最终消息作为命令结果，主上下文保持干净 |

MCP prompt 是 `prompt` 和 `inline`，在其服务器上渲染。

## 条件和 hook

条件不满足时命令从补全中隐藏。手动输入会再次检查，并给出明确错误。

| 字段 | 通过条件 |
| --- | --- |
| `paths` | 会话最近接触的文件或用 `@file` 指明的文件匹配 |
| `requires.any-bins` | `which` 至少找到一个；否则提示 “needs `git` / `rg`, please install first” |
| `requires.config` | profile 配置了该键 |
| `requires.platform` | 匹配，如 `[darwin, linux]` |

```
hooks:
  PreToolUse:
    - matcher: Bash
      command: !`echo "blocked by /review" >&2; exit 2`
  PostToolUse:
    - matcher: Edit
      handler: built-in:auto-stage
```

只在该命令执行期间生效。事件名复用 `runtime/events/registry.py`。`!` 块：stdout 进日志，退出码决定放行或拒绝。`built-in:<id>`：已注册的 handler。schema 先固定，日后启用不算破坏性变更。

## 菜单

```
/review                  按团队规范审查当前 diff                           [project]
  [target]

/review (project)                                                 ⇥ 详情面板
─────────────────────────────────────
按团队规范审查当前 diff

Arguments: [target] (optional)
Mode: inline · model: inherit · effort: medium
Source: .openprogram/commands/review.md
```

按来源分组（project、user、skill、mcp、plugin、builtin），组内按字母序。模糊搜索 name、description、when-to-use。

## 安全

| 输入 | 规则 |
| --- | --- |
| 命令文件 | `realpath` 后必须落在所扫描的受信根内（`~/.openprogram/`、`$cwd/.openprogram/`） |
| YAML | `yaml.safe_load` |
| Glob | `fnmatch`；禁用 `..` 和绝对路径 |
| `!` 块 | 除非 `commands.allow_shell: true` 否则关闭；MCP 上下文中关闭；2 秒超时；禁 fork 炸弹；stdout 上限 64 KB |
| `@` 引用 | 在受信根内，或 `--allow-file <abs>` |

## 实现

| openprogram/runtime/commands/ 下的文件 | 作用 |
| --- | --- |
| `loader.py` | 扫描用户和项目目录 |
| `frontmatter.py` | YAML 和字段解析 |
| `template.py` | 正文渲染 |
| `registry.py` | 合并表、冲突索引、MCP 同步 |
| `dispatch.py` | 解析并渲染；纯函数，结果由宿主执行 |
| `_plugin_adapter.py`、`_skill_adapter.py` | 把插件和 skill 投影到注册表 |

1. **用户输入** `/review xxx`
2. **`dispatch.invoke(text, session_id, cwd)`** `registry.resolve`，再渲染模板
3. **按 kind 返回** `prompt`：宿主发送文本。`local`：运行 handler。`mcp_prompt`：从服务器获取。

| 端点 | 返回 |
| --- | --- |
| `GET /api/commands` | 合并列表；`?source=`、`?include_hidden=` |
| `GET /api/commands/{name}` | 单条，含正文 |
| `POST /api/commands/invoke` | 请求体 `{text, session_id, cwd}`：解析并渲染，不发送 |
| `POST /api/commands/reload` | 强制重扫 |
| `GET /api/commands/conflicts` | 同名多来源 |
| `GET /api/plugins/commands` | 旧的仅插件列表 |

| 前端 | 读取注册表的方式 |
| --- | --- |
| Web composer（`use-slash-menu.ts`） | `/api/commands`，`/api/plugins/commands` 作回退；渲染文本落入输入框 |
| Rich REPL（`repl/handlers.py`） | `_handle_slash` 和 `dispatch.invoke`。`register_repl_builtins` 用标记字符串注册本地动作，`_LOCAL_ACTIONS` 映射回去。存在性、别名和 `/help` 读 `list_all()` |
| Ink TUI（`apps/cli/src/commands/registry.ts`） | 只硬编码 TUI 本地动作。`GET /api/commands` 供补全、Ctrl+K 和 `/help`；`POST /api/commands/invoke` 展开 |

**有意不做**

| 来源 | 设计 | 原因 |
| --- | --- | --- |
| openclaw | i18n（`descriptionLocalizations`） | 只有英文和简体中文 |
| openclaw | provider 路由（Slack、Mattermost） | 单宿主 |
| hermes | `platforms` 过滤 | 由 `requires.platform` 取代 |
| hermes | 134 条提示注入检测 | 属于独立扫描器 |
| claude-code | `local-jsx` React 组件 | Web UI 用结构化事件；CLI 没有 |
| pi-mono | 纯硬编码 | 反例 |

**版本**

- `version` 和来源仓库的 git hash（如有）一起存入注册表。
- L0 跟随 OpenProgram 版本。L1 走插件自动更新。L3 走 skill 发现差异。L4、L5 由用户编写，不自动更新。
- 从参考项目发现的新设计作为字段加到这里。frontmatter 是稳定契约：上游改名时，`frontmatter.py` 里的别名让新旧写法都能解析。

## 实现状态

| 状态 | 项目 |
| --- | --- |
| 已实现 | 六层来源、frontmatter 解析、`$ARGUMENTS`、位置、命名和 `OPENPROGRAM_*` 替换、覆盖和 `(source)name`、冲突表、API、三个前端 |
| 已解析但未生效 | `paths`、`requires`、`hooks`、`allowed-tools` 限制、`context: fork`（`invoke` 返回，但不运行子 agent） |
| 未实现 | `!` 和 `@` 替换、`<<command-name>>` 展开、`commands.allow_shell`、watcher、`local-jsx`、⇥ 来源切换和详情面板、字段别名表、版本和 git hash 存储 |

skill 以 `inline` 注册，并设好 `agent: general-purpose`，日后切到 fork 时落在正确的池。
