refactor(app): split session and CLI workflows
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
export const MCP_CONNECTION_LOST =
|
||||
"REA lost its MCP client connection. Restart REA from your MCP client.";
|
||||
export const MCP_CONNECTION_START_FAILED =
|
||||
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.";
|
||||
export const MCP_SHUTDOWN_FAILED =
|
||||
"REA could not close cleanly. End the REA process before starting it again.";
|
||||
export const MCP_PERMISSION_RELOAD_FAILED =
|
||||
"Reloaded permission policy failed unexpectedly";
|
||||
export const SERVER_START_FAILED =
|
||||
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.";
|
||||
@@ -0,0 +1,100 @@
|
||||
import { parseConfig } from "../config.js";
|
||||
import { readProjectPermissionStore } from "../application/ProjectPermissionStore.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { PermissionGrant } from "../domain/permissionPolicy.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { RuntimeDependencies } from "./types.js";
|
||||
import type { RuntimeState } from "./state.js";
|
||||
import { MCP_PERMISSION_RELOAD_FAILED } from "./messages.js";
|
||||
|
||||
type McpServerInstance = ReturnType<
|
||||
typeof import("../server/createServer.js").createServer
|
||||
>;
|
||||
|
||||
export const registerConfigReload = (input: {
|
||||
readonly dependencies: RuntimeDependencies;
|
||||
readonly permissionAuthority: PermissionAuthority;
|
||||
readonly runtimeState: RuntimeState;
|
||||
readonly liveServers: Set<McpServerInstance>;
|
||||
readonly serverLogger: Logger;
|
||||
}): (() => void) => {
|
||||
const {
|
||||
dependencies,
|
||||
permissionAuthority,
|
||||
runtimeState,
|
||||
liveServers,
|
||||
serverLogger,
|
||||
} = input;
|
||||
let reloadQueue = Promise.resolve();
|
||||
return (
|
||||
dependencies.registerReload?.(() => {
|
||||
const refreshed = parseConfig(dependencies.env);
|
||||
if (!refreshed.ok) {
|
||||
serverLogger.error("Reloaded permission policy is invalid");
|
||||
return;
|
||||
}
|
||||
reloadQueue = reloadQueue
|
||||
.then(async () => {
|
||||
let projectGrants: readonly PermissionGrant[] = [];
|
||||
if (
|
||||
refreshed.value.permissionProjectRoot !== undefined &&
|
||||
refreshed.value.permissionProjectStore !== undefined
|
||||
) {
|
||||
const project = await (
|
||||
dependencies.readProjectPermissionStore ??
|
||||
readProjectPermissionStore
|
||||
)(
|
||||
refreshed.value.permissionProjectStore,
|
||||
refreshed.value.permissionProjectRoot,
|
||||
);
|
||||
if (!project.ok) {
|
||||
serverLogger.error("Reloaded project grants could not be read");
|
||||
return;
|
||||
}
|
||||
projectGrants = project.value?.grants ?? [];
|
||||
}
|
||||
const reloaded = await permissionAuthority.replaceConfiguredPolicy({
|
||||
ceilings: refreshed.value.permissionCeilings,
|
||||
administratorGrants: refreshed.value.administratorPermissionGrants,
|
||||
projectGrants,
|
||||
});
|
||||
if (!reloaded.ok) {
|
||||
serverLogger.error(
|
||||
"Reloaded permission policy could not be applied",
|
||||
);
|
||||
return;
|
||||
}
|
||||
runtimeState.currentConfig = refreshed.value;
|
||||
Object.assign(
|
||||
runtimeState.processPolicy,
|
||||
refreshed.value.processExecutionPolicy,
|
||||
);
|
||||
Object.assign(
|
||||
runtimeState.evidencePolicy,
|
||||
refreshed.value.evidenceFilePolicy,
|
||||
);
|
||||
Object.assign(
|
||||
runtimeState.snapshotPolicy,
|
||||
refreshed.value.analysisSnapshotFilePolicy,
|
||||
);
|
||||
runtimeState.investigationRoots.splice(
|
||||
0,
|
||||
runtimeState.investigationRoots.length,
|
||||
...refreshed.value.investigationInputRoots,
|
||||
);
|
||||
Object.assign(
|
||||
runtimeState.javascriptReplayPolicy,
|
||||
refreshed.value.javascriptReplayPolicy,
|
||||
);
|
||||
Object.assign(
|
||||
runtimeState.managedRuntimePolicy,
|
||||
refreshed.value.managedRuntimePolicy,
|
||||
);
|
||||
for (const server of liveServers) server.sendToolListChanged();
|
||||
})
|
||||
.catch(() => {
|
||||
serverLogger.error(MCP_PERMISSION_RELOAD_FAILED);
|
||||
});
|
||||
}) ?? (() => undefined)
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
|
||||
|
||||
import type { BinarySession } from "../application/BinarySession.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { RuntimeDependencies } from "./types.js";
|
||||
import { MCP_SHUTDOWN_FAILED } from "./messages.js";
|
||||
|
||||
export const createShutdown = (input: {
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly session: BinarySession;
|
||||
readonly permissionAuthority: PermissionAuthority;
|
||||
readonly unregisterReload: () => void;
|
||||
readonly dependencies: RuntimeDependencies;
|
||||
readonly serverLogger: Logger;
|
||||
}): {
|
||||
readonly shutdown: () => Promise<void>;
|
||||
readonly request: () => void;
|
||||
} => {
|
||||
const {
|
||||
handle,
|
||||
session,
|
||||
permissionAuthority,
|
||||
unregisterReload,
|
||||
dependencies,
|
||||
serverLogger,
|
||||
} = input;
|
||||
let shutdownPromise: Promise<void> | undefined;
|
||||
let unregisterShutdown = (): void => undefined;
|
||||
const shutdown = async (): Promise<void> => {
|
||||
shutdownPromise ??= (async () => {
|
||||
unregisterReload();
|
||||
unregisterShutdown();
|
||||
await handle.close();
|
||||
await session.close();
|
||||
permissionAuthority.clearSessionGrants();
|
||||
})();
|
||||
return shutdownPromise;
|
||||
};
|
||||
const requestShutdown = (): void => {
|
||||
shutdown().catch(() => {
|
||||
dependencies.setExitCode(1);
|
||||
serverLogger.error(MCP_SHUTDOWN_FAILED);
|
||||
dependencies.writeStderr(`${MCP_SHUTDOWN_FAILED}\n`);
|
||||
});
|
||||
};
|
||||
unregisterShutdown = dependencies.registerShutdown(requestShutdown);
|
||||
return { shutdown, request: requestShutdown };
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BinarySession } from "../application/BinarySession.js";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { projectAnalysisError } from "../domain/errors.js";
|
||||
|
||||
export const openInitialTarget = async (
|
||||
session: BinarySession,
|
||||
config: AppConfig,
|
||||
serverLogger: Logger,
|
||||
writeStderr: (text: string) => void,
|
||||
): Promise<
|
||||
{ readonly ok: true } | { readonly ok: false; readonly exitCode: 1 }
|
||||
> => {
|
||||
if (config.hopperTargetPath === undefined) return { ok: true };
|
||||
const opened = await session.open(config.hopperTargetPath, {
|
||||
targetKind: config.hopperTargetKind,
|
||||
});
|
||||
if (opened.ok) return { ok: true };
|
||||
await session.close();
|
||||
serverLogger.error(
|
||||
{ errorTag: opened.error._tag },
|
||||
"Initial target failed to open",
|
||||
);
|
||||
writeStderr(`${projectAnalysisError(opened.error).message}\n`);
|
||||
return { ok: false, exitCode: 1 };
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { AppConfig } from "../config.js";
|
||||
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import type { JavaScriptReplayPolicy } from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ManagedRuntimePolicy } from "../application/ManagedRuntimeCorrelationService.js";
|
||||
|
||||
export interface RuntimeState {
|
||||
currentConfig: AppConfig;
|
||||
processPolicy: ProcessExecutionPolicy & {
|
||||
executableRoots: string[];
|
||||
workingRoots: string[];
|
||||
allowedEnvironment: string[];
|
||||
};
|
||||
evidencePolicy: EvidenceFilePolicy & { roots: string[] };
|
||||
snapshotPolicy: EvidenceFilePolicy & { roots: string[] };
|
||||
investigationRoots: string[];
|
||||
javascriptReplayPolicy: JavaScriptReplayPolicy & { roots: string[] };
|
||||
managedRuntimePolicy: ManagedRuntimePolicy & { roots: string[] };
|
||||
}
|
||||
|
||||
export const createRuntimeState = (config: AppConfig): RuntimeState => ({
|
||||
currentConfig: config,
|
||||
processPolicy: {
|
||||
...config.processExecutionPolicy,
|
||||
executableRoots: [...config.processExecutionPolicy.executableRoots],
|
||||
workingRoots: [...config.processExecutionPolicy.workingRoots],
|
||||
allowedEnvironment: [...config.processExecutionPolicy.allowedEnvironment],
|
||||
},
|
||||
evidencePolicy: {
|
||||
...config.evidenceFilePolicy,
|
||||
roots: [...config.evidenceFilePolicy.roots],
|
||||
},
|
||||
snapshotPolicy: {
|
||||
...config.analysisSnapshotFilePolicy,
|
||||
roots: [...config.analysisSnapshotFilePolicy.roots],
|
||||
},
|
||||
investigationRoots: [...config.investigationInputRoots],
|
||||
javascriptReplayPolicy: {
|
||||
...config.javascriptReplayPolicy,
|
||||
roots: [...config.javascriptReplayPolicy.roots],
|
||||
},
|
||||
managedRuntimePolicy: {
|
||||
...config.managedRuntimePolicy,
|
||||
roots: [...config.managedRuntimePolicy.roots],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
|
||||
|
||||
import type { BinarySession } from "../application/BinarySession.js";
|
||||
import type { CdpBrowserProvider } from "../browser/CdpBrowserProvider.js";
|
||||
import type { CdpElectronProvider } from "../browser/CdpElectronProvider.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { createServer } from "../server/createServer.js";
|
||||
import type { RuntimeDependencies } from "./types.js";
|
||||
import type { RuntimeState } from "./state.js";
|
||||
import {
|
||||
MCP_CONNECTION_LOST,
|
||||
MCP_CONNECTION_START_FAILED,
|
||||
} from "./messages.js";
|
||||
|
||||
type McpServerInstance = ReturnType<typeof createServer>;
|
||||
|
||||
interface ServerContext {
|
||||
readonly logger: Logger;
|
||||
readonly serverLogger: Logger;
|
||||
readonly browserObservation: CdpBrowserProvider;
|
||||
readonly electronObservation: CdpElectronProvider;
|
||||
readonly permissionAuthority: PermissionAuthority;
|
||||
readonly runtimeState: RuntimeState;
|
||||
}
|
||||
|
||||
export const startMcpTransport = async (
|
||||
dependencies: RuntimeDependencies,
|
||||
session: BinarySession,
|
||||
serverContext: ServerContext,
|
||||
): Promise<
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly handle: StdioServerHandle;
|
||||
readonly liveServers: Set<McpServerInstance>;
|
||||
}
|
||||
| { readonly ok: false }
|
||||
> => {
|
||||
const liveServers = new Set<McpServerInstance>();
|
||||
const { serverLogger } = serverContext;
|
||||
let handle: StdioServerHandle;
|
||||
try {
|
||||
handle = dependencies.serve(
|
||||
() => {
|
||||
const server = (dependencies.createServer ?? createServer)(
|
||||
session,
|
||||
session,
|
||||
{
|
||||
logger: serverContext.logger,
|
||||
processPolicy: serverContext.runtimeState.processPolicy,
|
||||
evidenceFilePolicy: serverContext.runtimeState.evidencePolicy,
|
||||
investigationInputRoots:
|
||||
serverContext.runtimeState.investigationRoots,
|
||||
analysisSnapshotFilePolicy:
|
||||
serverContext.runtimeState.snapshotPolicy,
|
||||
permissionAuthority: serverContext.permissionAuthority,
|
||||
browserObservation: serverContext.browserObservation,
|
||||
electronObservation: serverContext.electronObservation,
|
||||
artifactIntegrityContinueEnabled: () =>
|
||||
serverContext.runtimeState.currentConfig
|
||||
.artifactIntegrityContinueEnabled,
|
||||
javascriptReplayPolicy:
|
||||
serverContext.runtimeState.javascriptReplayPolicy,
|
||||
managedRuntimePolicy:
|
||||
serverContext.runtimeState.managedRuntimePolicy,
|
||||
availabilityPolicy: () => ({
|
||||
processCaptureEnabled:
|
||||
serverContext.runtimeState.currentConfig.processExecutionPolicy
|
||||
.enabled,
|
||||
evidenceFileRoots:
|
||||
serverContext.runtimeState.currentConfig.evidenceFilePolicy
|
||||
.roots.length,
|
||||
browserObservationEnabled:
|
||||
serverContext.runtimeState.currentConfig
|
||||
.browserObservationEnabled &&
|
||||
serverContext.runtimeState.currentConfig.browserCdpEndpoints
|
||||
.length > 0 &&
|
||||
serverContext.runtimeState.currentConfig.browserAllowedOrigins
|
||||
.length > 0,
|
||||
electronObservationEnabled:
|
||||
serverContext.runtimeState.currentConfig
|
||||
.electronObservationEnabled &&
|
||||
serverContext.runtimeState.currentConfig.electronCdpEndpoints
|
||||
.length > 0 &&
|
||||
serverContext.runtimeState.currentConfig.electronFileRoots
|
||||
.length > 0,
|
||||
javascriptReplayEnabled:
|
||||
serverContext.runtimeState.currentConfig.javascriptReplayPolicy
|
||||
.enabled,
|
||||
managedRuntimeEnabled:
|
||||
serverContext.runtimeState.currentConfig.managedRuntimePolicy
|
||||
.enabled,
|
||||
}),
|
||||
},
|
||||
);
|
||||
liveServers.add(server);
|
||||
return server;
|
||||
},
|
||||
{
|
||||
onerror: () => {
|
||||
serverLogger.error(MCP_CONNECTION_LOST);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_LOST}\n`);
|
||||
},
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
await session.close();
|
||||
serverLogger.error(MCP_CONNECTION_START_FAILED);
|
||||
dependencies.writeStderr(`${MCP_CONNECTION_START_FAILED}\n`);
|
||||
return { ok: false };
|
||||
}
|
||||
return { ok: true, handle, liveServers };
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export interface RuntimeDependencies {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly serve: typeof import("@modelcontextprotocol/server/stdio").serveStdio;
|
||||
readonly writeStderr: (text: string) => void;
|
||||
readonly setExitCode: (code: number) => void;
|
||||
readonly registerShutdown: (handler: () => void) => () => void;
|
||||
readonly registerReload?: (handler: () => void) => () => void;
|
||||
readonly createServer?: typeof import("../server/createServer.js").createServer;
|
||||
readonly readProjectPermissionStore?: typeof import("../application/ProjectPermissionStore.js").readProjectPermissionStore;
|
||||
}
|
||||
Reference in New Issue
Block a user