fix(cli): render help in REA and list csv and tsv formats (#11688)

* refactor(cli): render help pages with REA's help owner

REA now renders the root page, every command page, help after an unknown command, the mcp group page, the mcp doctor builtin page and the completions page before incur sees argv, with incur's precedence (update check, --update without help, --mcp and the LLM manifests first; then the integrations; then --version; then root and command pages). help.ts gains arguments, custom global options, the root-only flags and integrations, and a command-list page.

The --format row on the root and command pages now lists csv and tsv (#10250), the approved difference; the mcp and mcp add pages keep the document formats they accept. Every other help byte is unchanged: 397 pages compared with incur's Help for all 196 registered commands.

Fixes #10250

* test(cli): elide the root command list wherever the root page is printed

The golden renderer chose root-page elision by case name, so help after an unknown command froze the whole command list. It now elides any stdout that opens with the root page's rea@<version> title.

* refactor(cli): answer --version, --schema and the LLM manifests in REA (#11690)

* refactor(cli): answer --version, --schema and the LLM manifests in REA

src/cli/discovery.ts answers help, --version, --schema, --llms and --llms-full with incur's precedence, reading the arguments as the dispatcher receives them (after result output has adapted them, so token counts and buffering are unchanged). commandManifests.ts renders the Markdown index and full manifest, the structured manifests and the --schema document; commandSuggestion.ts ranks Did-you-mean candidates. Both are adapted from incur under its MIT licence.

--schema --format md stays with incur: incur renders it without Markdown escaping, unlike REA's renderer, and that difference awaits a decision on #11654. Compared with incur's serve for every registered command and format, 3746 of 3945 discovery invocations are identical; the rest are the 196 Markdown schemas left to incur and the three root help pages with the approved csv/tsv row.

* test(cli): pin which discovery document wins when several are asked for

Goldens for --llms with --help, --llms with --version, --llms with --llms-full, --schema with --version and --schema with --help, recorded with incur's rendering on the base branch.
This commit is contained in:
morluto authored and GitHub committed 2026-11-16 12:55:30 +08:00
1 parent 6c4e2bba9d
commit a8cd584ccf
34 files changed
+1210 -184

No files matched your search

+14 -8
View File
@@ -1,5 +1,4 @@
import { Cli } from "incur";
import { z } from "zod";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js";
@@ -28,6 +27,11 @@ import {
} from "./cliResultOutput.js";
import { completionHelpNote, createCliCompletions } from "./completions.js";
import { excludeDeclaredSensitiveArguments } from "./explicitSensitiveArguments.js";
import {
CLI_CUSTOM_GLOBAL_OPTIONS,
CLI_DESCRIPTION,
serveDiscovery,
} from "./discovery.js";
import { reportUnknownMcpSubcommand } from "./mcpBuiltinCommands.js";
import { serveMcpRegistration } from "./mcpRegistration.js";
import { presentOmittableDefaults } from "./omittableDefaults.js";
@@ -95,13 +99,8 @@ export const createCliShell = (options: CliShellOptions): CliInstance => {
);
const timedCli = Cli.create(PRODUCT_IDENTITY.cliBinary, {
version: PRODUCT_IDENTITY.packageVersion,
description: "Reverse engineer anything from your terminal or agent.",
globals: z.object({
timings: z
.boolean()
.default(false)
.describe("Write measured command timing to stderr."),
}),
description: CLI_DESCRIPTION,
globals: CLI_CUSTOM_GLOBAL_OPTIONS,
mcp: {
instructions:
"Ask what software, artifact, protocol, or behavior the user wants to understand, then choose the available investigation capabilities that can produce evidence.",
@@ -146,6 +145,13 @@ export const createCliShell = (options: CliShellOptions): CliInstance => {
);
presentOmittableDefaults(cli);
// Discovery reads the arguments the dispatcher would, after result output
// has adapted them, so its documents are counted and buffered alike.
const dispatch = cli.serve.bind(cli);
cli.serve = (arguments_ = process.argv.slice(2), serveOptions) =>
serveDiscovery(cli, arguments_, serveOptions ?? {})
? Promise.resolve()
: dispatch(arguments_, serveOptions);
if (options.resultOutput !== undefined)
streamCliCommandResults(cli, options.resultOutput);
const serveStrict = validateCliArguments(cli);
+193
View File
@@ -0,0 +1,193 @@
/*
* The --llms index, the --llms-full manifest and the --schema document are
* adapted from Incur's manifest and skill generators.
* Copyright (c) 2025-present weth, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
import { z } from "zod";
import type { CliCommandEntry } from "./commandRegistry.js";
/** The manifests' format version, which callers may already check. */
const MANIFEST_VERSION = "incur.v1";
type JsonSchema = Record<string, unknown> & {
readonly type?: unknown;
readonly properties?: Readonly<Record<string, JsonSchema>>;
readonly required?: readonly string[];
readonly default?: unknown;
readonly deprecated?: unknown;
};
/**
* A command input as JSON Schema, without `$schema`. Bigints and dates are
* strings, and unrepresentable types accept anything.
*/
export const commandInputJsonSchema = (schema: z.ZodType): JsonSchema => {
const result = z.toJSONSchema(schema, {
unrepresentable: "any",
override: (context) => {
const type = context.zodSchema._zod.def.type;
if (type === "bigint" || type === "date")
context.jsonSchema.type = "string";
},
}) as JsonSchema;
delete result.$schema;
return result;
};
/** The JSON type a manifest table shows, with integers shown as numbers. */
const tableType = (property: JsonSchema | undefined): string => {
const type = property?.type;
if (typeof type !== "string") return "unknown";
return type === "integer" ? "number" : type;
};
const shape = (schema: z.ZodObject): Readonly<Record<string, z.ZodType>> =>
schema.shape as Readonly<Record<string, z.ZodType>>;
/** `rea <command> <required> [optional] <variadic...>`. */
const signature = (cli: string, { name, definition }: CliCommandEntry) => {
const base = `${cli} ${name}`;
if (definition.args === undefined) return base;
const json = commandInputJsonSchema(definition.args);
const required = new Set(json.required ?? []);
const names = Object.keys(shape(definition.args)).map((key) => {
const label = json.properties?.[key]?.type === "array" ? `${key}...` : key;
return required.has(key) ? `<${label}>` : `[${label}]`;
});
return `${base} ${names.join(" ")}`;
};
/** The `--llms` Markdown index: one row per command. */
export const formatLlmsIndex = (
cli: string,
commands: readonly CliCommandEntry[],
description: string,
): string =>
[
`# ${cli}`,
"",
description,
"",
"| Command | Description |",
"|---------|-------------|",
...commands.map(
(command) =>
`| \`${signature(cli, command)}\` | ${command.definition.description ?? ""} |`,
),
"",
`Run \`${cli} --llms-full\` for full manifest. Run \`${cli} <command> --schema\` for argument details.`,
].join("\n");
const commandBody = (cli: string, { name, definition }: CliCommandEntry) => {
const heading =
definition.description === undefined || definition.description === ""
? `# ${cli} ${name}`
: `# ${cli} ${name}\n\n${definition.description}`;
const sections = [heading];
if (definition.args !== undefined) {
const json = commandInputJsonSchema(definition.args);
const required = new Set(json.required ?? []);
const rows = Object.entries(shape(definition.args)).map(
([key, field]) =>
`| \`${key}\` | \`${tableType(json.properties?.[key])}\` | ${required.has(key) ? "yes" : "no"} | ${field.description ?? ""} |`,
);
sections.push(
`## Arguments\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n${rows.join("\n")}`,
);
}
if (definition.options !== undefined) {
const json = commandInputJsonSchema(definition.options);
const rows = Object.entries(shape(definition.options)).map(
([key, field]) => {
const property = json.properties?.[key];
const fallback =
property?.default === undefined ? "" : String(property.default);
const text = field.description ?? "";
const description =
property?.deprecated === true ? `**Deprecated.** ${text}` : text;
return `| \`--${key}\` | \`${tableType(property)}\` | ${fallback === "" ? "" : `\`${fallback}\``} | ${description} |`;
},
);
sections.push(
`## Options\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n${rows.join("\n")}`,
);
}
return sections.join("\n\n");
};
/** The `--llms-full` Markdown manifest: each command's arguments and options. */
export const formatLlmsFull = (
cli: string,
commands: readonly CliCommandEntry[],
): string => commands.map((command) => commandBody(cli, command)).join("\n\n");
/** The `--llms` document for a structured format: names and descriptions. */
export const llmsIndexManifest = (
commands: readonly CliCommandEntry[],
globals: z.ZodObject,
) => ({
version: MANIFEST_VERSION,
commands: commands.map(({ name, definition }) => ({
name,
...(definition.description ? { description: definition.description } : {}),
})),
globals: commandInputJsonSchema(globals),
});
/** The `--llms-full` document for a structured format: each command's input schemas. */
export const llmsFullManifest = (
commands: readonly CliCommandEntry[],
globals: z.ZodObject,
) => ({
version: MANIFEST_VERSION,
commands: commands.map(({ name, definition }) => ({
name,
...(definition.description ? { description: definition.description } : {}),
...(definition.args === undefined && definition.options === undefined
? {}
: {
schema: {
...(definition.args === undefined
? {}
: { args: commandInputJsonSchema(definition.args) }),
...(definition.options === undefined
? {}
: { options: commandInputJsonSchema(definition.options) }),
},
}),
})),
globals: commandInputJsonSchema(globals),
});
/** The `--schema` document of one command. */
export const commandSchemaDocument = (
{ definition }: CliCommandEntry,
globals: z.ZodObject,
) => ({
...(definition.args === undefined
? {}
: { args: commandInputJsonSchema(definition.args) }),
...(definition.options === undefined
? {}
: { options: commandInputJsonSchema(definition.options) }),
globals: commandInputJsonSchema(globals),
});
+74
View File
@@ -0,0 +1,74 @@
/*
* The ranking is adapted from Incur's command suggestion.
* Copyright (c) 2025-present weth, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/** The edit distance between two strings. */
const editDistance = (left: string, right: string): number => {
const row = Array.from({ length: right.length + 1 }, (_, index) => index);
for (let i = 1; i <= left.length; i += 1) {
let diagonal = row[0]!;
row[0] = i;
for (let j = 1; j <= right.length; j += 1) {
const above = row[j]!;
row[j] =
left[i - 1] === right[j - 1]
? diagonal
: 1 + Math.min(diagonal, above, row[j - 1]!);
diagonal = above;
}
}
return row[right.length]!;
};
/**
* The command a mistyped name most likely meant, or undefined. Candidates
* that extend the input rank first, then ones that contain it, then ones
* within a small edit distance (2 for inputs of up to 4 characters, otherwise
* half the input's length). Within a tier the smallest distance wins, and the
* first candidate wins a tie. Case is ignored.
*/
export const suggestCommand = (
input: string,
candidates: Iterable<string>,
): string | undefined => {
const threshold = input.length <= 4 ? 2 : Math.floor(input.length / 2);
const lower = input.toLowerCase();
let best: string | undefined;
let bestScore = Infinity;
for (const candidate of candidates) {
const name = candidate.toLowerCase();
const distance = editDistance(lower, name);
const score =
name.startsWith(lower) && name !== lower
? distance
: name.includes(lower)
? 100 + distance
: distance <= threshold
? 200 + distance
: undefined;
if (score !== undefined && score < bestScore) {
bestScore = score;
best = candidate;
}
}
return best;
};
+3 -2
View File
@@ -17,6 +17,7 @@ import {
type CompletionCommand,
} from "./completionProtocol.js";
import { cliCommands } from "./commandRegistry.js";
import { COMPLETIONS_DESCRIPTION, MCP_GROUP_DESCRIPTION } from "./discovery.js";
import { MCP_SUBCOMMANDS } from "./mcpBuiltinCommands.js";
import type { CliInstance } from "./types.js";
import { MCP_DOCTOR_ALIAS, MCP_DOCTOR_OPTIONS } from "../mcpDoctorOptions.js";
@@ -100,12 +101,12 @@ const completionCommands = (
);
commands.set("mcp", {
_group: true,
description: "Register as MCP server",
description: MCP_GROUP_DESCRIPTION,
commands: MCP_SUBCOMMANDS,
});
commands.set("completions", {
_group: true,
description: "Generate shell completion script",
description: COMPLETIONS_DESCRIPTION,
commands: new Map(CLI_COMPLETION_SHELLS.map((shell) => [shell, {}])),
});
// REA uses sync:false, so the framework's skills integration is disabled.
+291
View File
@@ -0,0 +1,291 @@
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<Parameters<CliInstance["serve"]>[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;
};
+101 -14
View File
@@ -3,20 +3,39 @@ import { z } from "zod";
import { declaredOptionType, optionFlagName } from "./optionFields.js";
/**
* REA's command help text. The layout is the one the CLI has always printed:
* a `name — description` title, a usage line, aligned option rows with type
* placeholders and shown defaults, an optional hint, then the global options the
* entry accepts.
* REA's help text. The layout is the one the CLI has always printed: a
* `name — description` title, a usage line, aligned argument and option rows
* with type placeholders and shown defaults, an optional hint, then the global
* options the entry accepts.
*/
/** A named entry in a command list. */
export interface HelpCommandRow {
readonly name: string;
readonly description?: string | undefined;
}
/** The global options block of an entry that accepts them. */
export interface GlobalOptionsHelp {
/** The `--format` values this entry accepts, in display order. */
readonly formats: readonly string[];
/** Global options REA defines beyond the standard ones, such as `--timings`. */
readonly custom?: z.ZodObject | undefined;
/**
* The root page also lists the integration commands and the flags that
* apply only before a command (`--mcp`, `--update`, `--version`).
*/
readonly root?:
| { readonly integrations: readonly HelpCommandRow[] }
| undefined;
}
export interface CommandHelp {
readonly description?: string | undefined;
/** Printed as `name@version` in the title. */
readonly version?: string | undefined;
/** Positionals, in argv order. */
readonly args?: z.ZodObject | undefined;
readonly options?: z.ZodObject | undefined;
/** Short alias by option key, such as `{ help: "h" }`. */
readonly alias?: Readonly<Record<string, string>> | undefined;
@@ -92,8 +111,32 @@ const optionRows = (
},
);
/** The global options every command entry accepts, sorted by flag. */
const globalOptionRows = ({ formats }: GlobalOptionsHelp): Row[] =>
/** A command list's rows, in the order given. */
const commandRows = (commands: readonly HelpCommandRow[]): string[] => {
const width = Math.max(...commands.map((command) => command.name.length));
return commands.map((command) =>
command.description === undefined || command.description === ""
? ` ${command.name}`
: ` ${command.name}${" ".repeat(width - command.name.length)} ${command.description}`,
);
};
/** `<required>`, `[optional]` and `<variadic...>` placeholders, in argv order. */
const synopsis = (name: string, args: z.ZodObject | undefined): string =>
[
name,
...Object.entries(
(args?.shape ?? {}) as Readonly<Record<string, z.ZodType>>,
).map(([key, field]) => {
const type = typeName(field);
const label =
(type.includes("|") ? type : key) + (type === "array" ? "..." : "");
return field._zod.optout === "optional" ? `[${label}]` : `<${label}>`;
}),
].join(" ");
/** The global options an entry accepts, sorted by flag. */
const globalOptionRows = ({ formats, root }: GlobalOptionsHelp): Row[] =>
[
{
label: "--filter-output <keys>",
@@ -116,24 +159,68 @@ const globalOptionRows = ({ formats }: GlobalOptionsHelp): Row[] =>
description: "Skip first n tokens of output",
},
{ label: "--full-output", description: "Show full output envelope" },
...(root === undefined
? []
: [
{ label: "--mcp", description: "Start as MCP stdio server" },
{ label: "--update", description: "Update to latest version" },
{ label: "--version", description: "Show version" },
]),
].sort((left, right) => left.label.localeCompare(right.label));
/** Integrations, custom global options and global options, in that order. */
const globalOptionsLines = (help: GlobalOptionsHelp | undefined): string[] => {
if (help === undefined) return [];
const lines: string[] = [];
if (help.root !== undefined)
lines.push("", "Integrations:", ...commandRows(help.root.integrations));
const custom =
help.custom === undefined ? [] : optionRows(help.custom, undefined);
if (custom.length > 0)
lines.push("", "Custom Global Options:", ...alignedRows(custom));
lines.push("", "Global Options:", ...alignedRows(globalOptionRows(help)));
return lines;
};
const title = (name: string, help: CommandHelp): string => {
const heading = help.version === undefined ? name : `${name}@${help.version}`;
return help.description === undefined
? heading
: `${heading} — ${help.description}`;
};
/** Render one command's help, without a trailing newline. */
export const formatCommandHelp = (name: string, help: CommandHelp): string => {
const lines = [
help.description === undefined ? name : `${name} — ${help.description}`,
title(name, help),
"",
`Usage: ${name}${help.options === undefined ? "" : " [options]"}`,
`Usage: ${synopsis(name, help.args)}${help.options === undefined ? "" : " [options]"}`,
];
const args = Object.entries(
(help.args?.shape ?? {}) as Readonly<Record<string, z.ZodType>>,
).map(([key, field]) => ({
label: key,
description: field.description ?? "",
}));
if (args.length > 0) lines.push("", "Arguments:", ...alignedRows(args));
const options =
help.options === undefined ? [] : optionRows(help.options, help.alias);
if (options.length > 0) lines.push("", "Options:", ...alignedRows(options));
if (help.hint !== undefined) lines.push("", help.hint);
if (help.globalOptions !== undefined)
lines.push(
"",
"Global Options:",
...alignedRows(globalOptionRows(help.globalOptions)),
);
lines.push(...globalOptionsLines(help.globalOptions));
return lines.join("\n");
};
/** Render a page that lists commands (the root or a group), without a trailing newline. */
export const formatCommandListHelp = (
name: string,
help: Pick<CommandHelp, "description" | "version" | "globalOptions"> & {
readonly commands: readonly HelpCommandRow[];
},
): string => {
const lines = [title(name, help), "", `Usage: ${name} <command>`];
if (help.commands.length > 0)
lines.push("", "Commands:", ...commandRows(help.commands));
lines.push(...globalOptionsLines(help.globalOptions));
return lines.join("\n");
};