protocol-slash-commands.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import type { ExecutionPort, ExecutionResult, SessionId } from "@zcode/contracts";
  6. import { resolveZCodeBuiltinPromptCommand } from "../src/builtin-prompt-command.js";
  7. import { resolveZCodeCustomCommandPrompt } from "../src/custom-command-prompt.js";
  8. import { listProtocolSlashCommands } from "../src/zcode-protocol/slash-commands.js";
  9. describe("protocol slash command surface", () => {
  10. it("returns app-supported builtins plus agent-discovered custom commands", async () => {
  11. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-protocol-slash-"));
  12. const workspace = join(tempRoot, "workspace");
  13. const home = join(tempRoot, "home");
  14. const projectCommands = join(workspace, ".zcode", "commands");
  15. const userCommands = join(home, ".zcode", "commands");
  16. try {
  17. await mkdir(projectCommands, { recursive: true });
  18. await mkdir(userCommands, { recursive: true });
  19. await writeCommand(projectCommands, "review", "Project review", "Project body.");
  20. await writeCommand(userCommands, "review", "User review", "User body.");
  21. await writeCommand(userCommands, "ship", "Ship changes", "Ship $ARGUMENTS.", [
  22. "argument-hint: [target]",
  23. ]);
  24. await writeCommand(userCommands, "model", "Reserved custom model", "Should be hidden.");
  25. await writeCommand(userCommands, "plan", "Reserved custom plan", "Should be hidden.");
  26. await writeCommand(userCommands, "offline", "Noninteractive disabled", "Hidden.", [
  27. "disable-noninteractive: true",
  28. ]);
  29. // 同名自定义命令不得顶替内置 `/workflow`(保留名):目录里只剩内置那一行。
  30. await writeCommand(userCommands, "workflow", "Shadowing workflow", "Should be hidden.");
  31. const commands = await listProtocolSlashCommands({
  32. env: { ZCODE_ENV: "test" },
  33. homeDirectory: home,
  34. skipUserConfig: true,
  35. workingDirectory: workspace,
  36. });
  37. expect(commands.map((command) => ({ name: command.name, source: command.source }))).toEqual([
  38. { name: "goal", source: "builtin" },
  39. // `/workflow` 是随 CLI 编译的内置 prompt 命令(builtin-workflow-command.ts)。App `/` 面板
  40. // 按本目录顺序展示,产品要求工作流紧随目标之后(docs/ui/chat-composer-action-menu.md
  41. // 「工作流入口」),顺序由 APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES 决定。
  42. { name: "workflow", source: "builtin" },
  43. { name: "compact", source: "builtin" },
  44. { name: "init", source: "builtin" },
  45. { name: "plan", source: "builtin" },
  46. { name: "review", source: "custom" },
  47. { name: "ship", source: "custom" },
  48. ]);
  49. expect(commands.find((command) => command.name === "review")?.description).toBe(
  50. "User review",
  51. );
  52. expect(commands.find((command) => command.name === "ship")?.inputHint).toBe(
  53. "/ship [target]",
  54. );
  55. expect(commands.some((command) => command.name === "model")).toBe(false);
  56. expect(commands.filter((command) => command.name === "workflow")).toHaveLength(1);
  57. expect(commands.find((command) => command.name === "workflow")?.inputHint).toBe(
  58. "/workflow [what the workflow should accomplish]",
  59. );
  60. expect(commands.filter((command) => command.name === "plan")).toHaveLength(1);
  61. expect(commands.find((command) => command.name === "plan")?.description).toBe(
  62. "Switch to Plan mode and optionally send a task.",
  63. );
  64. expect(commands.some((command) => command.name === "offline")).toBe(false);
  65. } finally {
  66. await rm(tempRoot, { force: true, recursive: true });
  67. }
  68. });
  69. it("expands prompt custom commands without taking over reserved builtins", async () => {
  70. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-custom-command-prompt-"));
  71. const workspace = join(tempRoot, "workspace");
  72. const home = join(tempRoot, "home");
  73. const userCommands = join(home, ".zcode", "commands");
  74. try {
  75. await mkdir(workspace, { recursive: true });
  76. await mkdir(userCommands, { recursive: true });
  77. await writeCommand(userCommands, "review", "Review changes", "Review $ARGUMENTS.");
  78. await writeCommand(userCommands, "init", "Custom init", "Should not expand.");
  79. await writeCommand(userCommands, "model", "Reserved model", "Should not expand.");
  80. const options = {
  81. env: { ZCODE_ENV: "test" },
  82. homeDirectory: home,
  83. skipUserConfig: true,
  84. workingDirectory: workspace,
  85. };
  86. const prompt = await resolveZCodeCustomCommandPrompt("/review src packages", options);
  87. expect(prompt).toContain("Run custom command /review.");
  88. expect(prompt).toContain("Command source: user/zcode.");
  89. expect(prompt).toContain("Review src packages.");
  90. await expect(resolveZCodeCustomCommandPrompt("/model glm-5", options)).resolves.toBe(
  91. undefined,
  92. );
  93. await expect(resolveZCodeCustomCommandPrompt("/init", options)).resolves.toBe(undefined);
  94. await expect(resolveZCodeCustomCommandPrompt("please /review", options)).resolves.toBe(
  95. undefined,
  96. );
  97. } finally {
  98. await rm(tempRoot, { force: true, recursive: true });
  99. }
  100. });
  101. // DWG-03:灰度关闭时 `/workflow` 不得展开。目录侧已经剃掉了它,但用户仍可手打命令名,
  102. // 两条路径必须给出同一个结论;同时 `workflow` 是保留名,自定义命令解析对它一律不展开,
  103. // 用户或插件的同名命令既顶替不了内置语义,也绕不过灰度门。
  104. it("expands builtin /workflow through the builtin resolver only, gated by the feature flag", async () => {
  105. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-builtin-workflow-"));
  106. const workspace = join(tempRoot, "workspace");
  107. const home = join(tempRoot, "home");
  108. const userCommands = join(home, ".zcode", "commands");
  109. try {
  110. await mkdir(workspace, { recursive: true });
  111. await mkdir(userCommands, { recursive: true });
  112. await writeCommand(userCommands, "workflow", "Shadowing workflow", "Should not expand.");
  113. const options = {
  114. env: { ZCODE_ENV: "test" },
  115. homeDirectory: home,
  116. skipUserConfig: true,
  117. workingDirectory: workspace,
  118. };
  119. const expanded = resolveZCodeBuiltinPromptCommand("/workflow ship it", {
  120. dynamicWorkflowEnabled: true,
  121. workingDirectory: workspace,
  122. });
  123. expect(expanded).toContain("Required skills: `dynamic-workflows`.");
  124. expect(expanded).toContain("ship it");
  125. expect(expanded).not.toContain("Should not expand.");
  126. // 缺席(TUI / headless)等于开启;显式 false 才挡下。
  127. expect(
  128. resolveZCodeBuiltinPromptCommand("/workflow ship it", { workingDirectory: workspace }),
  129. ).toContain("ship it");
  130. expect(
  131. resolveZCodeBuiltinPromptCommand("/workflow ship it", {
  132. dynamicWorkflowEnabled: false,
  133. workingDirectory: workspace,
  134. }),
  135. ).toBe(undefined);
  136. await expect(resolveZCodeCustomCommandPrompt("/workflow ship it", options)).resolves.toBe(
  137. undefined,
  138. );
  139. } finally {
  140. await rm(tempRoot, { force: true, recursive: true });
  141. }
  142. });
  143. it("expands builtin /init into the workspace AGENTS.md prompt", async () => {
  144. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-builtin-init-"));
  145. const workspace = join(tempRoot, "workspace");
  146. try {
  147. await mkdir(workspace, { recursive: true });
  148. const prompt = resolveZCodeBuiltinPromptCommand("/init include pnpm scripts", {
  149. workingDirectory: workspace,
  150. });
  151. expect(prompt).toContain("built-in /init command");
  152. expect(prompt).toContain("AGENTS.md");
  153. expect(prompt).toContain(join(workspace, "AGENTS.md"));
  154. expect(prompt).toContain(join(workspace, ".zcode", "AGENTS.md"));
  155. expect(prompt).toContain(join(workspace, ".agents", "AGENTS.md"));
  156. expect(prompt).toContain("they already have an instructions file");
  157. expect(prompt).not.toContain("Do not create CLAUDE.md or AGNENTS.md");
  158. expect(prompt).toContain("include pnpm scripts");
  159. expect(resolveZCodeBuiltinPromptCommand("/review", { workingDirectory: workspace })).toBe(
  160. undefined,
  161. );
  162. expect(resolveZCodeBuiltinPromptCommand("please /init", { workingDirectory: workspace })).toBe(
  163. undefined,
  164. );
  165. } finally {
  166. await rm(tempRoot, { force: true, recursive: true });
  167. }
  168. });
  169. it("runs shell expansion for plugin commands with plugin and session variables", async () => {
  170. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-plugin-command-shell-"));
  171. const workspace = join(tempRoot, "workspace");
  172. const pluginRoot = join(tempRoot, "ralph-loop");
  173. const commandsRoot = join(pluginRoot, "commands");
  174. const pluginDataRoot = join(tempRoot, "plugins");
  175. const configPath = join(tempRoot, "config.json");
  176. const sessionId = "sess_shell_expansion" as SessionId;
  177. let capturedRequest: Parameters<ExecutionPort["run"]>[0] | undefined;
  178. const executionPort: ExecutionPort = {
  179. async run(request) {
  180. capturedRequest = request;
  181. return createExecutionResult("ralph setup output");
  182. },
  183. };
  184. try {
  185. await mkdir(commandsRoot, { recursive: true });
  186. await mkdir(join(pluginRoot, ".claude-plugin"), { recursive: true });
  187. await writeFile(
  188. join(pluginRoot, ".claude-plugin", "plugin.json"),
  189. JSON.stringify({ name: "ralph-loop", version: "1.0.0" }),
  190. );
  191. await writeCommand(
  192. commandsRoot,
  193. "ralph-loop",
  194. "Start Ralph",
  195. [
  196. "Before",
  197. "```!",
  198. 'echo "${CLAUDE_PLUGIN_ROOT}/scripts/setup-ralph-loop.sh" "$ARGUMENTS"',
  199. "```",
  200. "After",
  201. ].join("\n"),
  202. );
  203. await writeFile(
  204. configPath,
  205. JSON.stringify({
  206. plugins: {
  207. dirs: [pluginRoot],
  208. enabled: true,
  209. },
  210. storage: {
  211. dir: pluginDataRoot,
  212. },
  213. }),
  214. );
  215. const prompt = await resolveZCodeCustomCommandPrompt("/ralph-loop build demo", {
  216. env: { ZCODE_ENV: "test" },
  217. executionPort,
  218. projectConfigPath: configPath,
  219. sessionId,
  220. skipUserConfig: true,
  221. workingDirectory: workspace,
  222. });
  223. expect(prompt).toContain("ralph setup output");
  224. expect(prompt).not.toContain("```!");
  225. expect(capturedRequest?.command).toMatchObject({
  226. command: 'echo "${CLAUDE_PLUGIN_ROOT}/scripts/setup-ralph-loop.sh" "build demo"',
  227. mode: "shell",
  228. });
  229. expect(capturedRequest?.cwd).toBe(workspace);
  230. expect(capturedRequest?.env?.set).toMatchObject({
  231. CLAUDE_CODE_SESSION_ID: sessionId,
  232. CLAUDE_PLUGIN_ROOT: pluginRoot,
  233. CLAUDE_PROJECT_DIR: workspace,
  234. CLAUDE_SESSION_ID: sessionId,
  235. ZCODE_PLUGIN_ROOT: pluginRoot,
  236. ZCODE_PROJECT_DIR: workspace,
  237. ZCODE_SESSION_ID: sessionId,
  238. });
  239. } finally {
  240. await rm(tempRoot, { force: true, recursive: true });
  241. }
  242. });
  243. it("fails shell-expanded custom commands that request unavailable contexts", async () => {
  244. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-command-shell-missing-context-"));
  245. const workspace = join(tempRoot, "workspace");
  246. const home = join(tempRoot, "home");
  247. const userCommands = join(home, ".zcode", "commands");
  248. let executionCalled = false;
  249. const executionPort: ExecutionPort = {
  250. async run() {
  251. executionCalled = true;
  252. return createExecutionResult("should not run");
  253. },
  254. };
  255. try {
  256. await mkdir(userCommands, { recursive: true });
  257. await writeCommand(
  258. userCommands,
  259. "skill-context",
  260. "Needs skill context",
  261. ['```!', 'echo "${CLAUDE_SKILL_DIR}"', "```"].join("\n"),
  262. );
  263. await writeCommand(
  264. userCommands,
  265. "session-context",
  266. "Needs session context",
  267. ['```!', 'echo "${CLAUDE_SESSION_ID}"', "```"].join("\n"),
  268. );
  269. const options = {
  270. env: { ZCODE_ENV: "test" },
  271. executionPort,
  272. homeDirectory: home,
  273. skipUserConfig: true,
  274. workingDirectory: workspace,
  275. };
  276. await expect(resolveZCodeCustomCommandPrompt("/skill-context", options)).rejects.toThrow(
  277. "Custom command /skill-context variable requires a skill context: CLAUDE_SKILL_DIR",
  278. );
  279. await expect(resolveZCodeCustomCommandPrompt("/session-context", options)).rejects.toThrow(
  280. "Custom command /session-context variable requires a runtime session context: CLAUDE_SESSION_ID",
  281. );
  282. expect(executionCalled).toBe(false);
  283. } finally {
  284. await rm(tempRoot, { force: true, recursive: true });
  285. }
  286. });
  287. });
  288. async function writeCommand(
  289. directory: string,
  290. name: string,
  291. description: string,
  292. body: string,
  293. extraFrontmatter: string[] = [],
  294. ): Promise<void> {
  295. await writeFile(
  296. join(directory, `${name}.md`),
  297. ["---", `description: ${description}`, ...extraFrontmatter, "---", "", body].join("\n"),
  298. );
  299. }
  300. function createExecutionResult(stdout: string): ExecutionResult {
  301. const now = new Date();
  302. return {
  303. status: "completed",
  304. exitCode: 0,
  305. stdout: { text: stdout, bytes: stdout.length, truncated: false },
  306. stderr: { text: "", bytes: 0, truncated: false },
  307. durationMs: 1,
  308. timedOut: false,
  309. cancelled: false,
  310. startedAt: now,
  311. completedAt: now,
  312. };
  313. }