index.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. // ============================================================
  2. // Node Custom Command Adapter
  3. // ============================================================
  4. import { open, readdir, readFile, stat } from "node:fs/promises";
  5. import { basename, relative, resolve } from "node:path";
  6. import type {
  7. CustomCommandContent,
  8. CustomCommandDiagnostic,
  9. CustomCommandLoadOutcome,
  10. CustomCommandMetadata,
  11. CustomCommandOperationOptions,
  12. CustomCommandPort,
  13. CustomCommandRoot,
  14. } from "@zcode/contracts";
  15. import {
  16. resolveDefaultCustomCommandRoots,
  17. type CustomCommandRootResolutionOptions,
  18. } from "./roots.js";
  19. const COMMAND_EXTENSION = ".md";
  20. const COMMAND_NAME_PATTERN = /^[a-z0-9][a-z0-9_:-]{0,63}$/;
  21. const DEFAULT_MAX_COMMAND_BYTES = 100_000;
  22. const MAX_DESCRIPTION_LENGTH = 1024;
  23. const MAX_SCAN_DEPTH = 12;
  24. const SAFE_FRONTMATTER_KEYS = new Set([
  25. "allowed-tools",
  26. "argument-hint",
  27. "description",
  28. "disable-noninteractive",
  29. "model",
  30. "skills",
  31. ]);
  32. export interface NodeCustomCommandAdapterOptions extends CustomCommandRootResolutionOptions {
  33. // 被禁用的命令 .md 绝对路径集合(来自 config.json 的 command.<path>.enable=false)。
  34. // 命中的命令在发现阶段直接剔除,使 discover/load/inspect 全链路保持一致。
  35. disabledPaths?: Iterable<string>;
  36. }
  37. export class NodeCustomCommandAdapter implements CustomCommandPort {
  38. private readonly disabledPaths: ReadonlySet<string>;
  39. constructor(private readonly options: NodeCustomCommandAdapterOptions = {}) {
  40. this.disabledPaths = new Set(Array.from(options.disabledPaths ?? [], (path) => resolve(path)));
  41. }
  42. async discoverCommands(
  43. request: { roots?: CustomCommandRoot[]; workingDirectory: string },
  44. options?: CustomCommandOperationOptions,
  45. ): Promise<CustomCommandLoadOutcome> {
  46. throwIfAborted(options);
  47. const workingDirectory = resolve(request.workingDirectory);
  48. const roots =
  49. request.roots ?? (await resolveDefaultCustomCommandRoots(workingDirectory, this.options));
  50. const diagnostics: CustomCommandDiagnostic[] = [];
  51. const selected = new Map<string, CustomCommandMetadata>();
  52. let totalDiscovered = 0;
  53. for (const root of roots.toSorted((a, b) => a.priority - b.priority)) {
  54. throwIfAborted(options);
  55. const commandPaths = await this.commandFilesUnderRoot(root, diagnostics);
  56. for (const path of commandPaths) {
  57. throwIfAborted(options);
  58. const parsed = await this.parseCommand(path, root, diagnostics);
  59. if (!parsed) continue;
  60. // 命中 config 禁用名单的命令不进入可用集合
  61. if (this.disabledPaths.has(resolve(parsed.path))) continue;
  62. totalDiscovered++;
  63. if (selected.has(parsed.name)) {
  64. diagnostics.push({
  65. code: "custom_command_duplicate_name",
  66. commandName: parsed.name,
  67. message: `Duplicate custom command ignored: ${parsed.name}`,
  68. path,
  69. severity: "warning",
  70. });
  71. continue;
  72. }
  73. selected.set(parsed.name, parsed);
  74. }
  75. }
  76. return {
  77. commands: Array.from(selected.values()).toSorted((a, b) => a.name.localeCompare(b.name)),
  78. diagnostics,
  79. totalDiscovered,
  80. };
  81. }
  82. async loadCommand(
  83. request: {
  84. maxBytes?: number;
  85. name: string;
  86. roots?: CustomCommandRoot[];
  87. workingDirectory: string;
  88. },
  89. options?: CustomCommandOperationOptions,
  90. ): Promise<CustomCommandContent> {
  91. throwIfAborted(options);
  92. const outcome = await this.discoverCommands(
  93. {
  94. roots: request.roots,
  95. workingDirectory: request.workingDirectory,
  96. },
  97. options,
  98. );
  99. const normalizedName = normalizeCommandName(request.name);
  100. const metadata = outcome.commands.find((command) => command.name === normalizedName);
  101. if (!metadata) {
  102. throw new Error(`Custom command not found: ${request.name}`);
  103. }
  104. const maxBytes = request.maxBytes ?? DEFAULT_MAX_COMMAND_BYTES;
  105. const info = await stat(metadata.path);
  106. const truncated = info.size > maxBytes;
  107. const buffer = truncated
  108. ? await readFirstBytes(metadata.path, maxBytes)
  109. : await readFile(metadata.path);
  110. return {
  111. metadata,
  112. bytesRead: buffer.byteLength,
  113. content: stripFrontmatter(buffer.toString("utf8")).trim(),
  114. sizeBytes: info.size,
  115. truncated,
  116. };
  117. }
  118. private async commandFilesUnderRoot(
  119. root: CustomCommandRoot,
  120. diagnostics: CustomCommandDiagnostic[],
  121. ): Promise<string[]> {
  122. try {
  123. const info = await stat(root.path);
  124. if (!info.isDirectory()) return [];
  125. return await scanMarkdownFiles(root.path, diagnostics);
  126. } catch (error) {
  127. if (isNotFoundError(error)) return [];
  128. diagnostics.push({
  129. code: "custom_command_scan_failed",
  130. message:
  131. error instanceof Error ? error.message : `Failed to scan command root: ${root.path}`,
  132. path: root.path,
  133. severity: "warning",
  134. });
  135. return [];
  136. }
  137. }
  138. private async parseCommand(
  139. path: string,
  140. root: CustomCommandRoot,
  141. diagnostics: CustomCommandDiagnostic[],
  142. ): Promise<CustomCommandMetadata | null> {
  143. let rawContent: string;
  144. try {
  145. rawContent = await readFile(path, "utf8");
  146. } catch (error) {
  147. if (isNotFoundError(error)) return null;
  148. diagnostics.push({
  149. code: "custom_command_read_failed",
  150. message: error instanceof Error ? error.message : `Failed to read custom command: ${path}`,
  151. path,
  152. severity: "warning",
  153. });
  154. return null;
  155. }
  156. const name = commandNameFromPath(path, root.path);
  157. if (!COMMAND_NAME_PATTERN.test(name)) {
  158. diagnostics.push({
  159. code: "custom_command_invalid_name",
  160. commandName: name,
  161. message: `Invalid custom command name: ${name}`,
  162. path,
  163. severity: "error",
  164. });
  165. return null;
  166. }
  167. const frontmatter = extractFrontmatter(rawContent);
  168. const parsed = frontmatter ? parseFlatYaml(frontmatter, path, diagnostics) : emptyFrontmatter();
  169. const body = stripFrontmatter(rawContent).trim();
  170. const description = parseScalar(parsed.values.description) ?? extractDescription(body);
  171. if (!description) {
  172. diagnostics.push({
  173. code: "custom_command_invalid_frontmatter",
  174. commandName: name,
  175. message: `Custom command must include a description or non-empty body: ${path}`,
  176. path,
  177. severity: "error",
  178. });
  179. return null;
  180. }
  181. for (const key of parsed.keys) {
  182. if (SAFE_FRONTMATTER_KEYS.has(key)) continue;
  183. diagnostics.push({
  184. code: "custom_command_unknown_frontmatter",
  185. commandName: name,
  186. message: `Unknown custom command frontmatter key: ${key}`,
  187. path,
  188. severity: "warning",
  189. });
  190. }
  191. return {
  192. allowedTools: parseList(parsed.values["allowed-tools"]),
  193. argumentHint: parseScalar(parsed.values["argument-hint"]),
  194. description: truncate(description, MAX_DESCRIPTION_LENGTH),
  195. disableNonInteractive: parseBoolean(parsed.values["disable-noninteractive"]),
  196. frontmatterKeys: parsed.keys,
  197. model: parseScalar(parsed.values.model),
  198. name: root.namespace ? `${root.namespace.toLowerCase()}/${name}` : name,
  199. path,
  200. plugin: root.plugin,
  201. rootPath: root.path,
  202. scope: root.scope,
  203. skills: parseList(parsed.values.skills),
  204. source: root.source,
  205. };
  206. }
  207. }
  208. export function createNodeCustomCommandAdapter(
  209. options: NodeCustomCommandAdapterOptions = {},
  210. ): NodeCustomCommandAdapter {
  211. return new NodeCustomCommandAdapter(options);
  212. }
  213. async function scanMarkdownFiles(
  214. directory: string,
  215. diagnostics: CustomCommandDiagnostic[],
  216. depth = 0,
  217. ): Promise<string[]> {
  218. if (depth > MAX_SCAN_DEPTH) return [];
  219. try {
  220. const entries = await readdir(directory, { withFileTypes: true });
  221. const results: string[] = [];
  222. for (const entry of entries) {
  223. const path = resolve(directory, entry.name);
  224. let isDirectory = entry.isDirectory();
  225. let isFile = entry.isFile();
  226. if (entry.isSymbolicLink()) {
  227. try {
  228. const target = await stat(path);
  229. isDirectory = target.isDirectory();
  230. isFile = target.isFile();
  231. } catch {
  232. // 悬空 symlink 或无权限:跳过该条目,继续扫描其余命令
  233. continue;
  234. }
  235. }
  236. if (isDirectory) {
  237. results.push(...(await scanMarkdownFiles(path, diagnostics, depth + 1)));
  238. } else if (isFile && entry.name.toLowerCase().endsWith(COMMAND_EXTENSION)) {
  239. results.push(path);
  240. }
  241. }
  242. return results;
  243. } catch (error) {
  244. diagnostics.push({
  245. code: "custom_command_scan_failed",
  246. message:
  247. error instanceof Error ? error.message : `Failed to scan command directory: ${directory}`,
  248. path: directory,
  249. severity: "warning",
  250. });
  251. return [];
  252. }
  253. }
  254. function commandNameFromPath(path: string, rootPath: string): string {
  255. const relativePath = relative(rootPath, path);
  256. const withoutExtension = relativePath.slice(0, -COMMAND_EXTENSION.length);
  257. return normalizeCommandName(withoutExtension.split(/[\\/]+/).join(":"));
  258. }
  259. function normalizeCommandName(name: string): string {
  260. return name.trim().replace(/^\/+/, "").toLowerCase();
  261. }
  262. function extractFrontmatter(content: string): string | null {
  263. const normalized = content.replace(/^\uFEFF/, "");
  264. if (!normalized.startsWith("---")) return null;
  265. const lines = normalized.split(/\r?\n/);
  266. if (lines[0]?.trim() !== "---") return null;
  267. const endIndex = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
  268. if (endIndex <= 0) return null;
  269. return lines.slice(1, endIndex).join("\n");
  270. }
  271. function stripFrontmatter(content: string): string {
  272. const normalized = content.replace(/^\uFEFF/, "");
  273. if (!normalized.startsWith("---")) return content;
  274. const lines = normalized.split(/\r?\n/);
  275. const endIndex = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
  276. if (endIndex <= 0) return content;
  277. return lines.slice(endIndex + 1).join("\n");
  278. }
  279. function emptyFrontmatter(): { keys: string[]; values: Record<string, string> } {
  280. return { keys: [], values: {} };
  281. }
  282. function parseFlatYaml(
  283. frontmatter: string,
  284. path: string,
  285. diagnostics: CustomCommandDiagnostic[],
  286. ): { keys: string[]; values: Record<string, string> } {
  287. const values: Record<string, string> = {};
  288. const keys: string[] = [];
  289. for (const [index, line] of frontmatter.split(/\r?\n/).entries()) {
  290. if (line.trim().length === 0 || line.trim().startsWith("#")) continue;
  291. if (/^\s/.test(line)) continue;
  292. const separator = line.indexOf(":");
  293. if (separator <= 0) {
  294. diagnostics.push({
  295. code: "custom_command_invalid_frontmatter",
  296. message: `Invalid frontmatter line ${index + 1} in ${basename(path)}`,
  297. path,
  298. severity: "warning",
  299. });
  300. continue;
  301. }
  302. const key = line.slice(0, separator).trim();
  303. keys.push(key);
  304. values[key] = line.slice(separator + 1).trim();
  305. }
  306. return { keys, values };
  307. }
  308. function parseScalar(value: string | undefined): string | undefined {
  309. if (value === undefined) return undefined;
  310. const trimmed = value.trim();
  311. if (trimmed.length === 0) return undefined;
  312. if (
  313. (trimmed.startsWith('"') && trimmed.endsWith('"')) ||
  314. (trimmed.startsWith("'") && trimmed.endsWith("'"))
  315. ) {
  316. return trimmed.slice(1, -1).trim();
  317. }
  318. return trimmed;
  319. }
  320. function parseBoolean(value: string | undefined): boolean {
  321. const scalar = parseScalar(value)?.toLowerCase();
  322. return scalar === "true" || scalar === "yes";
  323. }
  324. function parseList(value: string | undefined): string[] {
  325. const scalar = parseScalar(value);
  326. if (!scalar) return [];
  327. const withoutBrackets = scalar.replace(/^\[/, "").replace(/\]$/, "");
  328. return withoutBrackets
  329. .split(",")
  330. .map((item) => item.trim())
  331. .filter(Boolean);
  332. }
  333. function extractDescription(body: string): string | undefined {
  334. const line = body
  335. .split(/\r?\n/)
  336. .map((candidate) =>
  337. candidate
  338. .replace(/^#+\s*/, "")
  339. .replace(/^[-*]\s*/, "")
  340. .trim(),
  341. )
  342. .find(Boolean);
  343. return line ? truncate(line, MAX_DESCRIPTION_LENGTH) : undefined;
  344. }
  345. function truncate(value: string, maxLength: number): string {
  346. return value.length > maxLength ? value.slice(0, maxLength) : value;
  347. }
  348. async function readFirstBytes(path: string, maxBytes: number): Promise<Buffer> {
  349. const handle = await open(path, "r");
  350. try {
  351. const buffer = Buffer.alloc(Math.max(0, maxBytes));
  352. const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, 0);
  353. return buffer.subarray(0, bytesRead);
  354. } finally {
  355. await handle.close();
  356. }
  357. }
  358. function isNotFoundError(error: unknown): boolean {
  359. return (
  360. typeof error === "object" &&
  361. error !== null &&
  362. "code" in error &&
  363. (error as { code?: unknown }).code === "ENOENT"
  364. );
  365. }
  366. function throwIfAborted(options: CustomCommandOperationOptions | undefined): void {
  367. if (options?.signal?.aborted) {
  368. throw new Error("Custom command operation cancelled");
  369. }
  370. }