mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
Run ordinary CLI commands through REA's registry, argv parser and result owner. Remove Incur, the second admission parse, SDK error middleware, output capture and redundant command traversal. Preserve explicit redaction, publication receipts, incremental output, terminal notice eligibility and drain ownership. Migrate fixtures to real registrations and retain the derived-source notices. Validation includes unchanged public parity goldens, public and lifecycle regressions, repaired fixture consumers, real TTY base comparisons, exports beyond the engine string limit, four schema catalogs and final static/docs checks. Native provider and optional validator coverage limits are in the PR. Fixes #11654. Fixes #10583. Refs #11682, #11476 and #10511. BREAKING CHANGE: Markdown argument diagnostics use REA's literal escaping, table widths and token counts. Flag-shaped unknown MCP subcommands honor the selected format. Completion --schema/--version routes use the canonical REA-owned hook rather than the retired SDK generator. Refresh affected literal snapshots and regenerate completion hooks with rea completions <shell>. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
170 lines
6.1 KiB
TypeScript
170 lines
6.1 KiB
TypeScript
import type { Writable } from "node:stream";
|
|
|
|
import {
|
|
cliCompletionShell,
|
|
isProjectScopedAmpRegistration,
|
|
parseCliGlobalArguments,
|
|
} from "./cliBuiltinArguments.js";
|
|
import {
|
|
cliConfigurationError,
|
|
parseCliOutputArguments,
|
|
readCliOutputArguments,
|
|
renderCliOutputArgumentError,
|
|
renderEmptyFilteredCliOutput,
|
|
renderVersionReport,
|
|
} from "./cliOutput.js";
|
|
import type { VersionReportHost } from "./domain/versionReport.js";
|
|
|
|
/**
|
|
* Process facilities one command needs. The executable binds them to its own
|
|
* streams and exit; a driver that serves several commands from one process
|
|
* binds them to per-command capture.
|
|
*/
|
|
export interface OneShotCliHost {
|
|
readonly environment: NodeJS.ProcessEnv;
|
|
readonly runtime: VersionReportHost;
|
|
readonly stdoutIsTerminal: boolean;
|
|
/** Destination for result documents the command streams itself. */
|
|
readonly resultDestination: Writable;
|
|
/** Status reported after a recovered failure when the reader has closed stdout. */
|
|
readonly closedStdoutStatus: number;
|
|
writeStdout(text: string): void;
|
|
writeStderr(text: string): void;
|
|
stdoutClosed(): boolean;
|
|
/** Status the process would report if it ended now. */
|
|
exitCode(): number;
|
|
setExitCode(code: number): void;
|
|
/** Called once when the command runtime loads, before any command runs. */
|
|
ownCliResources(close: () => Promise<void>): void;
|
|
/**
|
|
* The command asked to end the process with `code`. The host owns that
|
|
* exit and must drain `finishOutput` after closing the owned resources.
|
|
*/
|
|
exit(code: number, finishOutput: () => Promise<void>): void;
|
|
/** Whether `exit` has run. Its host then owns the pending result write. */
|
|
exitRequested(): boolean;
|
|
}
|
|
|
|
const AMP_PROJECT_SCOPE_REFUSAL =
|
|
"Amp does not support project-scoped registration. Run without --no-global to register Amp globally, or select a client with project settings. No client settings were changed.";
|
|
|
|
/**
|
|
* Run one CLI command: admit its output arguments and configuration, answer
|
|
* the documents that need no command runtime, then dispatch. Failures the
|
|
* command did not report propagate to the host.
|
|
*/
|
|
export const runOneShotCli = async (
|
|
arguments_: readonly string[],
|
|
host: OneShotCliHost,
|
|
): Promise<void> => {
|
|
// Completion words are transport data, including partial output flags.
|
|
const global =
|
|
cliCompletionShell(host.environment) === undefined
|
|
? parseCliGlobalArguments(arguments_)
|
|
: undefined;
|
|
const cliArguments = global?.arguments ?? arguments_;
|
|
const outputOptions =
|
|
global === undefined
|
|
? parseCliOutputArguments([])
|
|
: readCliOutputArguments(global);
|
|
const outputArguments = outputOptions.validation;
|
|
// `--version` with an explicit format reports the runtime as a document;
|
|
// plain `--version` stays a bare version string.
|
|
const versionOutput = renderVersionReport(
|
|
outputOptions,
|
|
host.runtime,
|
|
host.stdoutIsTerminal,
|
|
);
|
|
const configurationError = cliConfigurationError(host.environment);
|
|
// Doctor is the readiness report for this failure. Other commands still stop
|
|
// here so they do not run with an unusable log level.
|
|
if (
|
|
configurationError !== undefined &&
|
|
(global === undefined || global.command[0] !== "doctor")
|
|
) {
|
|
host.writeStderr(`${configurationError}\n`);
|
|
host.setExitCode(1);
|
|
return;
|
|
}
|
|
if (!outputArguments.ok) {
|
|
host.writeStdout(renderCliOutputArgumentError(outputArguments));
|
|
host.setExitCode(1);
|
|
return;
|
|
}
|
|
if (versionOutput !== undefined) {
|
|
host.writeStdout(versionOutput);
|
|
return;
|
|
}
|
|
if (global !== undefined && isProjectScopedAmpRegistration(global)) {
|
|
// Amp has global settings only. Share the parsed scope fact with the
|
|
// registration workflow and refuse before loading the command runtime.
|
|
//
|
|
// A caller that asked for a structured document gets the refusal in
|
|
// that document, through the same pre-execution error renderer the
|
|
// output-argument branch uses; anything else keeps the plain message.
|
|
const refusalFormat = outputOptions.format;
|
|
if (
|
|
refusalFormat === "json" ||
|
|
refusalFormat === "jsonl" ||
|
|
refusalFormat === "yaml"
|
|
) {
|
|
host.writeStdout(
|
|
renderCliOutputArgumentError({
|
|
format: refusalFormat,
|
|
code: "AMP_PROJECT_SCOPE_UNSUPPORTED",
|
|
message: AMP_PROJECT_SCOPE_REFUSAL,
|
|
}),
|
|
);
|
|
} else {
|
|
host.writeStderr(`${AMP_PROJECT_SCOPE_REFUSAL}\n`);
|
|
}
|
|
host.setExitCode(1);
|
|
return;
|
|
}
|
|
|
|
// Loaded only now: the documents above answer without the command catalog.
|
|
const { loadCliRuntime } = await import("./cli/cliLoader.js");
|
|
const runtime = await loadCliRuntime(global, host.environment);
|
|
host.ownCliResources(runtime.closeCliResources);
|
|
const { createCliResultOutput } = await import("./cli/cliResultOutput.js");
|
|
let wroteOutput = false;
|
|
const resultOutput = createCliResultOutput(
|
|
outputOptions,
|
|
host.resultDestination,
|
|
);
|
|
try {
|
|
await runtime.createCli(resultOutput).serve([...cliArguments], {
|
|
stdout: (output) => {
|
|
if (resultOutput?.handled) {
|
|
if (resultOutput.failed && !host.stdoutClosed())
|
|
host.writeStderr(output);
|
|
return;
|
|
}
|
|
if (output.length > 0) wroteOutput = true;
|
|
host.writeStdout(output);
|
|
},
|
|
exit: (code) => {
|
|
host.exit(typeof code === "number" ? code : 0, async () =>
|
|
resultOutput?.finish(),
|
|
);
|
|
},
|
|
});
|
|
} catch (cause) {
|
|
if (wroteOutput) throw cause;
|
|
const recovered = await resultOutput
|
|
?.recoverFormattingFailure(cause)
|
|
.catch((writeFailure: unknown) => {
|
|
// Recovery writes outside the command boundary. A reader that
|
|
// declined this document keeps the same quiet closed-pipe outcome.
|
|
if (!host.stdoutClosed()) throw writeFailure;
|
|
return true;
|
|
});
|
|
if (!recovered) throw cause;
|
|
host.setExitCode(host.stdoutClosed() ? host.closedStdoutStatus : 1);
|
|
}
|
|
if (!wroteOutput && !resultOutput?.handled)
|
|
host.writeStdout(renderEmptyFilteredCliOutput(outputOptions) ?? "");
|
|
// A requested exit is finished by the host, which owns its pending write.
|
|
if (!host.exitRequested()) await resultOutput?.finish();
|
|
};
|