commands-command.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import { formatJson } from "@zcode/core";
  2. import type { Logger } from "@zcode/contracts";
  3. import type { GlobalOptions, RunContext } from "@zcode/shared-types";
  4. import type {
  5. inspectZCodeCustomCommand,
  6. InspectZCodeCustomCommandOptions,
  7. listZCodeCustomCommands,
  8. ListZCodeCustomCommandsOptions,
  9. ZCodeCustomCommandInspection,
  10. } from "@zcode/bootstrap";
  11. import type { CliEnv } from "./env.js";
  12. type BootstrapModule = typeof import("@zcode/bootstrap");
  13. type CustomCommandListOutcome = Awaited<ReturnType<typeof listZCodeCustomCommands>>;
  14. type CustomCommandListItem = CustomCommandListOutcome["commands"][number];
  15. interface CommandsCommandDependencies {
  16. cwd?: () => string;
  17. env?: CliEnv;
  18. inspectCustomCommand?: (
  19. options: InspectZCodeCustomCommandOptions,
  20. ) => ReturnType<typeof inspectZCodeCustomCommand>;
  21. listCustomCommands?: (
  22. options: ListZCodeCustomCommandsOptions,
  23. ) => ReturnType<typeof listZCodeCustomCommands>;
  24. loadBootstrapModule?: () => Promise<BootstrapModule>;
  25. logger?: Logger;
  26. }
  27. const COMMANDS_COMMAND_USAGE = "Usage: zcode commands [list|inspect <name>]";
  28. export async function runCommandsCommand(
  29. ctx: RunContext,
  30. options: GlobalOptions,
  31. deps: CommandsCommandDependencies,
  32. args: string[],
  33. ): Promise<number> {
  34. const subcommand = args[0] ?? "list";
  35. if (subcommand === "list") {
  36. if (args.length > 1) return failUsage(ctx);
  37. return await runCommandsListCommand(ctx, options, deps);
  38. }
  39. if (subcommand === "inspect") {
  40. if (args.length !== 2 || args[1]?.trim().length === 0) return failUsage(ctx);
  41. return await runCommandsInspectCommand(ctx, options, deps, args[1]);
  42. }
  43. ctx.stderr.write(`Unknown commands command: ${subcommand}\n${COMMANDS_COMMAND_USAGE}\n`);
  44. return 1;
  45. }
  46. function failUsage(ctx: RunContext): number {
  47. ctx.stderr.write(`${COMMANDS_COMMAND_USAGE}\n`);
  48. return 1;
  49. }
  50. async function runCommandsListCommand(
  51. ctx: RunContext,
  52. options: GlobalOptions,
  53. deps: CommandsCommandDependencies,
  54. ): Promise<number> {
  55. try {
  56. const workingDirectory = (deps.cwd ?? process.cwd)();
  57. const listCustomCommands = await resolveListCustomCommands(deps);
  58. const outcome = await listCustomCommands({
  59. env: deps.env ?? process.env,
  60. logger: deps.logger,
  61. workingDirectory,
  62. });
  63. ctx.stdout.write(
  64. options.json
  65. ? formatCommandJson(outcome, workingDirectory)
  66. : formatHumanCommandList(outcome, options),
  67. );
  68. return 0;
  69. } catch (error) {
  70. return reportCommandsError(ctx, options, error);
  71. }
  72. }
  73. async function runCommandsInspectCommand(
  74. ctx: RunContext,
  75. options: GlobalOptions,
  76. deps: CommandsCommandDependencies,
  77. name: string,
  78. ): Promise<number> {
  79. try {
  80. const workingDirectory = (deps.cwd ?? process.cwd)();
  81. const inspectCustomCommand = await resolveInspectCustomCommand(deps);
  82. const inspection = await inspectCustomCommand({
  83. env: deps.env ?? process.env,
  84. logger: deps.logger,
  85. name,
  86. workingDirectory,
  87. });
  88. ctx.stdout.write(
  89. options.json
  90. ? formatCommandInspectionJson(inspection, workingDirectory)
  91. : formatHumanCommandInspection(inspection, options),
  92. );
  93. return 0;
  94. } catch (error) {
  95. return reportCommandsError(ctx, options, error);
  96. }
  97. }
  98. async function resolveListCustomCommands(deps: CommandsCommandDependencies) {
  99. if (deps.listCustomCommands) return deps.listCustomCommands;
  100. const bootstrap = deps.loadBootstrapModule ?? (() => import("@zcode/bootstrap"));
  101. return (await bootstrap()).listZCodeCustomCommands;
  102. }
  103. async function resolveInspectCustomCommand(deps: CommandsCommandDependencies) {
  104. if (deps.inspectCustomCommand) return deps.inspectCustomCommand;
  105. const bootstrap = deps.loadBootstrapModule ?? (() => import("@zcode/bootstrap"));
  106. return (await bootstrap()).inspectZCodeCustomCommand;
  107. }
  108. function reportCommandsError(ctx: RunContext, options: GlobalOptions, error: unknown): number {
  109. const message = error instanceof Error ? error.message : String(error);
  110. ctx.stderr.write(`Error: ${message}\n`);
  111. if (options.verbose && error instanceof Error && error.stack) {
  112. ctx.stderr.write(`${error.stack}\n`);
  113. }
  114. return 1;
  115. }
  116. function formatHumanCommandList(
  117. outcome: CustomCommandListOutcome,
  118. options: GlobalOptions,
  119. ): string {
  120. if (outcome.commands.length === 0) {
  121. return "No custom commands found.\n";
  122. }
  123. const lines = [`Custom commands (${outcome.commands.length})`];
  124. for (const command of outcome.commands) {
  125. lines.push(`- /${command.name}${command.argumentHint ? ` ${command.argumentHint}` : ""}`);
  126. lines.push(` ${formatCommandDescription(command)}`);
  127. lines.push(` ${command.scope}/${command.source}: ${command.path}`);
  128. }
  129. appendDiagnostics(lines, outcome.diagnostics, options);
  130. return `${lines.join("\n")}\n`;
  131. }
  132. function formatHumanCommandInspection(
  133. inspection: ZCodeCustomCommandInspection,
  134. options: GlobalOptions,
  135. ): string {
  136. const { metadata } = inspection.command;
  137. const lines = [
  138. `Command: /${metadata.name}`,
  139. `scope/source: ${metadata.scope}/${metadata.source}`,
  140. `path: ${metadata.path}`,
  141. `description: ${metadata.description}`,
  142. ];
  143. if (metadata.argumentHint) lines.push(`argumentHint: ${metadata.argumentHint}`);
  144. if (metadata.allowedTools.length > 0) {
  145. lines.push(`allowedTools: ${metadata.allowedTools.join(", ")}`);
  146. }
  147. if (metadata.skills.length > 0) lines.push(`skills: ${metadata.skills.join(", ")}`);
  148. if (metadata.model) lines.push(`model: ${metadata.model}`);
  149. lines.push(
  150. `size: ${inspection.command.bytesRead}/${inspection.command.sizeBytes} bytes${inspection.command.truncated ? " (truncated)" : ""}`,
  151. );
  152. if (options.verbose) lines.push("", "Content", inspection.command.content || "(empty)");
  153. appendDiagnostics(lines, inspection.diagnostics, options);
  154. return `${lines.join("\n")}\n`;
  155. }
  156. function formatCommandDescription(command: CustomCommandListItem): string {
  157. const suffix = command.disableNonInteractive ? " (interactive only)" : "";
  158. return `${command.description}${suffix}`;
  159. }
  160. function appendDiagnostics(
  161. lines: string[],
  162. diagnostics: CustomCommandListOutcome["diagnostics"],
  163. options: GlobalOptions,
  164. ): void {
  165. if (!options.verbose || diagnostics.length === 0) return;
  166. lines.push("", `Diagnostics (${diagnostics.length})`);
  167. for (const diagnostic of diagnostics) {
  168. const location = diagnostic.path ? ` (${diagnostic.path})` : "";
  169. lines.push(`- [${diagnostic.severity}] ${diagnostic.code}: ${diagnostic.message}${location}`);
  170. }
  171. }
  172. const formatCommandJson = (outcome: CustomCommandListOutcome, cwd: string): string =>
  173. formatJson({
  174. commands: outcome.commands.map(formatCommandMetadataJson),
  175. cwd,
  176. diagnostics: outcome.diagnostics.map(formatDiagnosticJson),
  177. totalDiscovered: outcome.totalDiscovered,
  178. });
  179. const formatCommandInspectionJson = (
  180. inspection: ZCodeCustomCommandInspection,
  181. cwd: string,
  182. ): string =>
  183. formatJson({
  184. command: {
  185. bytesRead: inspection.command.bytesRead,
  186. content: inspection.command.content,
  187. metadata: formatCommandMetadataJson(inspection.command.metadata),
  188. sizeBytes: inspection.command.sizeBytes,
  189. truncated: inspection.command.truncated,
  190. },
  191. cwd,
  192. diagnostics: inspection.diagnostics.map(formatDiagnosticJson),
  193. });
  194. function formatCommandMetadataJson(command: CustomCommandListItem) {
  195. return {
  196. allowedTools: command.allowedTools,
  197. description: command.description,
  198. disableNonInteractive: command.disableNonInteractive,
  199. frontmatterKeys: command.frontmatterKeys,
  200. name: command.name,
  201. path: command.path,
  202. rootPath: command.rootPath,
  203. scope: command.scope,
  204. skills: command.skills,
  205. source: command.source,
  206. ...(command.argumentHint ? { argumentHint: command.argumentHint } : {}),
  207. ...(command.model ? { model: command.model } : {}),
  208. };
  209. }
  210. function formatDiagnosticJson(diagnostic: CustomCommandListOutcome["diagnostics"][number]) {
  211. return {
  212. code: diagnostic.code,
  213. message: diagnostic.message,
  214. ...(diagnostic.commandName ? { commandName: diagnostic.commandName } : {}),
  215. ...(diagnostic.path ? { path: diagnostic.path } : {}),
  216. severity: diagnostic.severity,
  217. };
  218. }