mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 05:51:06 +00:00
Resolve bare REA launchers using the registration's effective PATH and verify the resulting installation before setup or uninstall changes an entry. Share the parsed environment through registration workflows and keep unproven launchers unknown. Cover npm shim lookup on Windows and use deterministic ownership fixtures for layered removal. Fixes #15026. Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
479 lines
17 KiB
TypeScript
479 lines
17 KiB
TypeScript
import type {
|
|
OwnedProviderSetting,
|
|
RecordedProviderSettings,
|
|
} from "../ports/DesktopBuildHost.js";
|
|
import {
|
|
validateRegistrationEnvironment,
|
|
type ValidatedRegistrationEnvironment,
|
|
} from "./RegistrationEnvironmentValidation.js";
|
|
import {
|
|
clientRegistrationSource,
|
|
gooseEnvironmentField,
|
|
} from "./ClientRegistrationSource.js";
|
|
import type { SetupClient } from "./SupportedClients.js";
|
|
import type { ClientRegistrationCommandLookup } from "./ClientRegistrationIdentity.js";
|
|
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
|
|
import { launchAnalysisSetting } from "../config/analysisSettings.js";
|
|
import {
|
|
DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS,
|
|
DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
|
|
} from "../domain/analysisResourceLimits.js";
|
|
import { ConfigurationError } from "../domain/configurationErrors.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import {
|
|
clientConfigurationEnvironmentKey,
|
|
effectiveClientServer,
|
|
type ClientConfigurationDocument,
|
|
} from "./ClientConfigurationDocument.js";
|
|
import { clientConfigurationRecordSchema } from "./ClientConfigurationValues.js";
|
|
import { PRODUCT_IDENTITY } from "../identity.js";
|
|
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
|
import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js";
|
|
import { dshDocument } from "./DshCordisPatch.js";
|
|
import { mergeRegistrationEnvironment } from "./UserConfigurationLocation.js";
|
|
import type { McpToolTimeoutInputs } from "../config/mcpStartupPolicy.js";
|
|
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
|
|
|
|
export interface ProviderRequestBudgetResolver {
|
|
(
|
|
analysisProvider: AnalysisProviderSelector,
|
|
environment: Readonly<Record<string, string>>,
|
|
): Promise<Result<number | undefined, ConfigurationError>>;
|
|
/**
|
|
* Settings needed for the provider and lookup selected by the literals.
|
|
* An unresolved expression blocks that lookup when it could change its
|
|
* inputs. An omitted declaration keeps the fail-closed whole-environment gate.
|
|
*/
|
|
readonly budgetSettings?: (
|
|
analysisProvider: AnalysisProviderSelector,
|
|
environment: Readonly<Record<string, string>>,
|
|
) => ReadonlySet<string>;
|
|
}
|
|
|
|
export interface ClientRegistrationEnvironmentDetails {
|
|
readonly values: Readonly<Record<string, string>>;
|
|
/** The platform-admitted keys used for launch setting and budget lookup. */
|
|
readonly runtimeEnvironment: Readonly<Record<string, string>>;
|
|
readonly configHomeFallbackApplied?: true;
|
|
readonly unresolvedSettings: ReadonlySet<string>;
|
|
readonly timeoutInputs: McpToolTimeoutInputs | undefined;
|
|
}
|
|
|
|
interface ResolvedClientRegistrationEnvironmentDetails extends ClientRegistrationEnvironmentDetails {
|
|
readonly timeoutInputs: McpToolTimeoutInputs;
|
|
}
|
|
|
|
const TIMEOUT_INPUT_SETTINGS: ReadonlySet<string> = new Set([
|
|
"REA_ANALYSIS_PROVIDER",
|
|
"REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS",
|
|
"REA_GHIDRA_STARTUP_TIMEOUT_MS",
|
|
"REA_HOPPER_STARTUP_TIMEOUT_MS",
|
|
"REA_JEB_MCP_TIMEOUT_MS",
|
|
]);
|
|
|
|
const environmentSchema = clientConfigurationRecordSchema.transform(
|
|
(values, context) => {
|
|
const entries: [string, string][] = [];
|
|
for (const [key, value] of Object.entries(values)) {
|
|
if (typeof value === "string") entries.push([key, value]);
|
|
else
|
|
context.addIssue({
|
|
code: "custom",
|
|
path: [key],
|
|
message: "Environment values must be strings",
|
|
});
|
|
}
|
|
return Object.fromEntries(entries);
|
|
},
|
|
);
|
|
|
|
/** Invalid recorded shape, with literal environment keys kept for source attribution. */
|
|
export class ClientRegistrationEnvironmentShapeError extends ConfigurationError {
|
|
constructor(
|
|
field: string,
|
|
readonly invalidKeys: readonly string[],
|
|
) {
|
|
super("Invalid REA server environment", {
|
|
settings: (invalidKeys.length === 0
|
|
? [field]
|
|
: invalidKeys.map((key) => `${field}.${key}`)
|
|
).map((setting) => ({
|
|
setting,
|
|
constraint:
|
|
"Server environment must be an object containing only string values",
|
|
})),
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Clients that expand `$VAR` and `${VAR}` in a recorded `env` value from the
|
|
* environment the client itself runs with.
|
|
*
|
|
* REA does not replicate that expansion — it would have to predict a child's
|
|
* environment — but it must not report the literal text as the value either, or
|
|
* a consumer that searches for an inherited `PATH` searches for a literal
|
|
* `${PATH}` entry instead.
|
|
*/
|
|
const VAR_EXPANDING_CLIENTS: ReadonlySet<string> = new Set(["qwen_code"]);
|
|
|
|
/** Recorded setting names whose value is an expression, not a literal. */
|
|
const expressionSettings = (
|
|
clientName: string | undefined,
|
|
values: Readonly<Record<string, string>>,
|
|
): ReadonlySet<string> =>
|
|
clientName !== undefined && VAR_EXPANDING_CLIENTS.has(clientName)
|
|
? new Set(
|
|
Object.entries(values)
|
|
.filter(([, value]) =>
|
|
/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[A-Za-z_][A-Za-z0-9_]*\})/u.test(
|
|
value,
|
|
),
|
|
)
|
|
.map(([name]) => name),
|
|
)
|
|
: new Set();
|
|
|
|
/** Admission of the recorded strings alone, shared by ownership and readiness. */
|
|
const readRecordedEnvironment = (
|
|
registration: unknown,
|
|
profile: SetupClient["registrationProfile"] | undefined,
|
|
key: ClientConfigurationDocument["environmentKey"],
|
|
): Result<Readonly<Record<string, string>>, ConfigurationError> => {
|
|
const source = clientRegistrationSource(registration, profile);
|
|
const field =
|
|
key === "envs" ? gooseEnvironmentField(source.connection) : ok(key);
|
|
if (!field.ok) return field;
|
|
const raw = source.connection?.[field.value];
|
|
const existing = environmentSchema.safeParse(raw === undefined ? {} : raw);
|
|
if (!existing.success)
|
|
return err(
|
|
new ClientRegistrationEnvironmentShapeError(
|
|
source.nested ? `transport.${field.value}` : field.value,
|
|
existing.error.issues.flatMap(({ path: [key] }) =>
|
|
typeof key === "string" ? [key] : [],
|
|
),
|
|
),
|
|
);
|
|
return ok(existing.data);
|
|
};
|
|
|
|
/** A recorded PATH overrides the inherited PATH if its value is literal. */
|
|
export const clientRegistrationCommandLookup = (
|
|
value: unknown,
|
|
client: SetupClient,
|
|
inherited: Readonly<NodeJS.ProcessEnv> = process.env,
|
|
key?: ClientConfigurationDocument["environmentKey"],
|
|
): ClientRegistrationCommandLookup => {
|
|
if (client.format === "unsupported") return { unresolvedPath: true };
|
|
const recorded = readRecordedEnvironment(
|
|
value,
|
|
client.registrationProfile,
|
|
key ?? clientConfigurationEnvironmentKey(client.format ?? "json"),
|
|
);
|
|
if (!recorded.ok) return { unresolvedPath: true };
|
|
const platform = HOST_PLATFORM.platform;
|
|
return {
|
|
environment: mergeEnvironmentOverrides(inherited, recorded.value, platform),
|
|
unresolvedPath: [...expressionSettings(client.name, recorded.value)].some(
|
|
(name) =>
|
|
platform === "win32" ? name.toLowerCase() === "path" : name === "PATH",
|
|
),
|
|
};
|
|
};
|
|
|
|
/** Read explicit REA overrides without dropping peers when one value is invalid. */
|
|
export const clientRegistrationEnvironment = (
|
|
parsed: ClientConfigurationDocument | undefined,
|
|
client: Pick<SetupClient, "name" | "registrationProfile"> | undefined,
|
|
platform: NodeJS.Platform,
|
|
overrides: Readonly<Record<string, string>> = {},
|
|
validation: "fragment" | "effective" = "effective",
|
|
): Result<Readonly<Record<string, string>>, ConfigurationError> => {
|
|
const details = clientRegistrationEnvironmentDetails(
|
|
parsed,
|
|
client,
|
|
platform,
|
|
overrides,
|
|
validation,
|
|
);
|
|
return details.ok ? ok(details.value.values) : details;
|
|
};
|
|
|
|
/** Retain original strings and the parser-owned timeout facts. */
|
|
export const clientRegistrationEnvironmentDetails = (
|
|
parsed: ClientConfigurationDocument | undefined,
|
|
client: Pick<SetupClient, "name" | "registrationProfile"> | undefined,
|
|
platform: NodeJS.Platform,
|
|
overrides: Readonly<Record<string, string>> = {},
|
|
validation: "fragment" | "effective" = "effective",
|
|
): Result<ClientRegistrationEnvironmentDetails, ConfigurationError> => {
|
|
if (parsed?.dialect === "dsh") {
|
|
const environment = dshDocument(parsed.document).environment(
|
|
overrides,
|
|
validation,
|
|
platform,
|
|
);
|
|
if (!environment.ok) return environment;
|
|
return ok(environmentDetails(environment.value.values, environment.value));
|
|
}
|
|
const registration =
|
|
parsed === undefined
|
|
? undefined
|
|
: effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
|
|
const existing = readRecordedEnvironment(
|
|
registration,
|
|
client?.registrationProfile,
|
|
parsed?.environmentKey ?? "env",
|
|
);
|
|
if (!existing.ok) return existing;
|
|
// Validate known settings with the runtime's parser, but retain the original
|
|
// string overrides, including unknown client-specific keys and no defaults.
|
|
const merged = mergeRegistrationEnvironment(
|
|
existing.value,
|
|
overrides,
|
|
platform,
|
|
);
|
|
const validated = validatedDetails(
|
|
merged.values,
|
|
validation,
|
|
platform,
|
|
expressionSettings(client?.name, merged.values),
|
|
);
|
|
return validated.ok && merged.configHomeFallbackApplied === true
|
|
? ok({ ...validated.value, configHomeFallbackApplied: true })
|
|
: validated;
|
|
};
|
|
|
|
/** Consume a resolved setting inside its reader without including its value in diagnostics. */
|
|
export type ProviderSettingObserver = (name: string, value: string) => void;
|
|
|
|
/**
|
|
* Compare settings selected in this process with a registration's own file.
|
|
* The server's environment also depends on what its client passes on, which is
|
|
* not observable here, so a gap is never a claim about the effective value.
|
|
* Returns only names: recorded values stay in the file that owns them.
|
|
*/
|
|
export const recordedProviderSettings = (
|
|
parsed: ClientConfigurationDocument,
|
|
client: Pick<SetupClient, "name" | "registrationProfile"> | undefined,
|
|
selected: Readonly<Record<string, string>>,
|
|
platform: NodeJS.Platform,
|
|
owns?: OwnedProviderSetting,
|
|
observe?: ProviderSettingObserver,
|
|
): RecordedProviderSettings | undefined => {
|
|
const selection = mergeEnvironmentOverrides({}, selected, platform);
|
|
const names = Object.keys(selection).sort(compareUnicodeCodePoints);
|
|
const identity = (name: string): string =>
|
|
platform === "win32" ? name.toUpperCase() : name;
|
|
if (names.length === 0) return undefined;
|
|
const details = clientRegistrationEnvironmentDetails(
|
|
parsed,
|
|
client,
|
|
platform,
|
|
{},
|
|
"fragment",
|
|
);
|
|
if (!details.ok) return { unrecorded: [], differing: [], unresolved: names };
|
|
const { runtimeEnvironment: recorded, unresolvedSettings } = details.value;
|
|
const isUnresolved = (name: string): boolean =>
|
|
unresolvedSettings.has(identity(name));
|
|
for (const name of names) {
|
|
const value = recorded[identity(name)];
|
|
if (value !== undefined && !isUnresolved(name)) observe?.(name, value);
|
|
}
|
|
const facts = {
|
|
unrecorded: names.filter(
|
|
(name) => recorded[identity(name)] === undefined && !isUnresolved(name),
|
|
),
|
|
differing: names.filter(
|
|
(name) =>
|
|
!isUnresolved(name) &&
|
|
recorded[identity(name)] !== undefined &&
|
|
recorded[identity(name)] !== selection[name],
|
|
),
|
|
unresolved: names.filter(isUnresolved),
|
|
};
|
|
const owned = names.filter((name) => {
|
|
const value = recorded[identity(name)];
|
|
return value !== undefined && owns?.(name, value) === true;
|
|
});
|
|
return facts.unrecorded.length +
|
|
facts.differing.length +
|
|
facts.unresolved.length +
|
|
owned.length ===
|
|
0
|
|
? undefined
|
|
: { ...facts, ...(owned.length === 0 ? {} : { owned }) };
|
|
};
|
|
|
|
/** Resolve the async provider-specific budget through its retained reader owner. */
|
|
export const clientRegistrationEnvironmentDetailsWithBudget = async (
|
|
parsed: ClientConfigurationDocument | undefined,
|
|
client: Pick<SetupClient, "name" | "registrationProfile"> | undefined,
|
|
overrides: Readonly<Record<string, string>>,
|
|
validation: "fragment" | "effective",
|
|
resolveProviderRequestBudget: ProviderRequestBudgetResolver | undefined,
|
|
platform: NodeJS.Platform,
|
|
): Promise<
|
|
Result<ResolvedClientRegistrationEnvironmentDetails, ConfigurationError>
|
|
> => {
|
|
const details = clientRegistrationEnvironmentDetails(
|
|
parsed,
|
|
client,
|
|
platform,
|
|
overrides,
|
|
validation,
|
|
);
|
|
if (!details.ok) return details;
|
|
// The budget gate stays fail-closed: settings the resolver may read must be
|
|
// literals, and an undeclared read set keeps every unresolved expression
|
|
// blocking, because an unreadable budget cannot be treated as absent.
|
|
const { timeoutInputs, runtimeEnvironment } = details.value;
|
|
const budgetSettings =
|
|
timeoutInputs === undefined
|
|
? undefined
|
|
: resolveProviderRequestBudget?.budgetSettings?.(
|
|
timeoutInputs.analysisProvider,
|
|
runtimeEnvironment,
|
|
);
|
|
const unresolved = [...details.value.unresolvedSettings].filter(
|
|
(setting) =>
|
|
TIMEOUT_INPUT_SETTINGS.has(setting) ||
|
|
(timeoutInputs !== undefined &&
|
|
resolveProviderRequestBudget !== undefined &&
|
|
(budgetSettings === undefined || budgetSettings.has(setting))),
|
|
);
|
|
if (timeoutInputs === undefined || unresolved.length > 0)
|
|
return err(
|
|
new ConfigurationError(
|
|
"Cannot derive a provider request budget from expression-backed settings",
|
|
{
|
|
settings: unresolved.map((setting) => ({
|
|
setting,
|
|
constraint:
|
|
"Resolve this setting to a literal before deriving a request budget",
|
|
})),
|
|
},
|
|
),
|
|
);
|
|
const resolved = { ...details.value, timeoutInputs };
|
|
if (resolveProviderRequestBudget === undefined) return ok(resolved);
|
|
return validatedBudget(resolved, resolveProviderRequestBudget);
|
|
};
|
|
|
|
const validatedDetails = (
|
|
environment: Readonly<Record<string, string>>,
|
|
validation: "fragment" | "effective",
|
|
platform: NodeJS.Platform,
|
|
expressionSettings: ReadonlySet<string>,
|
|
): Result<ClientRegistrationEnvironmentDetails, ConfigurationError> => {
|
|
const validated = validateRegistrationEnvironment(
|
|
environment,
|
|
expressionSettings,
|
|
validation,
|
|
platform,
|
|
);
|
|
return validated.ok
|
|
? ok(environmentDetails(environment, validated.value))
|
|
: validated;
|
|
};
|
|
|
|
const admittedTimeout = (
|
|
id: Parameters<typeof launchAnalysisSetting>[0],
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
fallback: number,
|
|
): number => {
|
|
const parsed = launchAnalysisSetting(id, environment);
|
|
return parsed.ok && parsed.value.value !== null
|
|
? parsed.value.value
|
|
: fallback;
|
|
};
|
|
|
|
const registrationTimeoutInputs = (
|
|
environment: Readonly<Record<string, string>>,
|
|
): Pick<
|
|
McpToolTimeoutInputs,
|
|
| "ghidraStartupTimeoutMs"
|
|
| "hopperStartupTimeoutMs"
|
|
| "ghidraDecompileTimeoutMs"
|
|
| "jebMcpTimeoutMs"
|
|
> => {
|
|
const decompile = launchAnalysisSetting(
|
|
"ghidra.decompile_timeout_seconds",
|
|
environment,
|
|
);
|
|
const jeb = launchAnalysisSetting("jeb.mcp_timeout_ms", environment);
|
|
return {
|
|
ghidraStartupTimeoutMs: admittedTimeout(
|
|
"ghidra.startup_timeout_ms",
|
|
environment,
|
|
DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS,
|
|
),
|
|
hopperStartupTimeoutMs: admittedTimeout(
|
|
"hopper.startup_timeout_ms",
|
|
environment,
|
|
DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
|
|
),
|
|
...(decompile.ok &&
|
|
decompile.value.source === "setting" &&
|
|
decompile.value.value !== null
|
|
? { ghidraDecompileTimeoutMs: decompile.value.value * 1000 }
|
|
: {}),
|
|
...(jeb.ok &&
|
|
jeb.value.source === "setting" &&
|
|
jeb.value.value !== null &&
|
|
environment.REA_JEB_MCP_TIMEOUT_MS !== undefined
|
|
? { jebMcpTimeoutMs: jeb.value.value }
|
|
: {}),
|
|
};
|
|
};
|
|
|
|
const environmentDetails = (
|
|
environment: Readonly<Record<string, string>>,
|
|
{
|
|
configuration,
|
|
runtimeEnvironment,
|
|
unresolvedSettings,
|
|
}: ValidatedRegistrationEnvironment,
|
|
): ClientRegistrationEnvironmentDetails => ({
|
|
values: Object.fromEntries(
|
|
Object.entries(environment).sort(([left], [right]) =>
|
|
compareUnicodeCodePoints(left, right),
|
|
),
|
|
),
|
|
runtimeEnvironment,
|
|
unresolvedSettings,
|
|
timeoutInputs: [...unresolvedSettings].some((setting) =>
|
|
TIMEOUT_INPUT_SETTINGS.has(setting),
|
|
)
|
|
? undefined
|
|
: {
|
|
analysisProvider: configuration.REA_ANALYSIS_PROVIDER,
|
|
...registrationTimeoutInputs(runtimeEnvironment),
|
|
},
|
|
});
|
|
|
|
const validatedBudget = async (
|
|
details: ResolvedClientRegistrationEnvironmentDetails,
|
|
resolveProviderRequestBudget: ProviderRequestBudgetResolver,
|
|
): Promise<
|
|
Result<ResolvedClientRegistrationEnvironmentDetails, ConfigurationError>
|
|
> => {
|
|
const providerBudget = await resolveProviderRequestBudget(
|
|
details.timeoutInputs.analysisProvider,
|
|
details.runtimeEnvironment,
|
|
);
|
|
if (!providerBudget.ok) return providerBudget;
|
|
return ok({
|
|
...details,
|
|
timeoutInputs: {
|
|
...details.timeoutInputs,
|
|
...(providerBudget.value === undefined
|
|
? {}
|
|
: { providerRequestTimeoutMs: providerBudget.value }),
|
|
},
|
|
});
|
|
};
|