620 lines
23 KiB
JavaScript
620 lines
23 KiB
JavaScript
// catalog.js - where the composer's suggestions come from.
|
|
//
|
|
// The workspace is reached only through the injected `exec` (the mod's
|
|
// `herdr.exec`), so this module runs in plain Node (tests/suggest.test.mjs)
|
|
// with a fake runner. It has no clock and no storage of its own: the view
|
|
// reads the person's snippets and passes them in, and it schedules the retry
|
|
// and the debounce with the numbers exported here.
|
|
//
|
|
// Three sources for `/` (the design's §5.3): the built-in commands of the
|
|
// agent, the project's own `.claude/commands/*.md` and
|
|
// `.claude/skills/*/SKILL.md`, and the person's saved snippets. One source
|
|
// for `@`: the files git tracks in the pane's folder.
|
|
//
|
|
// A read that fails is not an empty list: the failure is reported through
|
|
// `onReadError` and the menu keeps what it knows. A caller with no handler
|
|
// gets the failure itself - nobody may mistake a broken catalog for one
|
|
// 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, GROUP_PLUGIN, rank } from "./suggest.js";
|
|
import { decode } from "./powershell.js";
|
|
|
|
/**
|
|
* @typedef {import("./suggest.js").Item} Item
|
|
*
|
|
* @typedef {object} ExecResult
|
|
* @property {number} code
|
|
* @property {string} stdout
|
|
* @property {string} stderr
|
|
*
|
|
* @typedef {(command:string, args?:string[], options?:{cwd?:string}) => Promise<ExecResult>} Exec
|
|
*/
|
|
|
|
/** How long the composer waits before it asks the workspace again. */
|
|
export const DEBOUNCE_MS = 150;
|
|
|
|
/** The waits between the tries after a read failed: 2 s, 5 s, 15 s, 30 s. */
|
|
export const RETRY_DELAYS = [2000, 5000, 15000, 30000];
|
|
|
|
/** The catalog could not be read - the person may keep typing. */
|
|
export const READ_ERROR_MESSAGE =
|
|
"Nie udało się wczytać podpowiedzi. Pisz dalej, spróbujemy ponownie.";
|
|
|
|
/** The catalog was read and nothing fit the needle. */
|
|
export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo pisz dalej.";
|
|
|
|
/** 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 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: "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." },
|
|
{ key: "approvals", desc: "Ustawia sposób zatwierdzania poleceń." },
|
|
{ key: "new", desc: "Zaczyna nową sesję." },
|
|
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
|
|
],
|
|
};
|
|
|
|
/** The same agent under the name the program's table gives it. */
|
|
const AGENT_ALIASES = { claude: "claude-code" };
|
|
|
|
/** How many files the `@` menu shows at most. */
|
|
const FILE_LIMIT = 20;
|
|
|
|
/** The project's command files, as a shell finds them. */
|
|
const LIST_SH =
|
|
'for f in .claude/commands/*.md .claude/skills/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; exit 0';
|
|
|
|
/** The same in PowerShell, for a machine without a POSIX shell. */
|
|
const LIST_PS =
|
|
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
|
"@(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"';
|
|
|
|
/**
|
|
* How long to wait before the next try after a read failed. The last wait
|
|
* repeats: the composer keeps trying every 30 s until the catalog is read.
|
|
*
|
|
* @param {number} attempt - 0 for the first wait
|
|
* @returns {number} milliseconds
|
|
*/
|
|
export function retryDelay(attempt) {
|
|
const index = Number.isFinite(attempt) ? Math.max(0, Math.floor(attempt)) : 0;
|
|
return RETRY_DELAYS[Math.min(index, RETRY_DELAYS.length - 1)];
|
|
}
|
|
|
|
/**
|
|
* The commands the `/` menu offers: the agent's built-ins, the project's own
|
|
* and the person's snippets.
|
|
*
|
|
* A source that cannot be read does not take the others with it: the menu
|
|
* shows what is known and the failure goes to `onReadError`, so the caller
|
|
* can tell a catalog it could not read from one with nothing to show.
|
|
* Without a handler the call rejects - the failure is never swallowed.
|
|
*
|
|
* @param {string} cwd - the folder of the pane
|
|
* @param {Exec} exec
|
|
* @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 = {}) {
|
|
const builtins = builtinItems(options.agent);
|
|
const snippets = snippetItems(options.snippets);
|
|
|
|
let project = [];
|
|
try {
|
|
project = await projectItems(cwd, exec);
|
|
} catch (err) {
|
|
// Nobody to tell: the caller gets the failure instead of a list that
|
|
// looks empty - an empty list would say "nothing fits" and the caller
|
|
// would never try again.
|
|
if (options.onReadError) options.onReadError(err);
|
|
else throw err;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* The files the `@` menu offers: the ones git tracks in the pane's folder.
|
|
*
|
|
* The best matches come first and only then are they cut to twenty - a file
|
|
* that fits is never hidden behind twenty names that do not. Without a
|
|
* handler the call rejects when git fails.
|
|
*
|
|
* @param {string} cwd - the folder of the pane
|
|
* @param {Exec} exec
|
|
* @param {{needle?:string, limit?:number, onReadError?:(error:Error) => void}} [options]
|
|
* @returns {Promise<Item[]>}
|
|
*/
|
|
export async function files(cwd, exec, options = {}) {
|
|
const needle = String(options.needle ?? "").toLowerCase();
|
|
const limit = Number.isFinite(options.limit) ? options.limit : FILE_LIMIT;
|
|
|
|
let paths = [];
|
|
try {
|
|
paths = await gitFiles(cwd, exec);
|
|
} catch (err) {
|
|
// Nobody to tell: the caller gets the failure instead of an empty list
|
|
// that would say "nothing fits".
|
|
if (options.onReadError) options.onReadError(err);
|
|
else throw err;
|
|
}
|
|
|
|
const items = paths.map((path) => ({ key: path, desc: "", insert: `@${path} ` }));
|
|
return rank(items, needle, { atLineStart: true }).slice(0, limit);
|
|
}
|
|
|
|
/** The built-in commands of one agent - an agent we do not know has none. */
|
|
function builtinItems(agent) {
|
|
const name = String(agent ?? "");
|
|
const list = BUILTINS[name] ?? BUILTINS[AGENT_ALIASES[name]];
|
|
if (!list) return [];
|
|
return list.map((item) => ({
|
|
key: item.key,
|
|
desc: item.desc,
|
|
group: GROUP_BUILTIN,
|
|
insert: `/${item.key} `,
|
|
}));
|
|
}
|
|
|
|
/** The commands the project has: its command files and its skills. */
|
|
async function projectItems(cwd, exec) {
|
|
const { kind, paths } = await listProjectFiles(cwd, exec);
|
|
|
|
const items = [];
|
|
for (const path of paths) {
|
|
const name = commandName(path);
|
|
if (!name) continue;
|
|
const text = await readFile(cwd, exec, path, kind);
|
|
if (text === null) continue;
|
|
items.push({ key: name, desc: describe(text), group: GROUP_PROJECT, insert: `/${name} ` });
|
|
}
|
|
return items;
|
|
}
|
|
|
|
/** The person's own snippets, as the view read them from the storage. */
|
|
function snippetItems(snippets) {
|
|
if (!Array.isArray(snippets)) return [];
|
|
|
|
const items = [];
|
|
for (const snippet of snippets) {
|
|
const key = String(snippet?.key ?? snippet?.name ?? "").trim();
|
|
if (!key) continue;
|
|
const item = {
|
|
key,
|
|
desc: String(snippet?.desc ?? snippet?.description ?? ""),
|
|
group: GROUP_USER,
|
|
insert: `/${key} `,
|
|
};
|
|
if (Number.isFinite(snippet?.uses)) item.uses = snippet.uses;
|
|
items.push(item);
|
|
}
|
|
return items;
|
|
}
|
|
|
|
/**
|
|
* The project's command files. A POSIX shell is asked first - it is what a
|
|
* Linux or macOS machine has - and PowerShell after it, for a Windows machine
|
|
* without one. Neither is there: the catalog could not be read.
|
|
*/
|
|
async function listProjectFiles(cwd, exec) {
|
|
const viaShell = await tryList(exec, "sh", ["-c", LIST_SH, "catalog"], cwd, false);
|
|
if (viaShell) return { kind: "sh", paths: viaShell };
|
|
|
|
const viaPowerShell = await tryList(
|
|
exec,
|
|
"powershell",
|
|
["-NoProfile", "-Command", LIST_PS],
|
|
cwd,
|
|
true,
|
|
);
|
|
if (viaPowerShell) return { kind: "powershell", paths: viaPowerShell };
|
|
|
|
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;
|
|
try {
|
|
result = await exec(command, args, { cwd });
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!result || result.code !== 0) return null;
|
|
|
|
return String(result.stdout ?? "")
|
|
.split("\n")
|
|
.map((line) => {
|
|
const path = line.trim();
|
|
// PowerShell writes the separators of its own platform.
|
|
return windowsPaths ? path.replace(/\\/g, "/") : path;
|
|
})
|
|
.filter(Boolean);
|
|
}
|
|
|
|
/**
|
|
* One file of the project. The file may be gone between the listing and the
|
|
* read - then it is left out of the menu, not a reason to fail the catalog.
|
|
*/
|
|
async function readFile(cwd, exec, path, kind) {
|
|
const shells = kind === "sh" ? ["sh", "powershell"] : ["powershell", "sh"];
|
|
|
|
for (const shell of shells) {
|
|
const text = await tryRead(exec, shell, path, cwd);
|
|
if (text !== null) return text;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** One read, or `null` when the file is not there or cannot be read. */
|
|
async function tryRead(exec, shell, path, cwd) {
|
|
const args =
|
|
shell === "sh"
|
|
? ["-c", READ_SH, "catalog", path]
|
|
: ["-NoProfile", "-Command", readScript(path)];
|
|
|
|
let result;
|
|
try {
|
|
result = await exec(shell, args, { cwd });
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (!result || result.code !== 0) return null;
|
|
return String(result.stdout ?? "");
|
|
}
|
|
|
|
/**
|
|
* The PowerShell that reads one file.
|
|
*
|
|
* The path comes from a project that may have been cloned from anywhere, and
|
|
* PowerShell reads U+2018..U+201B as quotes too: the path is never in the
|
|
* script as text, only as Base64 that the script decodes (`powershell.js`).
|
|
*
|
|
* @param {string} path
|
|
* @returns {string}
|
|
*/
|
|
export function readScript(path) {
|
|
return (
|
|
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
|
// A file that is gone writes nothing and says nothing - the command
|
|
// would be a ghost. Without the encoding, Windows PowerShell reads a file
|
|
// without a BOM as the system's own code page, and the text comes out
|
|
// garbled.
|
|
`$path = ${decode(path)}; ` +
|
|
"if (-not (Test-Path -LiteralPath $path)) { exit 1 }; " +
|
|
"Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath $path"
|
|
);
|
|
}
|
|
|
|
/** The name of the command a file holds: the file's name, or a skill's folder. */
|
|
function commandName(path) {
|
|
const parts = path.split("/");
|
|
const file = parts[parts.length - 1] ?? "";
|
|
if (file.toLowerCase() === "skill.md") return parts[parts.length - 2] ?? "";
|
|
return file.replace(/\.md$/i, "");
|
|
}
|
|
|
|
/**
|
|
* What the menu says about a command: the description of the front matter if
|
|
* there is one, else the first line that says something.
|
|
*/
|
|
function describe(markdown) {
|
|
const { fields, body } = frontmatter(String(markdown ?? ""));
|
|
if (fields.description) return clip(fields.description);
|
|
|
|
const line = body
|
|
.split("\n")
|
|
.map((part) => part.trim())
|
|
.find((part) => part !== "" && !part.startsWith("#"));
|
|
return clip(line ?? "");
|
|
}
|
|
|
|
/** The front matter of a markdown file, if it has one. */
|
|
function frontmatter(text) {
|
|
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
|
if (!match) return { fields: {}, body: text };
|
|
|
|
const fields = {};
|
|
for (const line of match[1].split(/\r?\n/)) {
|
|
const field = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
|
|
if (!field) continue;
|
|
fields[field[1].toLowerCase()] = field[2].trim().replace(/^["']|["']$/g, "");
|
|
}
|
|
return { fields, body: text.slice(match[0].length) };
|
|
}
|
|
|
|
/** One line of text, no longer than the menu has room for. */
|
|
function clip(text) {
|
|
const flat = String(text).replace(/\s+/g, " ").trim();
|
|
if (flat.length <= 160) return flat;
|
|
return `${flat.slice(0, 160).replace(/\s\S*$/, "")}…`;
|
|
}
|
|
|
|
/**
|
|
* The files git tracks in the folder. `-z` keeps the names as they are - git
|
|
* would otherwise write a name with a non-ASCII character in it quoted and
|
|
* escaped.
|
|
*/
|
|
async function gitFiles(cwd, exec) {
|
|
let result;
|
|
try {
|
|
result = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
|
|
cwd,
|
|
});
|
|
} catch (err) {
|
|
throw new Error(`nie udało się wczytać plików: ${err?.message ?? String(err)}`);
|
|
}
|
|
|
|
if (!result || result.code !== 0) {
|
|
const stderr = String(result?.stderr ?? "");
|
|
// A folder that is not a repository has no files to offer - that is an
|
|
// empty list, not a catalog that could not be read.
|
|
if (result?.code === 128 && /repo/i.test(stderr)) return [];
|
|
throw new Error(
|
|
`nie udało się wczytać plików: ${stderr.trim() || `git zakończone kodem ${result?.code}`}`,
|
|
);
|
|
}
|
|
|
|
return String(result.stdout ?? "")
|
|
.split("\0")
|
|
.map((path) => path.trim())
|
|
.filter(Boolean);
|
|
}
|