Files
reverse-engineering-anything/src/application/DirectAnalysis.ts
T
morluto 81fe44d7d8 refactor(evidence): build a completed provider operation's Evidence in one owner (#11673)
* test(adapters): compare CLI and MCP Evidence for every CLI analysis operation

Run each official, workflow, native, artifact and managed operation that
has a CLI command through the CLI command tree and the MCP server over
one simulated provider, and require identical Evidence or failure. The
differences main has today are recorded per operation so the W2 invoke
path can only remove them.

Split bindDirectAnalysis(dependencies) out of createDirectAnalysis so the
CLI can run over injected session owners.

* test(adapters): give each parity case its own CLI and MCP connection

* refactor(evidence): build a completed provider operation's Evidence in one owner

The CLI's DirectAnalysis and the MCP provider-operation handler each
defaulted the subject, admitted the completed analysis and created the
Evidence. completedOperationEvidence in SessionEvidenceReuse now does it
for both, reusing the record the session issued for the same execution
and parameters. The session-Evidence lookup is no longer exported.

* test(evidence): deliver the record a one-shot Ghidra decompile session issued
2026-11-15 22:25:52 -05:00

979 lines
33 KiB
TypeScript

import {
admitOneShotOperation,
type DirectAnalysisTool,
} from "./oneShotOperationInput.js";
import { completedOperationEvidence } from "./binary/SessionEvidenceReuse.js";
import type { EspFlashSelection } from "../domain/firmware/espFlashLocation.js";
import type { ExecutableFormatHint } from "../domain/dosCom.js";
import { dispatchQueuedInterrupts } from "../process/queuedInterrupts.js";
import type {
BinaryArchitecture,
BinaryTarget,
} from "../domain/binaryTargetTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
import type { BinarySession } from "./binary/BinarySession.js";
import type { SessionProviderRoute } from "./binary/SessionProviderRouter.js";
import {
routeAllowsSnapshotReplay,
routeProviderIdentity,
} from "./binary/SessionProviderPolicy.js";
import type { ResolvedSessionOpen } from "./binary/BinarySessionOpen.js";
import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import { withEvidenceCallerInputPath } from "../domain/evidence.js";
import { createImmutableEvidenceBundle } from "../domain/evidenceBundle.js";
import { recognizeEvidence } from "../domain/evidenceValidation.js";
import {
retainAnalysisResultSources,
type AnalysisResultWithSources,
} from "./investigation/recordEvidenceSources.js";
import {
createInvestigationEvidenceClosureChecker,
collectInvestigationEvidenceClosure,
} from "./investigation/InvestigationEvidence.js";
import type { Evidence } from "../domain/evidence.js";
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import {
ARTIFACT_ANALYSIS_OPERATIONS,
type ArtifactAnalysisOperation,
} from "../contracts/artifactToolContracts.js";
import {
isManagedToolName,
type ManagedToolName,
} from "../contracts/managed/managedToolContracts.js";
import {
EvidenceFileError,
AnalysisSnapshotMismatchError,
type PublishedEvidenceFile,
} from "../domain/evidenceErrors.js";
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { access, stat } from "node:fs/promises";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import {
requestsFreshIndependentDecompile,
requiresNativeSourceAdmissionBeforeReplay,
} from "./binary/AnalysisSnapshotCache.js";
import {
snapshotBindingMismatch,
snapshotEvidenceForQuery,
} from "../domain/analysisSnapshot.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import { profilelessNativeDispatchProfile } from "./binary/ProfilelessNativeWorkflowSnapshot.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisExecution } from "../ports/AnalysisProvider.js";
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
import { REA_WORKFLOW_PROVIDER } from "../domain/investigationProviders.js";
import { workflowAnalysisProfile } from "./WorkflowAnalysisProfile.js";
import {
composedLimitationBudget,
executeComposedWorkflow,
createWorkflowEvidence,
retainPartialWorkflowEvidence,
workflowSnapshotRecord,
recordWorkflowUnknowns,
} from "./WorkflowEvidence.js";
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
import { resolveXrefsAddress } from "./XrefsAddressResolution.js";
import {
AnalysisInputError,
cancelledBy,
CallerAbort,
} from "../domain/analysisErrorCore.js";
import type { BinaryTargetError } from "../domain/configurationErrors.js";
import {
directAnalysisCleanupFailure,
projectDirectAnalysisFailure,
projectInvocationFailure,
managedAnalysisCleanupFailure,
withSessionCleanup,
} from "./DirectAnalysisCleanup.js";
import { completeProviderEvidence } from "./ProviderOperationExecution.js";
import { BUNDLE_RESOURCE_OPERATIONS } from "../ports/BundleResourceOperations.js";
import { classifyBinaryTargetFilesystemFailure } from "../domain/binaryTargetFilesystemFailure.js";
// These one-shot CLI questions require native utilities, not a deep engine.
// Runtime observation retains the ordinary session and authority checks.
const NATIVE_INSPECTION_OPERATIONS: ReadonlySet<string> = new Set([
"inspect_macho",
"inspect_signature",
"list_architectures",
"inspect_plist",
"demangle_swift",
] satisfies readonly NativeToolName[]);
const ARTIFACT_ANALYSIS_OPERATION_SET: ReadonlySet<string> = new Set(
ARTIFACT_ANALYSIS_OPERATIONS,
);
/**
* Open one binary, execute one tool, and always release provider resources.
* Unlike MCP mode, every CLI invocation is intentionally isolated and does not
* retain a target, provider session or runtime setting for a subsequent
* command. Failures are projected for that invocation lifetime, so they never
* offer same-session reuse or runtime updates; a new invocation's launch
* environment or arguments carry any changed limit.
*/
export const runDirectAnalysis = async (
dependencies: DirectAnalysisDependencies,
path: string,
tool: DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
options: {
readonly logger?: Logger;
readonly snapshotPath?: string | undefined;
readonly signal?: AbortSignal;
readonly providerId?: AnalysisProviderSelector;
readonly formatHint?: ExecutableFormatHint;
readonly architecture?: BinaryArchitecture;
readonly entryPoint?: string;
readonly espFlash?: EspFlashSelection;
readonly includeEvidenceSources?: boolean;
} = {},
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> =>
withProcessCancellation(options.signal, (signal) => {
const admitted = admitOneShotOperation(tool, arguments_, signal);
if (!admitted.ok)
return Promise.resolve(err(cliError(admitted.error, path)));
return runAnalysis(
dependencies,
path,
admitted.value.name,
admitted.value.input,
{
evidenceParameters: arguments_,
logger: options.logger ?? silentLogger,
snapshotPath: options.snapshotPath,
signal,
...(options.includeEvidenceSources === true
? { includeEvidenceSources: true }
: {}),
...targetSelection(options),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
},
);
});
/** How the caller asks an artifact target to be read. */
export interface ArtifactTargetSelection {
readonly formatHint?: ExecutableFormatHint;
readonly espFlash?: EspFlashSelection;
}
/** The caller's target interpretation, forwarded unchanged to every open. */
const targetSelection = (options: {
readonly formatHint?: ExecutableFormatHint;
readonly architecture?: BinaryArchitecture;
readonly entryPoint?: string;
readonly espFlash?: EspFlashSelection;
}) => ({
...(options.formatHint === undefined
? {}
: { formatHint: options.formatHint }),
...(options.architecture === undefined
? {}
: { architecture: options.architecture }),
...(options.entryPoint === undefined
? {}
: { entryPoint: options.entryPoint }),
...(options.espFlash === undefined ? {} : { espFlash: options.espFlash }),
});
/** Execute one provider-native semantic operation with atomic provenance. */
export const runProviderAnalysis = async (
dependencies: DirectAnalysisDependencies,
...[path, tool, arguments_, logger = silentLogger, signal, selection]:
| readonly [
path: string,
tool: NativeToolName | ArtifactAnalysisOperation | ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger?: Logger | undefined,
signal?: AbortSignal | undefined,
]
| readonly [
path: string,
tool: ArtifactAnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
logger: Logger | undefined,
signal: AbortSignal | undefined,
selection: ArtifactTargetSelection,
]
): Promise<Result<Evidence, JsonValue>> =>
withProcessCancellation(signal, async (operationSignal) => {
// Preserve the selected path and original arguments as request facts.
const evidenceParameters = { ...arguments_, input_path: path };
if (isManagedToolName(tool)) {
const evidence = await managedCallerEvidence(
dependencies,
path,
tool,
arguments_,
operationSignal,
);
// Completed Evidence already carries the caller's path.
return evidence.ok ? evidence : err(cliError(evidence.error, path));
}
const admitted = admitOneShotOperation(tool, arguments_, operationSignal);
if (!admitted.ok) return err(cliError(admitted.error, path));
return runAnalysis(
dependencies,
path,
admitted.value.name,
admitted.value.input,
{
logger,
snapshotPath: undefined,
signal: operationSignal,
evidenceParameters,
...targetSelection(selection ?? {}),
...(ARTIFACT_ANALYSIS_OPERATION_SET.has(tool)
? { createSession: dependencies.createArtifactBinarySession }
: NATIVE_INSPECTION_OPERATIONS.has(tool)
? { createSession: dependencies.createNativeBinarySession }
: {}),
},
);
});
/**
* Run one managed operation on a caller-selected path, keeping its typed
* failure so a composed command can retain earlier Evidence beside it.
*/
export const runManagedProviderEvidence = (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> =>
withProcessCancellation(signal, (operationSignal) =>
managedCallerEvidence(
dependencies,
path,
tool,
arguments_,
operationSignal,
),
);
/** Managed Evidence bound to the caller's path and its request facts. */
const managedCallerEvidence = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
operationSignal: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> => {
// Preserve the selected path and original arguments as request facts.
const original = await runManagedProviderAnalysis(
dependencies,
path,
tool,
arguments_,
{ ...arguments_, input_path: path },
operationSignal,
);
await dispatchQueuedInterrupts();
if (!original.ok)
return err(retainFinalCancellation(original.error, tool, operationSignal));
const evidence = withEvidenceCallerInputPath(original.value, path);
if (operationSignal.aborted)
return err(
cancelledBy(tool, operationSignal, {
partialObservation: evidence,
}),
);
return ok(evidence);
};
/** Execute managed metadata inspection in an isolated managed-only session. */
export const runManagedProviderExecution = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
signal?: AbortSignal,
parameters: Readonly<Record<string, JsonValue>> = {},
recoveryParameters?: Readonly<Record<string, JsonValue>>,
): Promise<Result<AnalysisExecution, AnalysisError>> =>
withProcessCancellation(signal, async (operationSignal) => {
const admitted = admitOneShotOperation(tool, parameters, operationSignal);
if (!admitted.ok) return admitted;
const session = await dependencies.createManagedBinarySession();
return withSessionCleanup(
session,
async () => {
const opened = await session.open(path, { signal: operationSignal });
if (!opened.ok) return opened;
return recoveryParameters === undefined
? await session.execute(admitted.value.name, admitted.value.input, {
signal: operationSignal,
})
: await session.executeForDirectObservation(
admitted.value.name,
admitted.value.input,
recoveryParameters,
{ signal: operationSignal },
);
},
managedAnalysisCleanupFailure,
);
});
/** Preserve typed managed Evidence before selecting its CLI delivery. */
const runManagedProviderAnalysis = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
evidenceParameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> => {
const execution = await runManagedProviderExecution(
dependencies,
path,
tool,
signal,
arguments_,
evidenceParameters,
);
if (!execution.ok) return execution;
const value = execution.value;
return ok(
createAnalysisExecutionEvidence(
tool,
evidenceParameters,
value,
"observed",
{ immutable: true },
),
);
};
const runAnalysis = async (
dependencies: DirectAnalysisDependencies,
path: string,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
options: {
readonly logger: Logger;
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
readonly evidenceParameters?: Readonly<Record<string, JsonValue>>;
readonly createSession?: () => BinarySession | Promise<BinarySession>;
readonly includeEvidenceSources?: boolean;
readonly providerId?: AnalysisProviderSelector;
readonly formatHint?: ExecutableFormatHint;
readonly architecture?: BinaryArchitecture;
readonly entryPoint?: string;
readonly espFlash?: EspFlashSelection;
},
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> => {
const { logger, signal, snapshotPath } = options;
const evidenceParameters = options.evidenceParameters ?? arguments_;
let session: BinarySession;
if (options.createSession !== undefined) {
session = await options.createSession();
} else {
const config = dependencies.readConfiguration();
if (!config.ok) return err(cliError(config.error));
session = await (
tool === "inspect_native_dispatch_metadata" && snapshotPath === undefined
? dependencies.createNativeDispatchBinarySession
: dependencies.createBinarySession
)(config.value, logger);
}
let publishedSnapshot: PublishedEvidenceFile | undefined;
let sourceEvidence: readonly Evidence[] | undefined;
const captureSources = (
evidence: Evidence,
supplied: readonly Evidence[] = [],
): Result<null, AnalysisError> => {
if (!options.includeEvidenceSources) return ok(null);
const records = new Map(
supplied.map((record) => [record.evidence_id, record]),
);
const collected = collectInvestigationEvidenceClosure(
{
evidenceForAnalysis: (id) =>
records.get(id) ?? session.evidenceForAnalysis(id),
},
evidence.evidence_links,
);
sourceEvidence = collected.records;
return collected.result;
};
const execute = async (): Promise<Result<Evidence, AnalysisError>> => {
let isDirectory = false;
if (BUNDLE_RESOURCE_OPERATIONS.has(tool)) {
const inspected = await inspectBundleResourceInput(path);
if (!inspected.ok) return inspected;
isDirectory = inspected.value;
}
if (BUNDLE_RESOURCE_OPERATIONS.has(tool) && isDirectory) {
const opened = await session.openBundleResources(path, { signal });
if (!opened.ok) return opened;
const execution = await session.execute(tool, arguments_, { signal });
if (!execution.ok) return execution;
return ok(
withEvidenceCallerInputPath(
createAnalysisExecutionEvidence(
tool,
evidenceParameters,
execution.value,
"observed",
),
path,
),
);
}
const prepared = await prepareSnapshot({
session,
path,
snapshotPath,
signal,
...targetSelection(options),
});
if (!prepared.ok) return prepared;
const { snapshot } = prepared.value;
let resolvedTarget: ResolvedSessionOpen | undefined;
if (snapshot !== undefined && prepared.value.target !== undefined) {
const preview = await session.previewTarget(prepared.value.target, {
signal,
snapshot,
...targetSelection(options),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
});
if (!preview.ok) return preview;
resolvedTarget = preview.value;
const route = preview.value.route;
const bindingProfile =
route.profile ?? nativeDispatchBindingProfile(route, tool);
const evidenceProfile = analysisProfileForRoute(route, tool);
// A parsed Windows path does not prove Ghidra's native snapshot owner
// admitted the selected source; CLI replay must wait for that client.
if (
bindingProfile !== undefined &&
evidenceProfile !== undefined &&
!requiresNativeSourceAdmissionBeforeReplay(
route.binding?.identity.id,
) &&
tool !== "trace_native_ui_action" &&
tool !== "decompile_all" &&
!requestsFreshIndependentDecompile(tool, arguments_) &&
routeAllowsSnapshotReplay(route, tool)
) {
const cached = snapshotEvidenceForQuery(snapshot, {
target: preview.value.target,
bindingProfile,
operation: tool,
parameters: arguments_,
provider: isWorkflowEvidenceTool(tool)
? REA_WORKFLOW_PROVIDER
: routeProviderIdentity(route, tool),
evidenceProfile,
});
if (cached !== undefined) {
const records = new Map(
snapshot.evidence_bundle.records.map((record) => [
record.evidence_id,
record,
]),
);
const checkClosure = createInvestigationEvidenceClosureChecker({
evidenceForAnalysis: (id) => records.get(id),
});
if (checkClosure(cached.evidence_links)) {
const evidence = withEvidenceCallerInputPath(cached, path);
const captured = captureSources(
evidence,
snapshot.evidence_bundle.records,
);
if (!captured.ok)
return err(captured.error.retainPartialObservation(evidence));
return ok(evidence);
}
}
}
}
const openOptions = {
signal,
...targetSelection(options),
...(snapshot === undefined ? {} : { snapshot }),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
};
const opened =
resolvedTarget === undefined
? await session.open(path, openOptions)
: await session.openResolvedTarget(resolvedTarget, openOptions);
if (!opened.ok) return opened;
const evidenceProfile = analysisProfileForEvidence(session, tool);
const executed = await executeAnalysisTool({
session,
openedTarget: opened.value,
tool,
arguments: arguments_,
evidenceParameters,
signal,
evidenceProfile,
saveSnapshot: snapshotPath !== undefined,
});
if (!executed.ok) {
if (options.includeEvidenceSources) {
const partial = recognizeEvidence(executed.error.partialObservation);
if (!partial.ok) executed.error.retainSecondaryFailure(partial.error);
else if (partial.value !== undefined) {
const captured = captureSources(partial.value);
if (!captured.ok)
executed.error.retainSecondaryFailure(captured.error);
}
}
return executed;
}
const { cachePolicy } = executed.value;
const evidence = withEvidenceCallerInputPath(executed.value.evidence, path);
// Provider execution may have already recorded the same semantic Evidence
// without this invocation's request path. Import replaces that metadata
// while retaining the authenticated result and snapshot binding.
const captured = captureSources(evidence);
if (!captured.ok)
return err(captured.error.retainPartialObservation(evidence));
const recorded = session.importEvidenceBundle(
createImmutableEvidenceBundle([evidence]),
);
if (!recorded.ok)
return err(recorded.error.retainPartialObservation(evidence));
if (isWorkflowEvidenceTool(tool)) {
const unknowns = recordWorkflowUnknowns({
name: tool,
result: evidence.normalized_result,
evidenceId: evidence.evidence_id,
recordUnknown: (unknown) => session.recordUnknown(unknown),
evidenceRetained: true,
});
if (!unknowns.ok)
return err(unknowns.error.retainPartialObservation(evidence));
}
if (
isWorkflowEvidenceTool(tool) &&
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
session.allowsSnapshotReplay(tool)
) {
const workflowRecord = workflowSnapshotRecord(
evidence,
tool,
evidenceProfile,
cachePolicy,
);
if (workflowRecord !== undefined) {
const recorded = session.recordWorkflowSnapshot(workflowRecord);
if (!recorded.ok)
return err(recorded.error.retainPartialObservation(evidence));
}
}
if (
tool !== "trace_native_ui_action" &&
tool !== "decompile_all" &&
snapshotPath !== undefined
) {
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok)
return err(snapshot.error.retainPartialObservation(evidence));
const written = await session.writeAnalysisSnapshot(
snapshot.value,
snapshotPath,
true,
);
if (written.ok) publishedSnapshot = written.value;
else {
const published =
written.error instanceof EvidenceFileError
? written.error.published
: undefined;
if (published?.path !== undefined)
publishedSnapshot = { path: published.path, bytes: published.bytes };
const released =
published !== undefined && (await session.closeFileResources()).ok;
if (!released || published?.path === undefined)
return err(written.error.retainPartialObservation(evidence));
}
}
return ok(evidence);
};
const outcome = await withSessionCleanup<{
readonly result: Result<Evidence, AnalysisError>;
readonly cleanupError?: AnalysisError;
}>(
session,
async () => {
const result = await execute();
if (
!result.ok &&
result.error.sourcePublicationRecovery?.completed.kind ===
"retained-evidence"
) {
const retained = session.evidenceForAnalysis(
result.error.sourcePublicationRecovery.completed.evidence_id,
);
if (retained !== undefined)
result.error.sourcePublicationRecovery = {
...result.error.sourcePublicationRecovery,
completed: {
kind: "inline-evidence",
retention: "one-shot-session",
source_closure: "not-established",
evidence: retained,
},
};
}
return { result };
},
(value, cleanupError) => ({ ...value, cleanupError }),
);
await dispatchQueuedInterrupts();
const result = outcome.result.ok
? completeProviderEvidence(outcome.result.value, signal)
: err(retainFinalCancellation(outcome.result.error, tool, signal));
if (!result.ok && publishedSnapshot !== undefined)
result.error.retainDiagnostics({
analysis_snapshot: { ...publishedSnapshot },
});
if (outcome.cleanupError !== undefined) {
// A committed snapshot remains published even when final close fails.
if (result.ok && publishedSnapshot !== undefined)
outcome.cleanupError.retainDiagnostics({
analysis_snapshot: { ...publishedSnapshot },
});
return {
...err(directAnalysisCleanupFailure(result, outcome.cleanupError, path)),
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
};
}
return {
...(result.ok ? ok(result.value) : err(cliError(result.error, path))),
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
};
};
/** Preserve an earlier failure and a cancellation observed during final cleanup. */
const retainFinalCancellation = (
failure: AnalysisError,
tool: string,
signal: AbortSignal,
): AnalysisError =>
signal.aborted
? analysisErrorWithCancellation(failure, cancelledBy(tool, signal))
: failure;
const executeAnalysisTool = async (input: {
readonly session: BinarySession;
readonly openedTarget: BinaryTarget;
readonly tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool;
readonly arguments: Readonly<Record<string, JsonValue>>;
readonly evidenceParameters: Readonly<Record<string, JsonValue>>;
readonly signal: AbortSignal;
readonly evidenceProfile: AnalysisProfileCommitment | undefined;
readonly saveSnapshot: boolean;
}): Promise<
Result<
{
readonly evidence: Evidence;
readonly cachePolicy?: "live";
},
AnalysisError
>
> => {
const { session, tool, signal, evidenceProfile } = input;
if (tool === "analyze_function") {
const { executeFunctionAnalysisEvidence } =
await import("./FunctionAnalysisEvidence.js");
let result = await executeFunctionAnalysisEvidence(
session,
input.arguments,
input.openedTarget,
{ signal },
);
result = retainAnalysisResultSources(
tool,
(source) => session.recordEvidence(source),
result,
);
return result.ok ? ok({ evidence: result.value }) : result;
}
if (isWorkflowEvidenceTool(tool)) {
const { EnhancedTools } = await import("./EnhancedTools.js");
let result = await executeComposedWorkflow(
session,
(observed) =>
new EnhancedTools(observed).execute(tool, input.arguments, signal),
composedLimitationBudget(tool),
);
retainPartialWorkflowEvidence(result, {
target: input.openedTarget,
operation: tool,
parameters: input.evidenceParameters,
upstreamProfile: evidenceProfile,
});
result = retainAnalysisResultSources(
tool,
(source) => session.recordEvidence(source),
result,
);
if (!result.ok) return result;
const evidence = createWorkflowEvidence({
target: input.openedTarget,
operation: tool,
parameters: input.evidenceParameters,
result: result.value.result,
upstreamProfile: evidenceProfile,
upstreamLimitations: result.value.limitations,
...(result.value.evidenceLinks === undefined
? {}
: { upstreamEvidenceLinks: result.value.evidenceLinks }),
});
return ok({
evidence,
...(result.value.cachePolicy === undefined
? {}
: { cachePolicy: result.value.cachePolicy }),
});
}
let result = await session.executeForDirectObservation(
tool,
input.arguments,
input.evidenceParameters,
{
signal,
...(input.saveSnapshot && tool === "procedure_pseudo_code"
? { snapshotContext: "one-shot-target" as const }
: {}),
},
);
if (
tool === "xrefs" &&
typeof input.arguments.address === "string" &&
!result.ok &&
result.error instanceof AnalysisInputError &&
!result.error.cleanupIncomplete &&
result.error.issues.length > 0 &&
result.error.issues.every(
({ path, reason }) =>
path.length === 1 &&
path[0] === "address" &&
reason === "invalid_format",
)
) {
const address = await resolveXrefsAddress(
session,
input.arguments.address,
signal,
);
if (!address.ok) return address;
if (address.value !== input.arguments.address)
result = await session.executeForDirectObservation(
tool,
{ ...input.arguments, address: address.value },
input.evidenceParameters,
{ signal },
);
}
if (!result.ok) return result;
const evidence = completedOperationEvidence(
tool,
input.evidenceParameters,
result.value,
{
target: input.openedTarget,
admitRecovery: session.admitRecoveryObservation.bind(session),
evidenceById: (id) => session.evidenceForAnalysis(id),
},
);
return evidence.ok ? ok({ evidence: evidence.value }) : evidence;
};
const withProcessCancellation = async <Value>(
suppliedSignal: AbortSignal | undefined,
operation: (signal: AbortSignal) => Promise<Value>,
): Promise<Value> => {
if (suppliedSignal !== undefined) return operation(suppliedSignal);
const controller = new AbortController();
const interrupt = (): void =>
controller.abort(CallerAbort.forProcessSignal("SIGINT"));
const terminate = (): void =>
controller.abort(CallerAbort.forProcessSignal("SIGTERM"));
// Package runners can forward a terminal interrupt after REA already received
// it directly. Keep both guards installed until provider cleanup has settled.
process.on("SIGINT", interrupt);
process.on("SIGTERM", terminate);
try {
return await operation(controller.signal);
} finally {
process.off("SIGINT", interrupt);
process.off("SIGTERM", terminate);
}
};
const prepareSnapshot = async (options: {
readonly session: Pick<
BinarySession,
"readAnalysisSnapshot" | "resolveTarget"
>;
readonly path: string;
readonly formatHint?: ExecutableFormatHint;
readonly architecture?: BinaryArchitecture;
readonly entryPoint?: string;
readonly espFlash?: EspFlashSelection;
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
}): Promise<
Result<
{ readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget },
AnalysisError
>
> => {
const { path, snapshotPath, session } = options;
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
return ok({});
const loaded = await session.readAnalysisSnapshot(
snapshotPath,
options.signal,
);
if (!loaded.ok) return loaded;
const target = await session.resolveTarget(path, {
signal: options.signal,
...targetSelection(options),
});
if (!target.ok) return target;
const mismatch = snapshotBindingMismatch(
loaded.value,
target.value,
undefined,
);
if (mismatch?.target !== undefined)
return err(
new AnalysisSnapshotMismatchError(
"Analysis snapshot target does not match the requested binary",
mismatch,
),
);
return ok({ snapshot: loaded.value, target: target.value });
};
const inspectBundleResourceInput = async (
path: string,
): Promise<Result<boolean, BinaryTargetError>> => {
const callerPath = absoluteCallerPath(path);
try {
return ok((await stat(callerPath)).isDirectory());
} catch (cause: unknown) {
const failure = classifyBinaryTargetFilesystemFailure(callerPath, cause);
if (failure !== undefined) return err(failure);
throw cause;
}
};
const analysisProfileForRoute = (
route: SessionProviderRoute,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
const profile = route.profile;
const nativeDispatchProfile =
profile === null || profile === undefined
? nativeDispatchBindingProfile(route, tool)
: undefined;
if (profile === null || profile === undefined) {
if (nativeDispatchProfile === undefined) return undefined;
return isWorkflowEvidenceTool(tool)
? workflowAnalysisProfile(nativeDispatchProfile, tool)
: nativeDispatchProfile;
}
if (isWorkflowEvidenceTool(tool))
return workflowAnalysisProfile(profile, tool);
const provider = routeProviderIdentity(route, tool);
return provider.id === profile.provider.id ? profile : undefined;
};
const nativeDispatchBindingProfile = (
route: SessionProviderRoute,
operation: string,
): AnalysisProfileCommitment | undefined => {
if (operation !== "inspect_native_dispatch_metadata") return undefined;
return profilelessNativeDispatchProfile(route);
};
const analysisProfileForEvidence = (
session: BinarySession,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
if (!isWorkflowEvidenceTool(tool)) return session.analysisProfile(tool);
return session.analysisProfile() ?? session.analysisProfile(tool);
};
const isWorkflowEvidenceTool = (
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): tool is Exclude<
Extract<DirectAnalysisTool, EnhancedToolName>,
"analyze_function"
> =>
tool === "binary_overview" ||
tool === "inspect_native_api" ||
tool === "inspect_native_dispatch_metadata" ||
tool === "trace_feature" ||
tool === "trace_native_values" ||
tool === "trace_native_ui_action" ||
tool === "decompile_all";
const fileExists = async (path: string): Promise<boolean> => {
try {
await access(path);
return true;
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "ENOENT"
)
return false;
throw cause;
}
};
const cliError = (
error: AnalysisError,
callerInputPath?: string,
): JsonValue => ({
error: "Analysis failed",
...(callerInputPath === undefined
? projectInvocationFailure(error)
: projectDirectAnalysisFailure(error, callerInputPath)),
});