From 02f7f2465bea4118f1dd259bd1074be5e90173e1 Mon Sep 17 00:00:00 2001 From: Factor Date: Thu, 19 Nov 2026 20:29:44 +0100 Subject: [PATCH] feat: the / menu offers user, plugin and all built-in commands Co-Authored-By: Ovis Fast (Claude) --- .../mods/herdr-composer/catalog.js | 256 +++++++++++++++++- .../mods/herdr-composer/suggest.js | 6 +- tests/catalog.test.mjs | 186 +++++++++++++ 3 files changed, 439 insertions(+), 9 deletions(-) create mode 100644 tests/catalog.test.mjs diff --git a/herdr/herdr-composer/mods/herdr-composer/catalog.js b/herdr/herdr-composer/mods/herdr-composer/catalog.js index 06b5fb2..16abdde 100644 --- a/herdr/herdr-composer/mods/herdr-composer/catalog.js +++ b/herdr/herdr-composer/mods/herdr-composer/catalog.js @@ -17,7 +17,7 @@ // with nothing to show. An empty list without a failure means the catalog // was read and nothing fit. -import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, rank } from "./suggest.js"; +import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_PLUGIN, rank } from "./suggest.js"; import { decode } from "./powershell.js"; /** @@ -47,15 +47,61 @@ export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo p /** The same, for the files of an `@`. */ export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej."; -/** The built-in commands of the agents, the small list the design names. */ +/** + * The built-in commands of the agents. The list is kept by hand, in the + * alphabetical order: when a new version of Claude Code brings a command, + * add it here. + */ export const BUILTINS = { "claude-code": [ + { key: "add-dir", desc: "Dodaje katalog roboczy." }, + { key: "agents", desc: "Zarządza subagentami." }, + { key: "bashes", desc: "Pokazuje zadania w tle." }, + { key: "bug", desc: "Zgłasza błąd Claude Code." }, { key: "clear", desc: "Czyści historię rozmowy." }, - { key: "compact", desc: "Ścisza historię do podsumowania." }, - { key: "model", desc: "Wybiera model." }, - { key: "permissions", desc: "Ustawia uprawnienia narzędzi." }, + { key: "code-review", desc: "Przegląd zmian pod kątem błędów." }, + { key: "compact", desc: "Zwija historię do podsumowania." }, { key: "config", desc: "Otwiera ustawienia." }, + { key: "context", desc: "Pokazuje zużycie kontekstu." }, + { key: "cost", desc: "Pokazuje koszt i zużycie tokenów." }, + { key: "doctor", desc: "Sprawdza instalację Claude Code." }, + { key: "exit", desc: "Kończy sesję." }, + { key: "export", desc: "Eksportuje rozmowę." }, + { key: "fast", desc: "Przełącza tryb szybki." }, + { key: "feedback", desc: "Wysyła opinię o Claude Code." }, + { key: "fewer-permission-prompts", desc: "Dodaje bezpieczne komendy do listy dozwolonych." }, + { key: "help", desc: "Pomoc." }, + { key: "hooks", desc: "Zarządza hookami." }, + { key: "ide", desc: "Łączy z IDE." }, + { key: "init", desc: "Tworzy CLAUDE.md dla projektu." }, + { key: "install-github-app", desc: "Instaluje aplikację GitHub." }, + { key: "keybindings", desc: "Ustawia skróty klawiszowe." }, + { key: "login", desc: "Logowanie." }, + { key: "logout", desc: "Wylogowanie." }, + { key: "loop", desc: "Uruchamia polecenie cyklicznie." }, + { key: "mcp", desc: "Zarządza serwerami MCP." }, + { key: "memory", desc: "Edytuje pliki pamięci." }, + { key: "model", desc: "Wybiera model." }, + { key: "output-style", desc: "Ustawia styl odpowiedzi." }, + { key: "permissions", desc: "Ustawia uprawnienia narzędzi." }, + { key: "plugin", desc: "Zarządza pluginami." }, + { key: "pr-comments", desc: "Pokazuje komentarze PR." }, + { key: "privacy-settings", desc: "Ustawienia prywatności." }, + { key: "release-notes", desc: "Pokazuje informacje o wydaniu." }, { key: "resume", desc: "Wznawia wcześniejszą sesję." }, + { key: "review", desc: "Przegląd pull requesta." }, + { key: "rewind", desc: "Cofa rozmowę lub kod." }, + { key: "schedule", desc: "Planuje zadania w chmurze." }, + { key: "security-review", desc: "Przegląd bezpieczeństwa zmian." }, + { key: "simplify", desc: "Upraszcza zmieniony kod." }, + { key: "status", desc: "Pokazuje stan sesji." }, + { key: "statusline", desc: "Ustawia linię statusu." }, + { key: "terminal-setup", desc: "Konfiguruje terminal." }, + { key: "todos", desc: "Pokazuje listę zadań." }, + { key: "upgrade", desc: "Zmienia plan." }, + { key: "usage", desc: "Pokazuje limity użycia." }, + { key: "vim", desc: "Przełącza tryb vim." }, + { key: "workflows", desc: "Pokazuje przebieg workflow." }, ], codex: [ { key: "model", desc: "Wybiera model." }, @@ -81,6 +127,18 @@ const LIST_PS = "@(Get-ChildItem -Path '.claude/commands/*.md','.claude/skills/*/SKILL.md' -File -ErrorAction SilentlyContinue) " + "| ForEach-Object { Resolve-Path -Relative -LiteralPath $_.FullName }"; +/** + * The global listing with a POSIX shell: the arguments come in threes - the + * index of the spec, its kind (`file`, `md` or `skills`) and its path - and + * every file found is written as `indexpath`. + */ +const GLOBAL_SH = + 'while [ $# -ge 3 ]; do i=$1; k=$2; p=$3; shift 3; case "$k" in ' + + 'file) [ -f "$p" ] && printf \'%s\\t%s\\n\' "$i" "$p";; ' + + 'md) for f in "$p"/*.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' + + 'skills) for f in "$p"/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' + + "esac; done; exit 0"; + /** Reading one file with a POSIX shell. */ const READ_SH = 'cat -- "$1"'; @@ -107,7 +165,8 @@ export function retryDelay(attempt) { * * @param {string} cwd - the folder of the pane * @param {Exec} exec - * @param {{agent?:string, snippets?:object[], onReadError?:(error:Error) => void}} [options] + * @param {{agent?:string, snippets?:object[], global?:Item[], onReadError?:(error:Error) => void}} [options] + * `global`: the person's and the plugins' commands, read by `globalCommands` * @returns {Promise} */ export async function commands(cwd, exec, options = {}) { @@ -125,7 +184,147 @@ export async function commands(cwd, exec, options = {}) { else throw err; } - return [...builtins, ...project, ...snippets]; + const global = Array.isArray(options.global) ? options.global : []; + + // A name is offered once: the first source that has it wins. + const seen = new Set(); + const out = []; + for (const item of [...builtins, ...project, ...global, ...snippets]) { + if (seen.has(item.key)) continue; + seen.add(item.key); + out.push(item); + } + return out; +} + +/** + * The commands that live in the person's `~/.claude`: their own commands and + * skills, and those of the plugins that `settings.json` switches on. + * + * Reads the two JSON files and the `plugin.json` of every enabled plugin + * with `readText` (a missing or broken file is an empty source), lists the + * files in one `exec`, reads each of them with `readText`. A listing that + * fails goes to `onReadError` - without a handler the call rejects. + * + * @param {string} home - the person's home folder + * @param {Exec} exec + * @param {(path:string) => Promise} readText + * @param {{onReadError?:(error:Error) => void}} [options] + * @returns {Promise} + */ +export async function globalCommands(home, exec, readText, options = {}) { + const root = slashes(home).replace(/\/+$/, ""); + const claude = `${root}/.claude`; + + /** @type {{kind:"file"|"md"|"skills", path:string, plugin:string|null}[]} */ + const specs = [ + { kind: "md", path: `${claude}/commands`, plugin: null }, + { kind: "skills", path: `${claude}/skills`, plugin: null }, + ]; + + const settings = await readJson(readText, `${claude}/settings.json`); + const installed = await readJson(readText, `${claude}/plugins/installed_plugins.json`); + const enabled = settings && typeof settings.enabledPlugins === "object" ? settings.enabledPlugins : {}; + + for (const [id, on] of Object.entries(enabled ?? {})) { + if (on !== true) continue; + const entries = installed?.plugins?.[id]; + const installPath = Array.isArray(entries) ? entries[0]?.installPath : null; + if (typeof installPath !== "string" || installPath === "") continue; + + const base = slashes(installPath).replace(/\/+$/, ""); + const name = id.split("@")[0]; + const manifest = await readJson(readText, `${base}/.claude-plugin/plugin.json`); + specs.push(...pluginSpecs(base, name, manifest)); + } + + let listed = []; + try { + listed = await listFiles(exec, specs); + } catch (err) { + if (options.onReadError) options.onReadError(err); + else throw err; + return []; + } + + const items = []; + for (const { index, path } of listed) { + const spec = specs[index]; + if (!spec) continue; + const text = await readText(path); + if (text === null || text === undefined) continue; + + const { fields } = frontmatter(String(text)); + if (fields["user-invocable"] === "false") continue; + + const own = commandName(path); + const isSkill = path.toLowerCase().endsWith("/skill.md"); + const name = isSkill && fields.name ? fields.name : own; + if (!name) continue; + + const key = spec.plugin ? `${spec.plugin}:${name}` : name; + items.push({ + key, + desc: describe(text), + group: spec.plugin ? GROUP_PLUGIN : GROUP_USER, + insert: `/${key} `, + }); + } + return items; +} + +/** Backslashes of a Windows path become slashes. */ +function slashes(path) { + return String(path).replace(/\\/g, "/"); +} + +/** A JSON file, or `null` when it is missing or broken. */ +async function readJson(readText, path) { + try { + const text = await readText(path); + if (text === null || text === undefined) return null; + return JSON.parse(String(text).replace(/^\uFEFF/, "")); + } catch { + return null; + } +} + +/** + * Where a plugin keeps its commands. `skills` and `commands` of its + * `plugin.json` may be a list of paths (a skill's folder or a `.md` file), a + * folder to look through, or missing (the default folders). + */ +function pluginSpecs(base, plugin, manifest) { + const join = (rel) => `${base}/${String(rel).replace(/^\.\//, "").replace(/\/+$/, "")}`; + const out = []; + + const skills = manifest?.skills; + if (skills === undefined || skills === null) { + out.push({ kind: "skills", path: join("skills"), plugin }); + } else if (typeof skills === "string") { + out.push({ kind: "skills", path: join(skills), plugin }); + } else if (Array.isArray(skills)) { + for (const rel of skills) { + if (typeof rel !== "string") continue; + const path = join(rel); + out.push({ kind: "file", path: /\.md$/i.test(path) ? path : `${path}/SKILL.md`, plugin }); + } + } + + const cmds = manifest?.commands; + if (cmds === undefined || cmds === null) { + out.push({ kind: "md", path: join("commands"), plugin }); + } else if (typeof cmds === "string") { + const path = join(cmds); + out.push({ kind: /\.md$/i.test(path) ? "file" : "md", path, plugin }); + } else if (Array.isArray(cmds)) { + for (const rel of cmds) { + if (typeof rel !== "string") continue; + const path = join(rel); + out.push({ kind: /\.md$/i.test(path) ? "file" : "md", path, plugin }); + } + } + return out; } /** @@ -227,6 +426,49 @@ async function listProjectFiles(cwd, exec) { throw new Error("nie udało się wczytać katalogu projektu"); } +/** + * The files of the global specs, listed by one `exec`: PowerShell first (the + * machine this mod is made for), a POSIX shell after it. The paths of the + * specs reach PowerShell only as Base64 of a JSON text (`decode`). + * + * @returns {Promise<{index:number, path:string}[]>} + */ +async function listFiles(exec, specs) { + const psScript = + "$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " + + `$specs = ConvertFrom-Json (${decode(JSON.stringify(specs.map((spec, i) => ({ i, k: spec.kind, p: spec.path }))))}); ` + + "foreach ($s in $specs) { $p = $s.p; " + + "if ($s.k -eq 'file') { if (Test-Path -LiteralPath $p -PathType Leaf) { \"$($s.i)`t$p\" } } " + + "elseif (Test-Path -LiteralPath $p -PathType Container) { " + + "if ($s.k -eq 'md') { Get-ChildItem -LiteralPath $p -Filter '*.md' -File | ForEach-Object { \"$($s.i)`t$($_.FullName)\" } } " + + "else { Get-ChildItem -LiteralPath $p -Directory | ForEach-Object { $f = Join-Path $_.FullName 'SKILL.md'; " + + "if (Test-Path -LiteralPath $f -PathType Leaf) { \"$($s.i)`t$f\" } } } } }"; + + const shArgs = ["-c", GLOBAL_SH, "catalog"]; + specs.forEach((spec, i) => shArgs.push(String(i), spec.kind, spec.path)); + + for (const [command, args] of [ + ["powershell", ["-NoProfile", "-Command", psScript]], + ["sh", shArgs], + ]) { + let result; + try { + result = await exec(command, args, {}); + } catch { + continue; + } + if (!result || result.code !== 0) continue; + + const found = []; + for (const line of String(result.stdout ?? "").split("\n")) { + const match = /^(\d+)\t(.+)$/.exec(line.replace(/\r$/, "")); + if (match) found.push({ index: Number(match[1]), path: slashes(match[2]).trim() }); + } + return found; + } + throw new Error("nie udało się wczytać katalogu globalnego"); +} + /** One listing, or `null` when the program is not there or it failed. */ async function tryList(exec, command, args, cwd, windowsPaths) { let result; diff --git a/herdr/herdr-composer/mods/herdr-composer/suggest.js b/herdr/herdr-composer/mods/herdr-composer/suggest.js index d5a5251..2bd249e 100644 --- a/herdr/herdr-composer/mods/herdr-composer/suggest.js +++ b/herdr/herdr-composer/mods/herdr-composer/suggest.js @@ -14,7 +14,7 @@ * @typedef {object} Item * @property {string} key - the name the needle is matched against * @property {string} desc - one line about the item - * @property {string} [group] - Wbudowane | Projekt | Użytkownik | Terminal + * @property {string} [group] - Wbudowane | Projekt | Użytkownik | Pluginy | Terminal * @property {string} insert - the text put into the field ("/review ") * @property {number} [uses] - how often the person picked the item */ @@ -25,11 +25,13 @@ export const GROUP_BUILTIN = "Wbudowane"; export const GROUP_PROJECT = "Projekt"; /** The person's own saved snippets. */ export const GROUP_USER = "Użytkownik"; +/** The commands of the plugins that are switched on. */ +export const GROUP_PLUGIN = "Pluginy"; /** The commands the terminal itself understands. */ export const GROUP_TERMINAL = "Terminal"; /** The groups, in the order the menu shows them. */ -export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_TERMINAL]; +export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_PLUGIN, GROUP_TERMINAL]; /** A name may start a word after one of these. */ const BOUNDARY = new Set([":", "-", "_", ".", "/"]); diff --git a/tests/catalog.test.mjs b/tests/catalog.test.mjs new file mode 100644 index 0000000..32a3d94 --- /dev/null +++ b/tests/catalog.test.mjs @@ -0,0 +1,186 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + BUILTINS, + commands, + globalCommands, +} from "../herdr/herdr-composer/mods/herdr-composer/catalog.js"; +import { + GROUPS, + GROUP_USER, + GROUP_PLUGIN, +} from "../herdr/herdr-composer/mods/herdr-composer/suggest.js"; + +const HOME = "C:/Users/Test"; + +/** + * A fake machine: `files` maps a path to its text. `exec` answers the POSIX + * listing of catalog.js (powershell is "not installed"), `readText` reads. + */ +function machine(files, { listError = false } = {}) { + const exec = async (command, args) => { + if (command !== "sh") throw new Error("not found"); + if (listError) return { code: 2, stdout: "", stderr: "boom" }; + const rest = args.slice(3); + const lines = []; + for (let i = 0; i + 2 < rest.length; i += 3) { + const [index, kind, path] = rest.slice(i, i + 3); + for (const file of Object.keys(files)) { + const name = file.slice(file.lastIndexOf("/") + 1); + const dir = file.slice(0, file.lastIndexOf("/")); + if (kind === "file" && file === path) lines.push(`${index}\t${file}`); + if (kind === "md" && dir === path && name.endsWith(".md")) lines.push(`${index}\t${file}`); + if (kind === "skills" && name === "SKILL.md" && dir.slice(0, dir.lastIndexOf("/")) === path) + lines.push(`${index}\t${file}`); + } + } + return { code: 0, stdout: lines.join("\n"), stderr: "" }; + }; + const readText = async (path) => files[path] ?? null; + return { exec, readText }; +} + +const skill = (name, extra = "") => `---\nname: ${name}\ndescription: Opis ${name}\n${extra}---\nTreść\n`; + +function plugins(enabled, installed) { + return { + [`${HOME}/.claude/settings.json`]: JSON.stringify({ enabledPlugins: enabled }), + [`${HOME}/.claude/plugins/installed_plugins.json`]: JSON.stringify({ + version: 2, + plugins: Object.fromEntries( + Object.entries(installed).map(([id, path]) => [id, [{ installPath: path }]]), + ), + }), + }; +} + +test("GROUPS has Pluginy right after Użytkownik", () => { + assert.equal(GROUPS[GROUPS.indexOf(GROUP_USER) + 1], "Pluginy"); + assert.equal(GROUP_PLUGIN, "Pluginy"); +}); + +test("claude-code builtins: the full list, unique keys", () => { + const keys = BUILTINS["claude-code"].map((item) => item.key); + for (const key of ["context", "help", "mcp", "rewind", "clear"]) assert.ok(keys.includes(key), key); + assert.equal(new Set(keys).size, keys.length); + assert.deepEqual(keys, [...keys].sort()); +}); + +test("globalCommands: an enabled plugin gives plugin:name (default skills dir)", async () => { + const dir = "C:/p/superpowers/7.0.2"; + const { exec, readText } = machine({ + ...plugins({ "superpowers@official": true }, { "superpowers@official": "C:\\p\\superpowers\\7.0.2" }), + [`${dir}/skills/brainstorming/SKILL.md`]: skill("brainstorming"), + }); + const items = await globalCommands(HOME, exec, readText); + assert.equal(items.length, 1); + assert.equal(items[0].key, "superpowers:brainstorming"); + assert.equal(items[0].group, GROUP_PLUGIN); + assert.equal(items[0].insert, "/superpowers:brainstorming "); + assert.equal(items[0].desc, "Opis brainstorming"); +}); + +test("globalCommands: disabled or unlisted plugin gives nothing", async () => { + const dir = "C:/p/a/1"; + const { exec, readText } = machine({ + ...plugins({ "a@m": false }, { "a@m": dir, "b@m": "C:/p/b/1" }), + [`${dir}/skills/x/SKILL.md`]: skill("x"), + ["C:/p/b/1/skills/y/SKILL.md"]: skill("y"), + }); + assert.deepEqual(await globalCommands(HOME, exec, readText), []); +}); + +test("globalCommands: plugin.json skills array takes only the named dirs", async () => { + const dir = "C:/p/mp/1"; + const { exec, readText } = machine({ + ...plugins({ "mp@m": true }, { "mp@m": dir }), + [`${dir}/.claude-plugin/plugin.json`]: JSON.stringify({ skills: ["./skills/eng/tdd"] }), + [`${dir}/skills/eng/tdd/SKILL.md`]: skill("tdd"), + [`${dir}/skills/eng/other/SKILL.md`]: skill("other"), + [`${dir}/skills/direct/SKILL.md`]: skill("direct"), + }); + const keys = (await globalCommands(HOME, exec, readText)).map((item) => item.key); + assert.deepEqual(keys, ["mp:tdd"]); +}); + +test("globalCommands: plugin commands dir and user-invocable false", async () => { + const dir = "C:/p/c/1"; + const { exec, readText } = machine({ + ...plugins({ "c@m": true }, { "c@m": dir }), + [`${dir}/commands/ship.md`]: "---\ndescription: Wysyła\n---\n", + [`${dir}/skills/hidden/SKILL.md`]: skill("hidden", "user-invocable: false\n"), + [`${dir}/skills/shown/SKILL.md`]: skill("shown"), + }); + const keys = (await globalCommands(HOME, exec, readText)).map((item) => item.key).sort(); + assert.deepEqual(keys, ["c:ship", "c:shown"]); +}); + +test("globalCommands: name: in the front matter wins over the folder name", async () => { + const { exec, readText } = machine({ + [`${HOME}/.claude/skills/folder/SKILL.md`]: skill("real-name"), + }); + const items = await globalCommands(HOME, exec, readText); + assert.deepEqual(items.map((item) => item.key), ["real-name"]); +}); + +test("globalCommands: a user command gives handoff in Użytkownik", async () => { + const { exec, readText } = machine({ + [`${HOME}/.claude/commands/handoff.md`]: "---\ndescription: Przekazanie\n---\n", + }); + const items = await globalCommands(HOME, exec, readText); + assert.equal(items.length, 1); + assert.equal(items[0].key, "handoff"); + assert.equal(items[0].group, GROUP_USER); + assert.equal(items[0].insert, "/handoff "); +}); + +test("globalCommands: no settings.json, broken json: user items only, no throw", async () => { + const none = machine({ [`${HOME}/.claude/commands/a.md`]: "x" }); + assert.deepEqual((await globalCommands(HOME, none.exec, none.readText)).map((i) => i.key), ["a"]); + + const broken = machine({ + [`${HOME}/.claude/settings.json`]: "{nope", + [`${HOME}/.claude/plugins/installed_plugins.json`]: "[[", + [`${HOME}/.claude/commands/a.md`]: "x", + }); + assert.deepEqual((await globalCommands(HOME, broken.exec, broken.readText)).map((i) => i.key), ["a"]); +}); + +test("globalCommands: a listing failure goes to onReadError, or throws", async () => { + const { exec, readText } = machine({}, { listError: true }); + const errors = []; + const items = await globalCommands(HOME, exec, readText, { onReadError: (err) => errors.push(err) }); + assert.deepEqual(items, []); + assert.equal(errors.length, 1); + await assert.rejects(() => globalCommands(HOME, exec, readText)); +}); + +test("paths with spaces and Polish letters are not put in the PowerShell script as text", async () => { + const home = "D:/Użytkownik Zażółć/x"; + let script = ""; + const exec = async (command, args) => { + if (command === "powershell") { + script = args[args.length - 1]; + return { code: 0, stdout: "", stderr: "" }; + } + throw new Error("no"); + }; + await globalCommands(home, exec, async () => null); + assert.ok(script.length > 0); + assert.ok(!script.includes("Zażółć")); +}); + +test("commands: options.global joins after the project, first key wins", async () => { + const exec = async () => ({ code: 0, stdout: "", stderr: "" }); + const global = [ + { key: "clear", desc: "dup", group: GROUP_USER, insert: "/clear " }, + { key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }, + ]; + const items = await commands("/x", exec, { agent: "claude-code", global }); + assert.equal(items.filter((item) => item.key === "clear").length, 1); + assert.equal( + items.find((item) => item.key === "clear").desc, + BUILTINS["claude-code"].find((item) => item.key === "clear").desc, + ); + assert.ok(items.some((item) => item.key === "handoff")); +});