Files
reverse-engineering-anything/src/cli/outputEnvelope.ts
T
a10037ef10 refactor(cli): report unknown commands and the update notice from REA (#11692)
* 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

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.

* refactor(cli): report unknown commands and the update notice from REA

src/cli/updateNotice.ts owns the terminal update notice: the same trigger (terminal stdout, no explicit format), text, cache file ($XDG_CACHE_HOME/incur/updates/<package>.json), daily detached refresh through rea --incur-update-check, and opt-outs (NO_UPDATE_NOTIFIER, npm_config_update_notifier=false, CI). Discovery answers the detached refresh first, and reports an unknown command with incur's Did-you-mean suggestion, corrected invocation, help command and notice, as text on a terminal or as the error document, full-output envelope, token count or token window otherwise. outputEnvelope.ts renders these dispatcher failures.

Unknown commands with --format md stay with incur pending the Markdown escaping decision on #11654. Compared with incur's serve, 224 of 224 unknown-command invocations are identical, piped and on a terminal with a due notice.

* fix(cli): redact unknown-command guidance before rendering

Share the producing reply boundary for root lookup, unknown schemas and MCP subcommands. Preserve ordinary argument identity and existing MCP suggestion policies; omit sensitive or unsafe replay commands and redact full-output command metadata.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

---------

Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-16 14:46:48 +08:00

145 lines
5.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* The failure envelope, its terminal rendering and the token window of
* dispatcher-written documents are adapted from Incur's CLI output.
* 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 { estimateTokenCount, sliceByTokens } from "tokenx";
import type { CliOutputFormat } from "../cliOutput.js";
import { formatCliOutput } from "./cliOutputFormatter.js";
/** Suggested commands that follow a document. */
export interface CallToAction {
readonly description: string;
readonly commands: readonly {
readonly command: string;
readonly description?: string;
}[];
}
export interface CliFailure {
readonly code: string;
readonly message: string;
}
/** How the caller asked for a dispatcher-written document. */
export interface EnvelopePresentation {
readonly format: Exclude<CliOutputFormat, "csv" | "tsv">;
/** A terminal without an explicit format: plain text for a person. */
readonly human: boolean;
readonly fullOutput: boolean;
readonly tokenCount: boolean;
readonly tokenLimit: number | undefined;
readonly tokenOffset: number | undefined;
}
/** `Error: message`, or `Error (CODE): message` for codes other than lookup failures. */
const humanError = ({ code, message }: CliFailure): string =>
`${code === "UNKNOWN" || code === "COMMAND_NOT_FOUND" ? "Error" : `Error (${code})`}: ${message}`;
/** A blank line, the description, then each command with its aligned comment. */
const humanCallToAction = ({ description, commands }: CallToAction): string => {
const width = Math.max(...commands.map(({ command }) => command.length));
return [
"",
description,
...commands.map(
({ command, description: comment }) =>
` ${command}${comment === undefined ? "" : ` ${"".padEnd(width - command.length)}# ${comment}`}`,
),
].join("\n");
};
/** One line of output: a trailing newline unless the text already ends with one. */
const line = (text: string): string =>
text.endsWith("\n") ? text : `${text}\n`;
const tokenWindow = (
text: string,
{ tokenLimit, tokenOffset }: EnvelopePresentation,
):
| { readonly truncated: false; readonly text: string }
| {
readonly truncated: true;
readonly text: string;
readonly nextOffset: number | undefined;
} => {
if (tokenLimit === undefined && tokenOffset === undefined)
return { truncated: false, text };
const total = estimateTokenCount(text);
const offset = tokenOffset ?? 0;
const end = tokenLimit === undefined ? total : offset + tokenLimit;
if (offset === 0 && end >= total) return { truncated: false, text };
const shown = Math.min(end, total);
return {
truncated: true,
text: `${sliceByTokens(text, offset, end)}\n[truncated: showing tokens ${offset}–${shown} of ${total}]`,
nextOffset: shown < total ? shown : undefined,
};
};
/**
* Render a failure the dispatcher reports itself, such as an unknown command.
* A person on a terminal reads the error and the suggested commands as text;
* otherwise the error and its suggestions form one document, or the
* `--full-output` envelope, in the chosen format and token window.
*/
export const renderFailure = (
failure: CliFailure,
{
command,
duration,
}: { readonly command: string; readonly duration: string },
cta: CallToAction,
presentation: EnvelopePresentation,
): string => {
if (presentation.human && !presentation.fullOutput)
return line(humanError(failure)) + line(humanCallToAction(cta));
const { format } = presentation;
if (presentation.tokenCount)
return line(String(estimateTokenCount(formatCliOutput(failure, format))));
const meta = { command, cta, duration };
if (presentation.fullOutput) {
const window = tokenWindow(formatCliOutput(failure, format), presentation);
return line(
formatCliOutput(
window.truncated
? {
ok: false,
error: window.text,
meta: {
...meta,
...(window.nextOffset === undefined
? {}
: { nextOffset: window.nextOffset }),
},
}
: { ok: false, error: failure, meta },
format,
),
);
}
return line(
tokenWindow(formatCliOutput({ ...failure, cta }, format), presentation)
.text,
);
};