// 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, rank } from "./suggest.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} 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 small list the design names. */ export const BUILTINS = { "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: "config", desc: "Otwiera ustawienia." }, { key: "resume", desc: "Wznawia wcześniejszą sesję." }, ], 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 }"; /** 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[], onReadError?:(error:Error) => void}} [options] * @returns {Promise} */ 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; } return [...builtins, ...project, ...snippets]; } /** * 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} */ 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"); } /** 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 goes in as a literal. */ function readScript(path) { const literal = path.replace(/'/g, "''"); 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. `if (-not (Test-Path -LiteralPath '${literal}')) { exit 1 }; ` + `Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath '${literal}'` ); } /** 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); }