Files
reverse-engineering-anything/src/cli/argumentErrors.ts
T
morlutoandCursor Agent 2bf347dee6 fix(cli): reject invalid inline values and honor requested output on terminals (#14763)
* fix(cli): reject invalid inline values and honor requested output on terminals

- Reject inline boolean and empty number values the schema cannot accept
  instead of coercing --skill=yes to false or --limit= to 0.
- Give captured mcp add output the terminal presentation of every other
  command through one shared result destination.
- Show the unapproved setup plan whose remediation asks a terminal reader to
  review it, and open the setup rail once when a scoped run starts at approval.
- Treat --full-output and --token-count as requesting the result document, so
  setup and argument errors no longer add terminal presentation beside it.
- Answer --schema for an unknown command in the selected format, and set the
  exit code instead of exiting so piped stdout drains.

* fix(cli): keep rejected boolean and number literals across repeated flags

Binding stored one scalar value, so a later valid flag replaced an earlier
literal before the schema could reject it. Boolean and number literals the
field rejects now stay bound, including decimal unions and count options,
while repeated valid flags still use the last value. --dry-run keeps its
own error.

* test(cli): assert the terminal full-output failure envelope

The terminal --full-output regression only checked that usage text was
absent. Decode the default document and the --json envelope and require
VALIDATION_ERROR with the skill field's invalid_type error.

* test(cli): accept a counted setup approval prompt

A scoped terminal plan names every eligible action, so a Linux host that
can install Hopper asks "Apply these N changes?" rather than the singular
question. The consent helper now answers either prompt, and the rail test
finds that question before checking the intro was rendered once.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-26 12:15:17 -05:00

176 lines
5.9 KiB
TypeScript

import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
import {
CLI_DOCUMENT_OUTPUT_FORMATS,
renderCliDocument,
structuredOutputRequested,
type ParsedCliOutputArguments,
} from "./cliOutput.js";
import { estimateTokenCount } from "tokenx";
import type { CliArgvFailure, CliFieldError } from "./argvParser.js";
import type { CliCommandEntry } from "./commandRegistry.js";
import { formatCommandHelp } from "./help.js";
import { optionFlagName } from "./optionFields.js";
import { renderFailure, type CallToAction } from "./outputEnvelope.js";
const ARGUMENT_GUIDANCE =
"REA could not read the command arguments. Check the named argument and its expected type, then try again.";
export interface CliCommandFailure {
readonly code: string;
readonly message: string;
readonly retryable?: boolean;
readonly fieldErrors?: readonly (CliFieldError & {
readonly maximum?: number;
})[];
}
const adbPackageCommands = new Set([
"pull-adb-package",
"inspect-adb-package",
"uninstall-adb-package",
"start-adb-app",
"stop-adb-app",
]);
const isAdbSelector = (command: string, field: string): boolean =>
(command.includes("-adb-") && field === "serial") ||
(adbPackageCommands.has(command) && field === "package") ||
(command === "list-adb-directory" && field === "device-path") ||
(command === "resolve-adb-packages" && field === "query") ||
(["pull-adb-file", "push-adb-file"].includes(command) &&
field === "device-path") ||
(command === "start-adb-activity" &&
["action", "component", "data-uri"].includes(field)) ||
(command === "read-adb-setting" && field === "key");
/** Project the parser's retained facts, without serializing an exception cause. */
export const cliArgumentFailure = (
cli: string,
command: string,
failure: CliArgvFailure,
): CliCommandFailure => {
if (failure.kind === "dry_run" || failure.kind === "flag_spelling")
return { code: "PARSE_ERROR", message: failure.message, retryable: false };
if (failure.kind !== "validation")
return {
code: "UNKNOWN",
message:
failure.message +
(failure.kind === "surplus"
? ` Use '${cli} ${command} --help' for the declared argument shape.`
: ""),
};
return {
code: "VALIDATION_ERROR",
message: ARGUMENT_GUIDANCE,
fieldErrors: failure.fieldErrors.map((field, index) => {
const issue = failure.issues[index];
if (
!command.includes("-adb-") ||
issue === undefined ||
issue.path.length !== 1 ||
issue.path[0] !== field.path ||
issue.code !== field.code ||
!isAdbSelector(command, field.path) ||
(issue.code !== "too_big" && issue.code !== "invalid_format")
)
return field;
const projected = projectInputIssues([issue], undefined)[0];
if (projected?.maximum !== undefined)
return { ...field, maximum: projected.maximum };
return projected?.expected === "regex"
? { ...field, expected: "regex" }
: field;
}),
};
};
/** Paths and expectations remain schema facts; caller text is redacted before rendering. */
export const redactCliCommandFailure = (
failure: CliCommandFailure,
values: readonly string[],
): CliCommandFailure => ({
...failure,
message: redactExplicitText(failure.message, values),
...(failure.fieldErrors === undefined
? {}
: {
fieldErrors: failure.fieldErrors.map((field) => ({
...field,
received: redactExplicitText(field.received, values),
message: redactExplicitText(field.message, values),
})),
}),
});
const validationUsage = (
cli: string,
entry: CliCommandEntry,
fields: NonNullable<CliCommandFailure["fieldErrors"]>,
): string => {
const lines = fields.map((field) => {
const [head, ...tail] = field.path.split(".");
const option =
head !== undefined && entry.definition.options?.shape[head] !== undefined;
const label = option
? `--${optionFlagName(head!)}${tail.length === 0 ? "" : `.${tail.join(".")}`}`
: `<${field.path}>`;
return field.missing
? `Error: missing required ${option ? "option" : "argument"} ${label}`
: `Error: invalid value for ${label}: ${field.message}`;
});
return [
...lines,
"See below for usage.",
"",
formatCommandHelp(`${cli} ${entry.name}`, {
...entry.definition,
globalOptions: { formats: CLI_DOCUMENT_OUTPUT_FORMATS },
}),
].join("\n");
};
/** Preserve ordinary-command diagnostic presentation while removing SDK middleware. */
export const renderCliCommandFailure = (
failure: CliCommandFailure,
input: {
readonly cli: string;
readonly entry: CliCommandEntry;
readonly duration: string;
readonly stdoutIsTerminal: boolean;
readonly controls: ParsedCliOutputArguments;
readonly cta?: CallToAction | undefined;
},
): string => {
const { controls, stdoutIsTerminal, cta } = input;
const human = stdoutIsTerminal && !controls.formatExplicit;
// Usage text is terminal presentation; a requested document or count wins.
if (
human &&
!structuredOutputRequested(controls) &&
failure.fieldErrors !== undefined
)
return `${validationUsage(input.cli, input.entry, failure.fieldErrors)}\n`;
const format =
controls.format === "csv" || controls.format === "tsv"
? "json"
: controls.format;
// Preserve the ordinary command's established count policy. JSONL errors
// remain diagnostic records; the common renderer owns their framing.
if (controls.tokenCount && format !== "jsonl")
return `${estimateTokenCount(renderCliDocument(failure, format, stdoutIsTerminal))}\n`;
return renderFailure(
failure,
{ command: input.entry.name, duration: input.duration },
cta,
{
format,
human,
fullOutput: controls.fullOutput,
tokenCount: false,
tokenLimit: controls.tokenLimit,
tokenOffset: controls.tokenOffset,
},
);
};