feat: the / menu offers user, plugin and all built-in commands

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 20:29:44 +01:00
1 parent a4c7f25307
commit 02f7f2465b
3 files changed
+439 -9

No files matched your search

@@ -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 `index<TAB>path`.
*/
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<Item[]>}
*/
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<string|null>} readText
* @param {{onReadError?:(error:Error) => void}} [options]
* @returns {Promise<Item[]>}
*/
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;
@@ -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([":", "-", "_", ".", "/"]);