protocol-slash-commands.test.ts 13 KB

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