import { z } from "zod"; import { parseCliGlobalArguments, type CliGlobalArguments, } from "../cliBuiltinArguments.js"; import { CLI_DOCUMENT_OUTPUT_FORMATS, CLI_OUTPUT_FORMATS, readCliOutputArguments, } from "../cliOutput.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { formatCliOutput } from "./cliOutputFormatter.js"; import { commandSchemaDocument, formatLlmsFull, formatLlmsIndex, llmsFullManifest, llmsIndexManifest, } from "./commandManifests.js"; import { cliCommands, type CliCommandEntry } from "./commandRegistry.js"; import { suggestCommand } from "./commandSuggestion.js"; import { formatCommandHelp, formatCommandListHelp, type HelpCommandRow, } from "./help.js"; import { MCP_SUBCOMMANDS } from "./mcpBuiltinCommands.js"; import type { CliInstance } from "./types.js"; /** The root page's description of REA. */ export const CLI_DESCRIPTION = "Reverse engineer anything from your terminal or agent."; /** Global options REA defines beyond the standard output controls. */ export const CLI_CUSTOM_GLOBAL_OPTIONS = z.object({ timings: z .boolean() .default(false) .describe("Write measured command timing to stderr."), }); export const MCP_GROUP_DESCRIPTION = "Register as MCP server"; export const COMPLETIONS_DESCRIPTION = "Generate shell completion script"; /** Shells in the order the completions page lists them. */ const HELP_SHELLS = ["bash", "fish", "nushell", "zsh"] as const; const completionsHint = (name: string): string => { const rows = [ ["bash", `eval "$(${name} completions bash)"`, "# add to ~/.bashrc"], [ "fish", `${name} completions fish | source`, "# add to ~/.config/fish/config.fish", ], ["nushell", `see \`${name} completions nushell\``, "# add to config.nu"], ["zsh", `eval "$(${name} completions zsh)"`, "# add to ~/.zshrc"], ] as const; const shellWidth = Math.max(...rows.map(([shell]) => shell.length)); const commandWidth = Math.max(...rows.map(([, command]) => command.length)); return `Setup:\n${rows .map( ([shell, command, comment]) => ` ${shell.padEnd(shellWidth)} ${command.padEnd(commandWidth)} ${comment}`, ) .join("\n")}`; }; /** The global options block of a page for a command that renders results. */ const commandGlobalOptions = { formats: CLI_OUTPUT_FORMATS, custom: CLI_CUSTOM_GLOBAL_OPTIONS, }; const rootPage = (cli: CliInstance): string => formatCommandListHelp(cli.name, { version: PRODUCT_IDENTITY.packageVersion, description: CLI_DESCRIPTION, commands: cliCommands(cli) .map(({ name, definition }): HelpCommandRow => ({ name, description: definition.description, })) .sort((left, right) => left.name.localeCompare(right.name)), globalOptions: { ...commandGlobalOptions, root: { integrations: [ { name: "completions", description: COMPLETIONS_DESCRIPTION }, { name: "mcp", description: `${MCP_GROUP_DESCRIPTION} (${[...MCP_SUBCOMMANDS.keys()].join(", ")})`, }, ], }, }, }); /** The position of an integration command: first, or after the CLI's own name. */ const integrationIndex = ( command: readonly string[], name: string, integration: string, ): number => command[0] === integration ? 0 : command[0] === name && command[1] === integration ? 1 : -1; /** A document REA writes instead of running a command, and the status it ends with. */ interface DiscoveryAnswer { readonly text: string; readonly exitCode: number; } const answer = (text: string, exitCode = 0): DiscoveryAnswer => ({ text: text.endsWith("\n") ? text : `${text}\n`, exitCode, }); const sortedCommands = (cli: CliInstance): readonly CliCommandEntry[] => [...cliCommands(cli)].sort((left, right) => left.name.localeCompare(right.name), ); /** * `--llms` and `--llms-full`: Markdown unless a structured format is chosen. * A known command first scopes the manifest to that command. */ const llmsAnswer = ( cli: CliInstance, global: CliGlobalArguments, full: boolean, ): DiscoveryAnswer => { const { format, formatExplicit } = readCliOutputArguments(global); const scoped = cliCommands(cli).find( ({ name }) => name === global.command[0], ); const commands = scoped === undefined ? sortedCommands(cli) : [scoped]; if (!formatExplicit || format === "md") return answer( full ? formatLlmsFull(cli.name, commands) : formatLlmsIndex(cli.name, commands, CLI_DESCRIPTION), ); return answer( formatCliOutput( full ? llmsFullManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS) : llmsIndexManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS), format, ), ); }; /** * `--schema` for a command, or the error for an unknown one. Markdown stays * with the dispatcher: it renders the document without Markdown escaping, * unlike REA's renderer, and that difference awaits a decision (#11654). */ const schemaAnswer = ( cli: CliInstance, global: CliGlobalArguments, ): DiscoveryAnswer | undefined => { const name = global.command[0]!; const entry = cliCommands(cli).find((command) => command.name === name); if (entry === undefined) { const suggestion = suggestCommand( name, cliCommands(cli).map((command) => command.name), ); return answer( `Error: '${name}' is not a command for '${cli.name}'.${suggestion === undefined ? "" : ` Did you mean '${suggestion}'?`}`, 1, ); } const { format, formatExplicit } = readCliOutputArguments(global); if (formatExplicit && format === "md") return undefined; return answer( formatCliOutput( commandSchemaDocument(entry, CLI_CUSTOM_GLOBAL_OPTIONS), formatExplicit ? format : "toon", ), ); }; /** * The document an invocation asks for instead of running a command, or * undefined. Precedence: the update check, `--update` without help and * `--mcp` stay with the dispatcher; the LLM manifests answer next; then the * integrations (`completions` shows its page for help or without a shell, * `mcp` shows its page without a subcommand); then `--version` without help; * then the root page for no command; then a command's page for help (help * after an unknown command shows the root page); then `--schema`. */ const discoveryAnswer = ( cli: CliInstance, global: CliGlobalArguments, ): DiscoveryAnswer | undefined => { const { command, flags } = global; const help = flags.has("--help") || flags.has("-h"); if ( flags.has("--incur-update-check") || (flags.has("--update") && !help) || flags.has("--mcp") ) return undefined; if (flags.has("--llms") || flags.has("--llms-full")) return llmsAnswer(cli, global, flags.has("--llms-full")); const completions = integrationIndex(command, cli.name, "completions"); if (completions >= 0) return help || command[completions + 1] === undefined ? answer( formatCommandHelp(`${cli.name} completions`, { description: COMPLETIONS_DESCRIPTION, args: z.object({ shell: z .enum(HELP_SHELLS) .describe("Shell to generate completions for"), }), hint: completionsHint(cli.name), }), ) : undefined; const mcp = integrationIndex(command, cli.name, "mcp"); if (mcp >= 0) { const subcommand = command[mcp + 1]; if (subcommand === undefined) return answer( formatCommandListHelp(`${cli.name} mcp`, { description: MCP_GROUP_DESCRIPTION, commands: [...MCP_SUBCOMMANDS].map(([name, { description }]) => ({ name, description, })), globalOptions: { formats: CLI_DOCUMENT_OUTPUT_FORMATS }, }), ); // `mcp add` renders its own page; an unknown subcommand is an error. return help && subcommand === "doctor" ? answer( formatCommandHelp(`${cli.name} mcp doctor`, { description: MCP_SUBCOMMANDS.get("doctor")!.description, }), ) : undefined; } if (flags.has("--version") && !help) return answer(PRODUCT_IDENTITY.packageVersion); if (command.length === 0) return answer(rootPage(cli)); if (help) { const entry = cliCommands(cli).find(({ name }) => name === command[0]); if (entry === undefined) return answer(rootPage(cli)); const { definition } = entry; return answer( formatCommandHelp(`${cli.name} ${entry.name}`, { description: definition.description, args: definition.args, options: definition.options, alias: definition.alias, globalOptions: commandGlobalOptions, }), ); } if (flags.has("--schema")) return schemaAnswer(cli, global); return undefined; }; type ServeOptions = NonNullable[1]>; /** * Answer help, `--version`, `--schema` and the LLM manifests, reading the * arguments as the command dispatcher receives them. Returns false when the * invocation asks for something else. */ export const serveDiscovery = ( cli: CliInstance, arguments_: readonly string[], options: ServeOptions, ): boolean => { const result = discoveryAnswer(cli, parseCliGlobalArguments(arguments_)); if (result === undefined) return false; (options.stdout ?? ((text: string) => process.stdout.write(text)))( result.text, ); if (result.exitCode !== 0) (options.exit ?? ((code: number) => process.exit(code)))(result.exitCode); return true; };