mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* refactor(browser): take the host in Chromium, Electron and capture adapters chromiumSandboxEnabled and safeElectronEnvironment take a required platform. The scenario browser, native module resolver, Electron provider and capture cleanup, mitmproxy adapter and web script artifacts take an optional platform seam (default HOST_PLATFORM); Electron fuses read the host architecture from HOST_PLATFORM. Their tests inject the platform instead of redefining process.platform. src/browser no longer reads process.platform or process.arch. * refactor(pcap): take the host platform in the packet tools, native bound and batch launch (#11141) * refactor(pcap): take the host platform in the packet tools, native bound and batch launch * test(pcap): cover the selected host in batch launch and capture-host support * refactor(apktool): take the host platform in launcher selection, version probe and decode (#11164) * refactor(apktool): take the host platform in launcher selection, version probe and decode * test(apktool): cover the provider's selected host in launcher selection * refactor(hopper): give the launcher the provider's host platform * refactor(native): inject the host into the pwntools decoders and native capability defaults (#11173) * refactor(native): inject the host into the pwntools decoders and native capability defaults * fix(native): give composed pwntools services the capability host and drop empty test hooks * refactor(adb): take the host platform in binary selection and pulled file names (#11176) * refactor(adb): take the host platform in binary selection and pulled file names * refactor(cli): pass the resolved host platform through rea mcp add (#11179) * refactor(cli): pass the resolved host platform through rea mcp add * refactor(composition): default composition entry points to HOST_PLATFORM and pass it to Hopper and IDA (#11183) * refactor(kuna): require the host platform in admission and installation, and give it to the session client (#11186) * refactor(kuna): require the host platform in admission and installation, and give it to the session client * fix(kuna): pass the host platform from the JavaScript installation callers verify-real-kuna, both native oracle helpers and the command-lifetime child script call inspectKunaInstallation from dist, where TypeScript cannot see the now-required platform. They passed undefined and got unsupported_host on supported hosts. * refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM (#11203) * refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM createServer read process.platform and process.arch live for its capability services, and registerSessionTools read process.platform for process capture. A host option (default HOST_PLATFORM) now selects both, and composition passes the capability host to the sigrok provider and the EVM provider (execution gate, limiter probe and environment rules), as it does for pwntools. hostRestrictedAvailabilityMcp selects its host through the option instead of redefining process.platform and process.arch, and moves to the MCP boundary lane since it no longer touches process-global state. evmCleanupRetry passes SIMULATED_LINUX_X64 to the provider instead of 52 property redefinitions; the fixture moves to tests/fixtures/simulatedHost.ts. * refactor(desktop): require the host platform in build computer and secret folder paths (#11210) * refactor(desktop): require the host platform in build computer and secret folder paths buildComputerArchiveDirectory, defaultBuildComputerArchive, resolveBuildComputerEnvironment and buildSecretsDirectory defaulted to process.platform. Every caller but DesktopBuildComputers' secret folder already passed the platform; it now passes HOST_PLATFORM.platform, which it reads for the build environment. * refactor(filesystem): default caller paths and ChangeTime settling to HOST_PLATFORM (#11212) appendCallerPath, absoluteCallerPath and the ChangeTime settle seams defaulted to a live process.platform read. Their defaults now come from HOST_PLATFORM: the 59 callers that omit the platform join or settle paths they open on this host, and callers describing another host's layout already pass it. The webScriptExport case that redefined process.platform to reach the Windows settle budget moves to its own file, which selects Windows by mocking HostPlatform. * fix(server): report process capture availability for the server's host sessionAvailabilityPolicy imported platform from node:process, so with a selected host binary_session reported capture_process_scenario from the running host while planning and capture used the selected one. It takes the platform from createServer and registerSessionTools. hostRestrictedAvailabilityMcp checks discovery against a dry-run plan on win32 and linux hosts. * build(guards): count platform and arch imports from node:process and node:os as ambient host reads sessionAvailabilityPolicy's named import of platform from node:process escaped the ambient-host-platform guard. The guards now also match named platform/arch imports from node:process or node:os and os.platform()/os.arch(). The one other site, DesktopApplicationCapture's os.arch(), records the capturing host and now reads HOST_PLATFORM.architecture. * refactor(config): take the host platform in parseConfig and give debugger managers the capability host (#11237) * refactor(config): take the host platform in parseConfig and give debugger managers the capability host parseConfig read process.platform for the default Hopper launcher; it takes the platform (default HOST_PLATFORM). GdbSessionManager and RizinDebugSessionManager default their platform to HOST_PLATFORM, and composition passes the capability host that already decides their availability. GDB's /proc descriptor check reads HOST_PLATFORM explicitly: it inspects this host's /proc whatever host the manager models. * refactor(firmware): give the firmware and Wakaru providers the capability host (#11239) * refactor(firmware): give the firmware and Wakaru providers the capability host resolveFirmwareCommand and resolveWakaruCommand read process.platform (and process.arch) for their host gate. They take the platform or host as a parameter; FirmwareProvider and WakaruProvider take a host (default HOST_PLATFORM) for the gate and their environment snapshots, and composition passes the capability host that already decides their availability. The JavaScript analysis source transfer defaults to HOST_PLATFORM. artifactSelectedCommand passes SIMULATED_LINUX_X64 to both providers instead of redefining process.platform and process.arch, and the Wakaru limiter configuration cases now run on any POSIX host. * refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM (#11240) * refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM TsharkCaptureProvider and CutterBridgeClient defaulted their platform to process.platform. Both default to HOST_PLATFORM now, and composition passes the capability host to the packet capture service, which already decides its availability. * refactor(platform): read HOST_PLATFORM explicitly in host-only path checks (#11241) * refactor(platform): read HOST_PLATFORM explicitly in host-only path checks Electron's readlink target split, IDA's host path comparison, the inspector's reported runtime path, the server identity check and WABT's executable names all describe paths on the running host. They read HOST_PLATFORM instead of process.platform. * test(native): select the native UI verifier's host through HostPlatform (#11242) verify-native-ui.mjs reads its macOS requirement from HOST_PLATFORM, and its action test resolves the script's HostPlatform import to a simulated darwin host instead of redefining process.platform in the child preload. Simulating linux there fails the macOS requirement, so the redirect is effective. * test(mcp): check that composition forwards the selected host to execution hostRestrictedAvailabilityMcp ran execution only on darwin, where the runner's own host also refuses. The new case calls the firmware, Wakaru, tshark, sigrok and EVM tools under a darwin and a linux x64 host and requires different outcomes, so dropping a provider's host forwarding fails on any runner (checked by removing the firmware forwarding). * fix(composition): give the pcap, Apktool and ADB providers the capability host createServer's selected host decided pcap capture discovery, but the default pcap, Apktool and ADB factories built their providers with HOST_PLATFORM. The factories take the platform (default HOST_PLATFORM) and capabilityServices passes its context platform, so availability and execution follow one host. * test: import moved resources owners in host-platform fixtures * refactor(config): drop the unused host parameter from parseConfig
443 lines
13 KiB
TypeScript
443 lines
13 KiB
TypeScript
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
import { Writable } from "node:stream";
|
|
|
|
import { Help, z } from "incur";
|
|
|
|
import {
|
|
mcpClientRegistrationWritten,
|
|
registerMcpClients,
|
|
type McpClientRegistrationOutcome,
|
|
} from "../application/McpClientRegistration.js";
|
|
import {
|
|
resolveMcpRegistrationClients,
|
|
type McpRegistrationClient,
|
|
} from "../application/McpRegistrationCatalog.js";
|
|
import { runningClientRewriteNotice } from "../application/SupportedClients.js";
|
|
import {
|
|
ArtifactReaderFailure,
|
|
ArtifactResourceScope,
|
|
} from "../resources/index.js";
|
|
import {
|
|
classifyMcpAddDiscovery,
|
|
declaredSensitiveValues,
|
|
readMcpAddArguments,
|
|
splitIncurBuiltinArguments,
|
|
} from "../cliBuiltinArguments.js";
|
|
import {
|
|
parseCliOutputArguments,
|
|
renderCliDocument,
|
|
renderCliOutputArgumentError,
|
|
type CliOutputArgumentValidation,
|
|
} from "../cliOutput.js";
|
|
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
|
import {
|
|
mcpRegistrationOptionsSchema,
|
|
mcpRegistrationReportSchema,
|
|
type McpRegistrationReport,
|
|
} from "../contracts/mcpRegistration.js";
|
|
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
|
import {
|
|
parseClientRegistrationCommand,
|
|
type ClientRegistrationCommand,
|
|
type ClientRegistrationCommandIssue,
|
|
} from "../domain/clientRegistrationCommand.js";
|
|
import { ConfigurationError } from "../domain/configurationErrors.js";
|
|
import { redactExplicitText } from "../domain/explicitSensitiveValues.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import { PRODUCT_IDENTITY } from "../identity.js";
|
|
import { createCliResultOutput } from "./cliResultOutput.js";
|
|
import { withCommandCancellation } from "./commandCancellation.js";
|
|
import type { CliInstance } from "./types.js";
|
|
import { ownCliProcessResource } from "./cliResources.js";
|
|
|
|
let retainedResources: ArtifactResourceScope | undefined;
|
|
|
|
/** Close the exact registration cleanup owners, retaining failures for retry. */
|
|
export const closeCliMcpRegistrationResources = async (): Promise<void> => {
|
|
const resources = retainedResources;
|
|
if (resources === undefined) return;
|
|
await resources.close();
|
|
if (retainedResources === resources) retainedResources = undefined;
|
|
};
|
|
|
|
ownCliProcessResource("mcp-registration", closeCliMcpRegistrationResources);
|
|
|
|
type ServeOptions = NonNullable<Parameters<CliInstance["serve"]>[1]>;
|
|
interface RegistrationRequest {
|
|
readonly agents: readonly string[];
|
|
readonly global: boolean;
|
|
readonly launcher: ClientRegistrationCommand;
|
|
}
|
|
interface RegistrationInputIssue {
|
|
readonly code: "invalid_value" | "unsupported_transport";
|
|
readonly message: string;
|
|
readonly field: string;
|
|
}
|
|
interface RegistrationPresentation {
|
|
write(text: string): void;
|
|
document(value: unknown, failure?: boolean): Promise<void>;
|
|
validation(
|
|
message: string,
|
|
field: string,
|
|
error?: AnalysisError,
|
|
code?: RegistrationInputIssue["code"],
|
|
): Promise<void>;
|
|
fail(): void;
|
|
}
|
|
|
|
const precedingFlags = [
|
|
"--llms",
|
|
"--llms-full",
|
|
"--mcp",
|
|
"--update",
|
|
"--incur-update-check",
|
|
];
|
|
|
|
/** Route only the named REA registration operation; other Incur commands remain theirs. */
|
|
export const serveMcpRegistration = (
|
|
arguments_: readonly string[],
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
defaultCommand: Result<
|
|
ClientRegistrationCommand,
|
|
ClientRegistrationCommandIssue
|
|
>,
|
|
options: ServeOptions,
|
|
): Promise<void> | undefined => {
|
|
const split = splitIncurBuiltinArguments(arguments_);
|
|
const offset = split.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0;
|
|
if (
|
|
split.command[offset] !== "mcp" ||
|
|
split.command[offset + 1] !== "add" ||
|
|
precedingFlags.some((flag) => split.flags.has(flag))
|
|
)
|
|
return undefined;
|
|
return (async () => {
|
|
const presentation = createRegistrationPresentation(
|
|
arguments_,
|
|
split.command,
|
|
options,
|
|
);
|
|
if (
|
|
presentation === undefined ||
|
|
(await serveRegistrationDiscovery(split.flags, presentation))
|
|
)
|
|
return Promise.resolve();
|
|
const request = readRegistrationRequest(
|
|
split.command.slice(offset + 2),
|
|
defaultCommand,
|
|
);
|
|
if (!request.ok) {
|
|
await presentation.validation(
|
|
request.error.message,
|
|
request.error.field,
|
|
undefined,
|
|
request.error.code,
|
|
);
|
|
return Promise.resolve();
|
|
}
|
|
return withCommandCancellation((signal) =>
|
|
executeRegistration(request.value, environment, signal, presentation),
|
|
);
|
|
})();
|
|
};
|
|
|
|
/** Bind one invocation's rendering, explicit redaction and exit behavior. */
|
|
const createRegistrationPresentation = (
|
|
arguments_: readonly string[],
|
|
command: readonly string[],
|
|
options: ServeOptions,
|
|
): RegistrationPresentation | undefined => {
|
|
const write =
|
|
options.stdout ?? ((text: string) => process.stdout.write(text));
|
|
const fail = () => {
|
|
if (options.exit !== undefined) options.exit(1);
|
|
else process.exitCode = 1;
|
|
};
|
|
const output = parseCliOutputArguments(arguments_);
|
|
const validation: CliOutputArgumentValidation =
|
|
output.validation.ok && (output.format === "csv" || output.format === "tsv")
|
|
? {
|
|
ok: false,
|
|
format: "json",
|
|
code: "UNSUPPORTED_OUTPUT_COMBINATION",
|
|
message:
|
|
"MCP registration returns a complete document. Use --format json, yaml, md, toon, or jsonl; CSV/TSV requires a selected row collection.",
|
|
}
|
|
: output.validation;
|
|
if (!validation.ok) {
|
|
write(renderCliOutputArgumentError(validation));
|
|
fail();
|
|
return undefined;
|
|
}
|
|
const destination =
|
|
options.stdout === undefined
|
|
? process.stdout
|
|
: new Writable({
|
|
write(chunk: Buffer, _encoding, callback) {
|
|
try {
|
|
write(chunk.toString());
|
|
callback();
|
|
} catch (error) {
|
|
callback(
|
|
error instanceof Error ? error : new Error(String(error)),
|
|
);
|
|
}
|
|
},
|
|
});
|
|
const result = createCliResultOutput(output, destination);
|
|
const document = async (value: unknown, failure = false) => {
|
|
const handled = await result?.write(value, {
|
|
command: "mcp add",
|
|
duration: "0ms",
|
|
format: output.format,
|
|
forceOutput: true,
|
|
failure,
|
|
});
|
|
if (!handled)
|
|
write(
|
|
renderCliDocument(value, output.format, process.stdout.isTTY === true),
|
|
);
|
|
if (result?.error !== undefined) fail();
|
|
};
|
|
return {
|
|
write,
|
|
document,
|
|
fail,
|
|
async validation(message, field, error, code = "invalid_value") {
|
|
const retained = redactExplicitText(
|
|
message,
|
|
declaredSensitiveValues(command),
|
|
);
|
|
await document(
|
|
{
|
|
code: "VALIDATION_ERROR",
|
|
message: retained,
|
|
...(error === undefined
|
|
? {}
|
|
: { error: projectAnalysisError(error) }),
|
|
fieldErrors: [
|
|
{
|
|
code,
|
|
missing: false,
|
|
path: field,
|
|
message: retained,
|
|
},
|
|
],
|
|
},
|
|
true,
|
|
);
|
|
fail();
|
|
},
|
|
};
|
|
};
|
|
|
|
/** Discovery never resolves configuration locations or acquires resource owners. */
|
|
const serveRegistrationDiscovery = async (
|
|
flags: ReadonlySet<string>,
|
|
presentation: RegistrationPresentation,
|
|
): Promise<boolean> => {
|
|
if (flags.has("--help") || flags.has("-h")) {
|
|
presentation.write(
|
|
`${Help.formatCommand("rea mcp add", {
|
|
description:
|
|
"Register exact stdio launcher arguments in selected client settings, with backups and verified publication.",
|
|
options: mcpRegistrationOptionsSchema,
|
|
alias: { command: "c" },
|
|
hint: "No package acquisition or server execution. --no-global never writes global settings.",
|
|
})}\n`,
|
|
);
|
|
return true;
|
|
}
|
|
const discovery = classifyMcpAddDiscovery(flags);
|
|
if (discovery === "version") {
|
|
presentation.write(`${PRODUCT_IDENTITY.packageVersion}\n`);
|
|
return true;
|
|
}
|
|
if (discovery !== "schema") return false;
|
|
await presentation.document({
|
|
inputSchema: z.toJSONSchema(mcpRegistrationOptionsSchema),
|
|
outputSchema: z.toJSONSchema(mcpRegistrationReportSchema),
|
|
});
|
|
return true;
|
|
};
|
|
|
|
const readRegistrationRequest = (
|
|
arguments_: readonly string[],
|
|
defaultCommand: Result<
|
|
ClientRegistrationCommand,
|
|
ClientRegistrationCommandIssue
|
|
>,
|
|
): Result<RegistrationRequest, RegistrationInputIssue> => {
|
|
const request = readMcpAddArguments(arguments_);
|
|
if (!request.validation.ok) {
|
|
const issue = request.validation.error;
|
|
return err({
|
|
code: "invalid_value",
|
|
message:
|
|
issue.kind === "missing_value"
|
|
? `Missing value for flag: ${issue.flag}`
|
|
: `Unexpected argument: ${issue.token}`,
|
|
field: issue.kind === "missing_value" ? issue.field : "arguments",
|
|
});
|
|
}
|
|
const launcher =
|
|
request.commandText === undefined
|
|
? defaultCommand
|
|
: parseClientRegistrationCommand(request.commandText);
|
|
return launcher.ok
|
|
? ok({
|
|
agents: request.agents,
|
|
global: request.global,
|
|
launcher: launcher.value,
|
|
})
|
|
: err({
|
|
code:
|
|
launcher.error.kind === "unsupported_transport"
|
|
? "unsupported_transport"
|
|
: "invalid_value",
|
|
message: launcher.error.message,
|
|
field: "command",
|
|
});
|
|
};
|
|
|
|
const executeRegistration = async (
|
|
request: RegistrationRequest,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
signal: AbortSignal,
|
|
presentation: RegistrationPresentation,
|
|
): Promise<void> => {
|
|
const resources = (retainedResources ??= new ArtifactResourceScope());
|
|
const outcomes = await resources
|
|
.run(async () => {
|
|
const { platform } = HOST_PLATFORM;
|
|
const targets = await resolveMcpRegistrationClients(
|
|
{
|
|
agents: request.agents,
|
|
global: request.global,
|
|
cwd: process.cwd(),
|
|
home: homeDirectoryFromEnvironment(environment, platform),
|
|
platform,
|
|
environment,
|
|
signal,
|
|
},
|
|
resources,
|
|
);
|
|
if (!targets.ok) {
|
|
await presentation.validation(
|
|
targets.error.message,
|
|
"agent",
|
|
targets.error,
|
|
);
|
|
return undefined;
|
|
}
|
|
return {
|
|
targets: targets.value,
|
|
outcomes: await registerMcpClients(
|
|
targets.value,
|
|
request.launcher,
|
|
signal,
|
|
resources,
|
|
platform,
|
|
),
|
|
};
|
|
})
|
|
.catch(async (cause: unknown) => {
|
|
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
|
|
const error = new ConfigurationError(
|
|
"Registration cannot continue until retained resource cleanup completes.",
|
|
{
|
|
cause,
|
|
cleanup: ArtifactReaderFailure.cleanupObservation(
|
|
cause,
|
|
resources.cleanupResources,
|
|
),
|
|
},
|
|
);
|
|
await presentation.validation(error.message, "registration", error);
|
|
return undefined;
|
|
});
|
|
if (outcomes !== undefined)
|
|
await presentRegistration(
|
|
outcomes.outcomes,
|
|
outcomes.targets,
|
|
request.launcher,
|
|
presentation,
|
|
);
|
|
};
|
|
|
|
const clientReport = (
|
|
outcome: McpClientRegistrationOutcome,
|
|
): McpRegistrationReport["clients"][number] => {
|
|
const labels = {
|
|
client: outcome.client,
|
|
config_path: outcome.configPath,
|
|
scope: outcome.scope,
|
|
};
|
|
if (outcome.status === "not_started")
|
|
return { ...labels, status: "not_started" };
|
|
if (!outcome.result.ok)
|
|
return {
|
|
...labels,
|
|
status: "failed",
|
|
error: {
|
|
...projectAnalysisError(outcome.result.error),
|
|
reason: outcome.result.error.message,
|
|
},
|
|
};
|
|
const receipt = outcome.result.value;
|
|
const permissions =
|
|
receipt.permissions === undefined
|
|
? {}
|
|
: { permissions: receipt.permissions };
|
|
return receipt.status === "unchanged"
|
|
? { ...labels, ...permissions, status: "unchanged" }
|
|
: {
|
|
...labels,
|
|
...permissions,
|
|
status: "configured",
|
|
...(receipt.backupPath === undefined
|
|
? {}
|
|
: { backup_path: receipt.backupPath }),
|
|
};
|
|
};
|
|
|
|
const presentRegistration = async (
|
|
outcomes: readonly McpClientRegistrationOutcome[],
|
|
targets: readonly McpRegistrationClient[],
|
|
launcher: ClientRegistrationCommand,
|
|
presentation: RegistrationPresentation,
|
|
): Promise<void> => {
|
|
const clients = outcomes.map(clientReport);
|
|
const report: McpRegistrationReport = {
|
|
name: "rea",
|
|
command: launcher.command,
|
|
args: [...launcher.args],
|
|
ok: clients.every(
|
|
(client) =>
|
|
client.status === "configured" || client.status === "unchanged",
|
|
),
|
|
clients,
|
|
};
|
|
await presentation.document(report, !report.ok);
|
|
for (const outcome of outcomes) {
|
|
if (outcome.status !== "completed") continue;
|
|
const target = targets.find(
|
|
({ id, configPath }) =>
|
|
id === outcome.client && configPath === outcome.configPath,
|
|
);
|
|
const name = target?.displayName ?? outcome.client;
|
|
const { result } = outcome;
|
|
if (result.ok && result.value.backupPath !== undefined)
|
|
process.stderr.write(
|
|
`${name} MCP registration backup retained at ${result.value.backupPath}\n`,
|
|
);
|
|
const notice =
|
|
mcpClientRegistrationWritten(result) && target?.setupClient !== undefined
|
|
? runningClientRewriteNotice(target.setupClient)
|
|
: undefined;
|
|
if (notice !== undefined) process.stderr.write(`${notice}\n`);
|
|
}
|
|
if (!report.ok) presentation.fail();
|
|
};
|