Files
reverse-engineering-anything/src/cli/cliShell.ts
T
8d6552e928 feat(config): persist provider settings in a user config file (#3023)
* feat(config): persist provider settings in a user config file

Providers currently rediscover install paths from scratch in every
process, so a path set once (for example GHIDRA_INSTALL_DIR) silently
reverts on the next run. Introduce ~/.config/rea/rea.json as the
user-owned persistence layer and merge it into the environment
snapshot before configuration parsing, keeping env > config file >
auto-detect precedence on both the CLI and MCP entry points.

Add a rea config command (list/get/set/unset) as the write surface,
reporting the effective value and where it came from.

* fix(config): address review findings on persistence safety and CLI surface

- stage config writes beside the file and rename into place so an
  interrupted write cannot leave partial JSON (greptile #4, codex #11)
- convert unreadable config files into configuration errors on the CLI
  seam instead of escaping raw filesystem errors (greptile #5, codex #15)
- keep injected runtimes without a config root isolated from the host
  account's rea.json (codex #18)
- surface the config file error on stderr when doctor falls back to the
  raw environment (greptile #3, codex #16)
- route the config command through logCliCommand and return documents so
  --json stays parseable and failures exit non-zero (greptile #2,
  codex #10)
- reject empty --set values, unknown --set/--unset/--get names, and --get
  combined with mutations (greptile #1/#7, codex #9/#12/#13/#17)
- cover the new behavior in the boundary tests and stop leaking one
  temporary home per run (greptile #8)

* fix(config): validate and back up persisted provider settings

* fix(config): keep saved provider defaults out of client registrations

* fix(config): preserve provider discovery and budgets for saved settings

* fix(config): check only settings needed by the IDA deadline lookup

* fix(config): share effective provider settings and verify config file reads

* fix(doctor): share selected settings with Hopper and ILSpy probes

* fix(config): resolve the destination of first-time saves

* fix(doctor): preserve unresolved provider location inputs

* fix(doctor): honor inherited IDA deadline overrides

* fix(config): show empty environment overrides

* fix(setup): preserve client-selected saved configuration roots

---------

Co-authored-by: Jackzigen <zigenhan@gmail.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-21 22:02:35 +00:00

147 lines
5.0 KiB
TypeScript

import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js";
import { parseCliGlobalArguments } from "../cliBuiltinArguments.js";
import type { DirectAnalysis } from "../composition/directAnalysis.js";
import { parseLogLevel } from "../config/processStart.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { createLogger } from "../logger.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import type {
CliCommandRegistration,
CliRegistrationContext,
} from "./cliCommandRegistration.js";
import type { CliResultOutput } from "./cliResultOutput.js";
import { runCliCommand } from "./runCliCommand.js";
import { completionHelpNote, createCliCompletions } from "./completions.js";
import { serveDiscovery } from "./discovery.js";
import { reportUnknownMcpSubcommand } from "./mcpBuiltinCommands.js";
import { serveMcpRegistration } from "./mcpRegistration.js";
import { presentOmittableDefaults } from "./omittableDefaults.js";
import type { CliInstance, CliServeOptions } from "./types.js";
/** A registrar and the module it was loaded from. */
export interface LoadedCliCommandRegistration {
readonly registration: CliCommandRegistration;
readonly module: unknown;
}
export interface CliShellOptions {
readonly selectedEnvironment: Readonly<Record<string, string | undefined>>;
readonly savedDefaults?: ReadonlySet<string> | undefined;
/** Registrars to run, in registration order. */
readonly registrations: readonly LoadedCliCommandRegistration[];
/** Required when any registrar declares analysis. */
readonly createAnalysis?: (
environment: Readonly<Record<string, string | undefined>>,
) => DirectAnalysis;
readonly resultOutput?: CliResultOutput | undefined;
readonly fridaInstrumentation?: FridaInstrumentationPort | undefined;
}
/** Run each registrar, creating analysis once for those that declare it. */
const registerCommands = (
context: CliRegistrationContext,
options: CliShellOptions,
): void => {
let analysis: DirectAnalysis | undefined;
for (const { registration, module } of options.registrations) {
if (!registration.analysis) {
registration.register(module, context);
continue;
}
if (options.createAnalysis === undefined)
throw new Error("A CLI registrar needs analysis that was not provided");
analysis ??= options.createAnalysis(context.environment);
registration.register(module, { ...context, analysis });
}
};
/**
* Build REA's CLI around the given registrars. Identity, global options,
* argument policy, completions, and registration builtins are the same for
* every set of registrars; they apply to whichever commands were registered.
*/
export const createCliShell = (options: CliShellOptions): CliInstance => {
const environment = snapshotEnvironment(
options.selectedEnvironment,
HOST_PLATFORM.platform,
);
// The executable reports an invalid level before every command except doctor.
// Doctor keeps going so its readiness report can name REA_LOG_LEVEL.
const level =
environment.REA_LOG_LEVEL === undefined
? undefined
: parseLogLevel(environment.REA_LOG_LEVEL);
const logger = createLogger(
"cli",
level?.ok === true ? level.value : "silent",
);
const cli: CliInstance = {
name: PRODUCT_IDENTITY.cliBinary,
serve,
};
registerCommands(
{
cli,
logger,
environment,
savedDefaults: options.savedDefaults,
fridaInstrumentation: options.fridaInstrumentation,
},
options,
);
presentOmittableDefaults(cli);
const updateEnvironment = {
variables: environment,
platform: HOST_PLATFORM.platform,
};
const completions = createCliCompletions(cli, environment);
function serve(
arguments_: readonly string[] = process.argv.slice(2),
serveOptions?: CliServeOptions,
): Promise<void> {
if (completions.complete(arguments_, serveOptions ?? {}))
return Promise.resolve();
const global = parseCliGlobalArguments(arguments_);
if (completions.writeScript(global, serveOptions ?? {}))
return Promise.resolve();
const registration = serveMcpRegistration(
global,
environment,
serveOptions ?? {},
);
if (registration !== undefined) return registration;
const result = reportUnknownMcpSubcommand(
cli.name,
global,
serveOptions ?? {},
)
? Promise.resolve()
: (serveDiscovery(
cli,
global.arguments,
serveOptions ?? {},
updateEnvironment,
global,
) ??
runCliCommand(
cli,
global,
serveOptions ?? {},
updateEnvironment,
options.resultOutput,
));
const note = completionHelpNote(global);
if (note === undefined) return result;
return result.then(() => {
const write =
serveOptions?.stdout ?? ((text: string) => process.stdout.write(text));
write(`\n${note}`);
});
}
return cli;
};