From 402ce20b807231efc9b7f209360aed158c4adc5f Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:55:48 -0500 Subject: [PATCH] fix(session): declare, admit and advertise the open-target prerequisite through one owner (#15356) * fix(contracts): declare the open-target prerequisite once in availability Replace the requiresActiveTarget boolean with an "active-target" value of the availability declaration. 18 contracts that read a required caller path, all declared standalone or host-restricted or named inventory rules, no longer claim to need an open target. * fix(session): admit tools through one session evaluator shared with binary_session binary_session availability and call-time dispatch now read one admission evaluator for active-target tools and external mutations. Resource-only lane refusals and Ghidra or resource-only external-mutation refusals carry the open_binary or close_binary recovery that binary_session reports, instead of a generic capability or unreadable-output error. Packet capture, Wakaru, firmware and mitmproxy refuse an unsupported host before reading tool configuration. * fix(mcp): advertise the open-target prerequisite and name open_binary on first contact Each active-target tool's advertised description ends with one sentence derived from its availability declaration. When the SDK refuses such a tool's arguments while the session would also refuse it, the invalid_request remediation names the session recovery first, read from the same admission evaluator as binary_session and dispatch. * fix(mcp): refuse composed workflows as a whole and keep scoped recovery and catalog identity in step A composed workflow such as batch_decompile now refuses with the advertised open_binary or close_binary recovery before it runs, instead of reporting a batch of failed children. Malformed arguments on a connection that does not advertise session tools lead with the scoped restart recovery, and catalog digests cover the advertised prerequisite sentence. The prerequisite test reads union alternatives. --- src/application/CapabilityInventory.test.ts | 45 ++++- src/application/CapabilityInventory.ts | 68 +++---- src/application/binary/BinarySession.ts | 59 +++--- .../binary/BinarySessionExecution.ts | 5 +- src/application/binary/BinarySessionPort.ts | 3 + .../binary/sessionAdmission.test.ts | 115 +++++++++++ src/application/binary/sessionAdmission.ts | 178 ++++++++++++++++++ .../history/MitmproxyCaptureAdapter.ts | 22 ++- .../apkSignature/apkSignatureToolContracts.ts | 1 - src/contracts/artifactToolContracts.ts | 10 +- .../captures/captureToolContracts.ts | 2 - src/contracts/catalog/catalogIdentity.ts | 6 +- src/contracts/cutterToolContracts.ts | 2 +- src/contracts/deb/debPackageToolContracts.ts | 1 - .../desktopApplicationToolContracts.ts | 1 - src/contracts/enhancedToolContracts.ts | 2 +- src/contracts/erlang/beamToolContracts.ts | 1 - src/contracts/evm/evmToolContracts.ts | 1 - .../functionWorkflowToolContracts.ts | 2 +- src/contracts/gdbToolContracts.ts | 4 +- src/contracts/go/goToolContracts.ts | 1 - src/contracts/gpu/gpuToolContracts.ts | 1 - src/contracts/il2cpp/il2cppToolContracts.ts | 1 - .../javascript/electronToolContracts.ts | 1 - src/contracts/labview/labviewToolContracts.ts | 1 - src/contracts/model/modelToolContracts.ts | 1 - src/contracts/native/nativeToolContracts.ts | 2 +- src/contracts/nuget/nupkgToolContracts.ts | 1 - .../oci/ociImageLayoutToolContracts.ts | 1 - src/contracts/officialToolContracts.ts | 2 +- .../python/pythonPycToolContracts.ts | 1 - .../reverseEngineeringToolContracts.ts | 2 +- src/contracts/rizinDebugToolContracts.ts | 6 +- src/contracts/rust/rustToolContracts.ts | 1 - src/contracts/sessionToolContracts.ts | 4 +- src/contracts/signals/signalToolContracts.ts | 2 - src/contracts/sqlite/sqliteToolContracts.ts | 1 - src/contracts/toolAvailability.ts | 23 ++- src/contracts/toolContractTypes.ts | 2 - .../vsix/vsixPackageToolContracts.ts | 1 - src/contracts/wasm/wasmToolContracts.ts | 1 - src/domain/analysisErrorPresentation.ts | 5 + src/domain/configurationErrors.ts | 14 +- src/firmware/FirmwareCommand.test.ts | 23 +++ src/firmware/FirmwareCommand.ts | 17 +- src/javascript/recovery/WakaruCommand.test.ts | 20 ++ src/javascript/recovery/WakaruCommand.ts | 15 +- src/pcap/PcapNativeBound.ts | 30 ++- src/pcap/PcapProvider.ts | 33 ++-- src/server/ErrorEvidenceTransport.ts | 20 +- src/server/EvidenceMcpServerCore.ts | 8 +- src/server/analysisAdmission.ts | 26 +++ src/server/contractToolHandler.ts | 9 + src/server/createServer.ts | 25 ++- src/server/toolRegistrationOptions.ts | 8 +- .../browser/historicalCaptureDecoder.test.ts | 19 ++ tests/boundary/mcp/serverIdentity.test.ts | 104 ++++++++++ tests/boundary/mcp/serverWorkflowMcp.test.ts | 6 +- .../mcp/targetContentFramingMcp.test.ts | 13 ++ .../pcap/pcapProviderCrossPlatform.test.ts | 38 +++- .../analysis-sessions/binarySession.test.ts | 12 +- 61 files changed, 861 insertions(+), 168 deletions(-) create mode 100644 src/application/binary/sessionAdmission.test.ts create mode 100644 src/application/binary/sessionAdmission.ts diff --git a/src/application/CapabilityInventory.test.ts b/src/application/CapabilityInventory.test.ts index 81672405671..969226e7f40 100644 --- a/src/application/CapabilityInventory.test.ts +++ b/src/application/CapabilityInventory.test.ts @@ -2,6 +2,7 @@ import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js"; import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js"; import { pcapCaptureHostSupported } from "../domain/pcap/pcapAnalysis.js"; import { describe, expect, it } from "vitest"; +import { z } from "zod"; import { buildCapabilityInventory, @@ -601,7 +602,7 @@ describe("partial navigation availability", () => { expect( TOOL_CONTRACTS.find((tool) => tool.name === "get_navigation_context"), ).toMatchObject({ - requiresActiveTarget: true, + availability: "active-target", }); }); it("allows explicit documents when the provider has no current-document getter", () => { @@ -1255,9 +1256,49 @@ describe("declared contract availability", () => { }); }); + it("declares an open target only for tools that take no caller-selected file, and reports it as required", () => { + const activeTarget = TOOL_CONTRACTS.filter( + (contract) => + "availability" in contract && contract.availability === "active-target", + ); + expect(activeTarget.length).toBeGreaterThan(0); + const tools = inventory({ processCaptureEnabled: false }); + // A union input declares `path` inside its alternatives, not at the root. + const requiredFields = ( + schema: Readonly>, + ): readonly unknown[] => [ + ...(Array.isArray(schema["required"]) ? schema["required"] : []), + ...["anyOf", "oneOf", "allOf"].flatMap((key) => { + const alternatives = schema[key]; + return Array.isArray(alternatives) + ? alternatives.flatMap((alternative: Record) => + requiredFields(alternative), + ) + : []; + }), + ]; + const requiredOf = (name: string): readonly unknown[] => { + const contract = TOOL_CONTRACTS.find((entry) => entry.name === name); + if (contract === undefined) throw new Error(`missing contract ${name}`); + return requiredFields( + z.toJSONSchema(contract.inputSchema, { io: "input" }), + ); + }; + // Controls: these file-taking tools require `path` only in alternatives. + expect(requiredOf("inspect_python_pyc")).toContain("path"); + expect(requiredOf("inspect_erlang_beam")).toContain("path"); + for (const contract of activeTarget) { + expect(requiredOf(contract.name), contract.name).not.toContain("path"); + expect(tools.get(contract.name), contract.name).toMatchObject({ + available: false, + reason: "target_required", + }); + } + }); + it("refuses each host-restricted declaration on an unsupported host before its configuration", () => { const hosted = declared.flatMap(({ name, availability }) => - availability === "standalone" ? [] : [{ name, ...availability }], + typeof availability === "string" ? [] : [{ name, ...availability }], ); expect(hosted.length).toBeGreaterThan(0); const tools = inventory({ diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts index e65dd772198..a41a2f4b1d7 100644 --- a/src/application/CapabilityInventory.ts +++ b/src/application/CapabilityInventory.ts @@ -54,13 +54,9 @@ import type { JebAnalysisAvailability } from "../ports/jeb/JebAnalysisPort.js"; import { FRIDA_TOOL_CONTRACTS } from "../contracts/fridaToolContracts.js"; import { TOOL_CONTRACTS } from "../contracts/toolContracts.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; -import { - analysisCleanupRetrySchema, - cleanupRetryRemediation, - type AnalysisCleanupRetry, -} from "../domain/analysisErrorRecovery.js"; +import { analysisCleanupRetrySchema } from "../domain/analysisErrorRecovery.js"; import { offeredOperationAlternatives } from "./OperationAlternatives.js"; -import { isBundleResourceOperation } from "../ports/BundleResourceOperations.js"; +import { admitTool, type SessionLane } from "./binary/sessionAdmission.js"; const FRIDA_OPERATION_NAMES: ReadonlySet = new Set( FRIDA_TOOL_CONTRACTS.map(({ name }) => name), @@ -143,9 +139,7 @@ type AvailabilityContext = { readonly kind: ToolKind; readonly declared: ToolAvailabilityDeclaration | undefined; readonly targetOpen: boolean; - readonly cleanupRetry: AnalysisCleanupRetry | undefined; - readonly resourceSession: boolean; - readonly requiresActiveTarget: boolean; + readonly lane: SessionLane; readonly targetKind: | "executable" | "database" @@ -343,11 +337,7 @@ export const buildCapabilityInventory = ( kind: contract.kind, declared: "availability" in contract ? contract.availability : undefined, targetOpen: status.open, - cleanupRetry: status.cleanup_retry, - resourceSession: status.session_kind === "bundle_resources", - requiresActiveTarget: - "requiresActiveTarget" in contract && - contract.requiresActiveTarget === true, + lane: sessionLane(status), targetKind: status.kind, targetFormat: status.format, descriptors, @@ -499,20 +489,26 @@ export function compactToolAvailability( : toolAvailabilityInventory.parse(inventory); } +/** What the reported session holds, as session admission reads it. */ +const sessionLane = (status: z.output): SessionLane => + status.session_kind === "bundle_resources" + ? { kind: "bundle_resources" } + : status.open + ? { kind: "analysis", bindingId: undefined } + : { kind: "none", cleanupRetry: status.cleanup_retry }; + +/** The dispatch owner's refusal for a tool that acts on the open target. */ +const sessionAdmission = ({ + name, + declared, + lane, +}: Pick) => + admitTool(name, declared, lane); + const availabilityFor = (context: AvailabilityContext): Availability => { - const workflowAvailability = workflowAvailabilityFor(context); - if ( - context.targetOpen && - context.resourceSession && - context.requiresActiveTarget && - !isBundleResourceOperation(context.name) && - (workflowAvailability === null || context.kind === "session") - ) - return { - reason: "target_unsupported", - remediation: - "This resource-only session cannot execute this operation. Call open_binary with an executable analysis target.", - }; + const admission = sessionAdmission(context); + if (admission?.stage === "lane") + return { reason: admission.reason, remediation: admission.remediation }; // Standalone workflows take caller-selected input; they do not load an // optional provider, so its load failure does not apply to them. if (context.declared === "standalone") @@ -544,6 +540,7 @@ const availabilityFor = (context: AvailabilityContext): Availability => { reason: "provider_unavailable", remediation: `Adapter ${failure.providerId} could not load: ${failure.reason}. Repair the adapter installation and restart REA; other capabilities remain available.`, }; + const workflowAvailability = workflowAvailabilityFor(context); if (workflowAvailability !== null) return workflowAvailability; const hostDecision = hostAvailability(context); if (hostDecision !== null) return hostDecision; @@ -576,7 +573,7 @@ const workflowAvailabilityFor = ( const { name, kind, policy, declared } = context; if (declared === "standalone") return { reason: "available", remediation: null }; - if (declared !== undefined) { + if (declared !== undefined && declared !== "active-target") { const host = hostFeatureAvailability(policy, declared.host); return declared.host === "evmInterface" && host.reason === "available" ? evmLimiterAvailability(policy) @@ -895,18 +892,13 @@ const targetAvailability = ({ targetKind, targetFormat, targetOpen, - cleanupRetry, - requiresActiveTarget, + declared, + lane, descriptors, }: AvailabilityContext): Availability | null => { - if (!targetOpen && requiresActiveTarget) - return { - reason: "target_required", - remediation: - cleanupRetry === undefined - ? "Call open_binary with a supported local target." - : `${cleanupRetryRemediation(cleanupRetry)} After cleanup succeeds, call open_binary with a supported local target.`, - }; + const admission = sessionAdmission({ name, declared, lane }); + if (admission?.stage === "target") + return { reason: admission.reason, remediation: admission.remediation }; const descriptor = descriptors.get(name); if ( targetOpen && diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index 5236103a1a4..9081f5b03a0 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -25,7 +25,6 @@ import { import { AnalysisCancelledError, AnalysisCapabilityUnavailableError, - AnalysisOutputError, isAborted, cancelledBy, OwnerCancellation, @@ -118,7 +117,13 @@ import type { ActiveBundleResourceSession, BundleResourceClientFactory, } from "./BundleResourceSession.js"; -import { BUNDLE_RESOURCE_OPERATIONS } from "../../ports/BundleResourceOperations.js"; +import { invariantViolation } from "../../domain/internalInvariant.js"; +import { + admitActiveTargetOperation, + admitExternalMutation, + sessionRefusalError, + type SessionLane, +} from "./sessionAdmission.js"; import { deliverSessionLimitations, type SessionLimitationDelivery, @@ -803,14 +808,10 @@ export class BinarySession ), ); return this.#serialize(async (admittedThrough) => { - if (this.#activeBundleResources !== undefined) - return err( - new AnalysisCapabilityUnavailableError( - "bundle-resources", - operationName, - "External mutation requires an active executable analysis target.", - ), - ); + // Transitions are serialized, so the lane cannot change before dispatch. + const refusal = admitExternalMutation(this.#lane()); + if (refusal !== undefined) + return err(sessionRefusalError(operationName, refusal)); if (isAborted(signal)) return err(cancelledBy(operationName, signal)); await this.#drainCalls(admittedThrough); if (isAborted(signal)) return err(cancelledBy(operationName, signal)); @@ -859,13 +860,6 @@ export class BinarySession if (isAborted(signal)) return err(cancelledBy(operationName, signal)); const activeAtDispatch = this.#active; - if (activeAtDispatch?.route.binding?.identity.id === "ghidra") - return err( - new AnalysisOutputError( - operationName, - "Close the active Ghidra session explicitly before an external mutation; rebinding would discard its ephemeral analysis edits.", - ), - ); // A protocol reply does not prove that background writers have stopped. // Retire the old analysis and require an explicit fresh open rather than // silently binding a snapshot while an unrestricted command can still write. @@ -1098,6 +1092,22 @@ export class BinarySession return closed; } + /** What the session holds now, as session admission reads it. */ + sessionLane(): SessionLane { + return this.#lane(); + } + + #lane(): SessionLane { + if (this.#activeBundleResources !== undefined) + return { kind: "bundle_resources" }; + if (this.#active === undefined) + return { kind: "none", cleanupRetry: this.#statusCleanupRetry() }; + return { + kind: "analysis", + bindingId: this.#active.route.binding?.identity.id, + }; + } + /** Only a retired target's known close owner can offer this status retry. */ #statusCleanupRetry(): AnalysisCleanupRetry | undefined { if ( @@ -1553,16 +1563,11 @@ export class BinarySession transition, ); if (!transitioned.ok) return transitioned; + const admission = admitActiveTargetOperation(name, this.#lane()); + if (admission !== undefined) + return err(sessionRefusalError(name, admission)); const resources = this.#activeBundleResources; if (resources !== undefined) { - if (!BUNDLE_RESOURCE_OPERATIONS.has(name)) - return err( - new AnalysisCapabilityUnavailableError( - "bundle-resources", - name, - "This operation requires an executable analysis target; the active session contains only app resource access.", - ), - ); const result = unrecordedExecution( await resources.client.execute(name, arguments_, options), ); @@ -1571,6 +1576,10 @@ export class BinarySession return ok(execution); } const sessionBinding = this.#active; + if (sessionBinding === undefined) + throw invariantViolation( + `Session admission admitted ${name} without a target`, + ); const prepared = prepareSessionExecution({ active: sessionBinding, operation: name, diff --git a/src/application/binary/BinarySessionExecution.ts b/src/application/binary/BinarySessionExecution.ts index 77c0d1e3816..4237b6930b8 100644 --- a/src/application/binary/BinarySessionExecution.ts +++ b/src/application/binary/BinarySessionExecution.ts @@ -4,7 +4,6 @@ import { type BinaryTarget, } from "../../domain/binaryTargetTypes.js"; import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js"; -import { NoBinaryOpenError } from "../../domain/configurationErrors.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import type { JsonValue } from "../../domain/jsonValue.js"; @@ -42,7 +41,8 @@ export interface PreparedSessionExecution { } interface PrepareSessionExecutionInput { - readonly active: ActiveExecutionBinding | undefined; + /** Session admission has already refused a call with no target open. */ + readonly active: ActiveExecutionBinding; readonly operation: AnalysisOperation; readonly parameters: Readonly>; readonly snapshotContext?: ExecutionOptions["snapshotContext"]; @@ -91,7 +91,6 @@ export const prepareSessionExecution = ( unboundOperationError, lookupSnapshot, } = input; - if (active === undefined) return err(new NoBinaryOpenError()); const capability = active.route.capabilities.get(operation); if (capability?.available !== true) { const selectionError = unboundOperationError(operation, active.route); diff --git a/src/application/binary/BinarySessionPort.ts b/src/application/binary/BinarySessionPort.ts index 5584a6d13d0..21e5c6cb0c3 100644 --- a/src/application/binary/BinarySessionPort.ts +++ b/src/application/binary/BinarySessionPort.ts @@ -19,6 +19,7 @@ import type { AnalysisSnapshotLoader } from "./BinarySessionOpen.js"; import type { WorkflowSnapshotRecordInput } from "./BinarySessionRecords.js"; import type { ResolvedAppBundleResourceRoot } from "../../domain/apple/bundleResourceRoot.js"; import type { binaryTargetSummary } from "./BinaryTargetSummary.js"; +import type { SessionLane } from "./sessionAdmission.js"; import type { AnalysisExecution, @@ -153,6 +154,8 @@ export interface BinarySessionPort readonly refreshCandidates?: boolean; }): Promise; activeTarget(): BinaryTarget | undefined; + /** What the session holds now, as session admission reads it. */ + sessionLane(): SessionLane; /** Create an isolated session over this session's auxiliary providers. */ createManagedBinarySession?(): | ManagedBinarySessionPort diff --git a/src/application/binary/sessionAdmission.test.ts b/src/application/binary/sessionAdmission.test.ts new file mode 100644 index 00000000000..7fddbd9e4b6 --- /dev/null +++ b/src/application/binary/sessionAdmission.test.ts @@ -0,0 +1,115 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; + +import { TOOL_CONTRACTS } from "../../contracts/toolContracts.js"; +import { analysisErrorRemediationAction } from "../../domain/analysisErrorPresentation.js"; +import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; +import { ok } from "../../domain/result.js"; +import { + createAnalysisExecution, + type AnalysisClient, + type AnalysisOperation, +} from "../../ports/AnalysisProvider.js"; +import { buildCapabilityInventory } from "../CapabilityInventory.js"; +import { InvestigationRecords } from "../investigation/InvestigationRecords.js"; +import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js"; +import { BinarySession } from "./BinarySession.js"; +import { SessionProviderRouter } from "./SessionProviderRouter.js"; + +const identity = { + id: "bundle-resource-fixture", + name: "Fixture", + version: "1", +}; + +const resourceClient: AnalysisClient = { + execute: async (operation) => + ok(createAnalysisExecution({ operation, target_sha256: null }, identity)), + close: async () => ok(null), +}; + +const createSession = () => + new BinarySession( + SessionProviderRouter.selectable(new AnalysisProviderRegistry([]), []), + new InvestigationRecords(), + { createClient: () => ({ client: resourceClient, capabilities: [] }) }, + ); + +const openResources = async (session: BinarySession): Promise => { + const root = await createTestTempDirectory("rea-session-admission-"); + await writeFile(join(root, "Info.plist"), ""); + const opened = await session.openBundleResources(root); + if (!opened.ok) throw opened.error; +}; + +const activeTargetTools = TOOL_CONTRACTS.filter( + (contract) => + "availability" in contract && contract.availability === "active-target", +).map(({ name }) => name); + +/** + * Each active-target tool's call-time refusal carries the remediation that + * binary_session advertises for it, in every session lane. + */ +describe("session admission parity", () => { + it.each([ + ["no target", async () => {}], + ["a resource-only session", openResources], + ] as const)( + "refuses each active-target tool with its advertised remediation in %s", + async (_lane, prepare) => { + const session = createSession(); + try { + await prepare(session); + const inventory = new Map( + buildCapabilityInventory(await session.status(), { + processCaptureEnabled: false, + }).map((tool) => [tool.name, tool]), + ); + for (const name of activeTargetTools) { + const advertised = inventory.get(name); + const called = await session.execute(name as AnalysisOperation, {}); + if (advertised?.available === true) { + expect(called.ok, name).toBe(true); + continue; + } + if (called.ok) throw new Error(`${name} was admitted`); + expect(advertised, name).toMatchObject({ + reason: expect.stringMatching(/^target_(required|unsupported)$/u), + }); + expect(analysisErrorRemediationAction(called.error), name).toBe( + advertised?.remediation, + ); + } + } finally { + await session.close(); + } + }, + ); + + it("refuses an external mutation beside a resource-only session and names close_binary", async () => { + const session = createSession(); + try { + await openResources(session); + const mutate = vi.fn(async () => ok("mutated")); + const admitted = await session.withAdmittedExternalMutation( + undefined, + undefined, + mutate, + (_value, error) => error, + ); + if (admitted.ok) throw new Error("external mutation was admitted"); + expect(mutate).not.toHaveBeenCalled(); + expect(projectAnalysisError(admitted.error)).toMatchObject({ + code: "capability_unavailable", + remediation: { + action: expect.stringContaining("Call close_binary"), + }, + }); + } finally { + await session.close(); + } + }); +}); diff --git a/src/application/binary/sessionAdmission.ts b/src/application/binary/sessionAdmission.ts new file mode 100644 index 00000000000..2bae0e12170 --- /dev/null +++ b/src/application/binary/sessionAdmission.ts @@ -0,0 +1,178 @@ +import type { ToolAvailabilityDeclaration } from "../../contracts/toolAvailability.js"; +import { TOOL_CONTRACTS } from "../../contracts/toolContracts.js"; +import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { + cleanupRetryRemediation, + type AnalysisCleanupRetry, +} from "../../domain/analysisErrorRecovery.js"; +import { + NO_TARGET_RECOVERY, + NoBinaryOpenError, +} from "../../domain/configurationErrors.js"; +import { isBundleResourceOperation } from "../../ports/BundleResourceOperations.js"; + +/** The session tool a refusal sends the caller to, checked against the registry. */ +export type SessionRecoveryTool = Extract< + (typeof TOOL_CONTRACTS)[number]["name"], + "open_binary" | "close_binary" +>; + +/** What the binary session currently holds, as admission reads it. */ +export type SessionLane = + | { + readonly kind: "none"; + /** A retired target's cleanup that the next close retries. */ + readonly cleanupRetry: AnalysisCleanupRetry | undefined; + } + | { readonly kind: "bundle_resources" } + | { + readonly kind: "analysis"; + /** The bound engine, when the route bound one. */ + readonly bindingId: string | undefined; + }; + +/** + * Why the session cannot admit an operation now, and the one session tool + * that changes that. Availability reporting and call-time refusal both + * project this value, so they cannot disagree. + */ +export interface SessionRefusal { + readonly stage: "target" | "lane"; + /** The `binary_session` availability reason this refusal reports. */ + readonly reason: "target_required" | "target_unsupported"; + readonly blocking: "no_target" | "bundle_resources" | "ephemeral_analysis"; + readonly nextTool: SessionRecoveryTool; + /** The session fact that refused the operation. */ + readonly cause: string; + readonly remediation: string; +} + +const OPEN_EXECUTABLE: SessionRecoveryTool = "open_binary"; +const CLOSE_SESSION: SessionRecoveryTool = "close_binary"; + +const noTargetRefusal = ( + cleanupRetry: AnalysisCleanupRetry | undefined, +): SessionRefusal => ({ + stage: "target", + reason: "target_required", + blocking: "no_target", + nextTool: OPEN_EXECUTABLE, + cause: "No target is open.", + remediation: + cleanupRetry === undefined + ? NO_TARGET_RECOVERY + : `${cleanupRetryRemediation(cleanupRetry)} After cleanup succeeds, call ${OPEN_EXECUTABLE} with a supported local target.`, +}); + +/** + * Admit an operation that acts on the open target. A resource-only session + * serves only its app-resource reads; anything else needs an executable. + */ +export const admitActiveTargetOperation = ( + operation: string, + lane: SessionLane, +): SessionRefusal | undefined => { + switch (lane.kind) { + case "none": + return noTargetRefusal(lane.cleanupRetry); + case "bundle_resources": + return isBundleResourceOperation(operation) + ? undefined + : { + stage: "lane", + reason: "target_unsupported", + blocking: "bundle_resources", + nextTool: OPEN_EXECUTABLE, + cause: + "The active session contains only app resource access, not an executable analysis target.", + remediation: `Call ${OPEN_EXECUTABLE} with the app's executable (or the app bundle) to analyze it; that replaces the resource-only session.`, + }; + case "analysis": + return undefined; + } +}; + +/** + * Admit one tool by its contract's declared prerequisite. Only a tool that + * acts on the open target is refused for the session's state. + */ +export const admitTool = ( + tool: string, + availability: ToolAvailabilityDeclaration | undefined, + lane: SessionLane, +): SessionRefusal | undefined => + availability === "active-target" + ? admitActiveTargetOperation(tool, lane) + : undefined; + +const DECLARED_AVAILABILITY: ReadonlyMap< + string, + ToolAvailabilityDeclaration | undefined +> = new Map( + TOOL_CONTRACTS.map((contract) => [ + contract.name, + "availability" in contract ? contract.availability : undefined, + ]), +); + +/** Admit one named tool by the prerequisite its contract declares. */ +export const admitDeclaredTool = ( + tool: string, + lane: SessionLane, +): SessionRefusal | undefined => + admitTool(tool, DECLARED_AVAILABILITY.get(tool), lane); + +/** + * Admit a command that may change the bound artifact. It runs on its own + * path, so it needs no target, but it retires the active analysis: a + * resource-only session and a Ghidra binding, whose ephemeral edits would be + * discarded, are closed explicitly first. + */ +export const admitExternalMutation = ( + lane: SessionLane, +): SessionRefusal | undefined => { + switch (lane.kind) { + case "none": + return undefined; + case "bundle_resources": + return { + stage: "lane", + reason: "target_unsupported", + blocking: "bundle_resources", + nextTool: CLOSE_SESSION, + cause: + "A resource-only session is active; external commands do not run beside it.", + remediation: `Call ${CLOSE_SESSION} to end the resource-only session, then repeat this command.`, + }; + case "analysis": + return lane.bindingId === "ghidra" + ? { + stage: "lane", + reason: "target_unsupported", + blocking: "ephemeral_analysis", + nextTool: CLOSE_SESSION, + cause: + "A Ghidra analysis is active; rebinding after an external command would discard its ephemeral analysis edits.", + remediation: `Preserve any Ghidra results you need, call ${CLOSE_SESSION}, then repeat this command.`, + } + : undefined; + } +}; + +/** The call-time error for a refusal; its remediation is the reported one. */ +export const sessionRefusalError = ( + operation: string, + refusal: SessionRefusal, +): AnalysisError => + refusal.blocking === "no_target" + ? new NoBinaryOpenError(refusal.remediation) + : new AnalysisCapabilityUnavailableError( + refusal.blocking === "bundle_resources" ? "bundle-resources" : "ghidra", + operation, + refusal.cause, + { + userMessage: `${refusal.cause} ${refusal.remediation}`, + remediationAction: refusal.remediation, + }, + ); diff --git a/src/browser/history/MitmproxyCaptureAdapter.ts b/src/browser/history/MitmproxyCaptureAdapter.ts index 72ca9a5c7fd..49908e901fe 100644 --- a/src/browser/history/MitmproxyCaptureAdapter.ts +++ b/src/browser/history/MitmproxyCaptureAdapter.ts @@ -9,7 +9,7 @@ import { MITMPROXY_CAPTURE_PROVIDER_IDENTITY } from "./CaptureProviderIdentities import { snapshotEnvironment } from "../../process/snapshotEnvironment.js"; const OPERATION = "inspect_web_network_capture"; const MITMDUMP_REQUIREMENT = - "Native capture decoding requires Linux and an absolute REA_MITMDUMP_COMMAND path to caller-supplied mitmdump 12.3.1; HAR needs no external engine."; + "Native capture decoding requires an absolute REA_MITMDUMP_COMMAND path to caller-supplied mitmdump 12.3.1; HAR needs no external engine."; /** Native mitmproxy decoding is offline and uses only an explicitly configured Linux tool. */ export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter { @@ -30,12 +30,22 @@ export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter { requestPath: string, runtimePath: string, ): Promise<{ command: string; arguments: readonly string[] }> { + // No setting makes another host supported, so the host is refused before + // the configuration is read. + if (this.platform !== "linux") { + const reason = `Native mitmproxy capture decoding runs only on Linux; this host is ${this.platform}`; + throw new AnalysisCapabilityUnavailableError( + "mitmproxy", + OPERATION, + reason, + { + userMessage: `${reason}. HAR needs no external engine.`, + remediationAction: `Decode native mitmproxy captures on a Linux host with REA_MITMDUMP_COMMAND set, or supply a HAR capture; no setting enables native decoding on this host.`, + }, + ); + } const command = this.environment.REA_MITMDUMP_COMMAND; - if ( - this.platform !== "linux" || - command === undefined || - !isAbsolute(command) - ) + if (command === undefined || !isAbsolute(command)) throw new AnalysisCapabilityUnavailableError( "mitmproxy", OPERATION, diff --git a/src/contracts/apkSignature/apkSignatureToolContracts.ts b/src/contracts/apkSignature/apkSignatureToolContracts.ts index 11caa8a6ec1..8f9c555d538 100644 --- a/src/contracts/apkSignature/apkSignatureToolContracts.ts +++ b/src/contracts/apkSignature/apkSignatureToolContracts.ts @@ -16,7 +16,6 @@ export const INSPECT_APK_SIGNATURE_CONTRACT = { cli: true, ...toolContractMetadata("inspect_apk_signature", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect declared APK v1/v2/v3/v3.1 signers, certificate fingerprints, digests, SDK ranges, rotation lineage and source stamp without executing Android code. Returns exact file SHA-256; identities include scheme/source ordinal and certificates retain DER digests. Default summary retains complete Evidence; optional view selects signers/digests/lineage by IDs/schemes/fields and pages. Reuse inspect_analysis_view kind apk-signature after removing the source. Matching content digests do not verify signatures or authenticity; lineage trust and v1 entry coverage remain unverified. No device, network or SDK; malformed structures and resource refusals are explicit.", inputSchema: inspectApkSignatureInputSchema, diff --git a/src/contracts/artifactToolContracts.ts b/src/contracts/artifactToolContracts.ts index 3e42498cce3..de6c4a61010 100644 --- a/src/contracts/artifactToolContracts.ts +++ b/src/contracts/artifactToolContracts.ts @@ -100,7 +100,9 @@ const artifact = < description: string, inputSchema: Schema, retainedSummary?: ToolContract["retainedSummary"], - requiresActiveTarget = true, + // `inspect_artifact` reads its `path`, else the open target: whether it + // needs a target depends on the request, so it declares none. + prerequisite: "active-target" | "request-dependent" = "active-target", ) => { const outputSchema = requireOutputSchema(artifactOutputSchemas, name); return { @@ -109,7 +111,9 @@ const artifact = < description, kind: "artifact-provider", cli: true, - requiresActiveTarget, + ...(prerequisite === "active-target" + ? { availability: "active-target" as const } + : {}), ...(retainedSummary === undefined ? {} : { retainedSummary }), inputSchema, outputSchema, @@ -130,7 +134,7 @@ export const ARTIFACT_TOOL_CONTRACTS = [ "Inventory an archive, app package, directory, firmware container or supported packaged executable without running it: the path given, else the open target. A directory's subject is its content-addressed root digest; a walk a limit stops is partial and has none. Returns nested content-addressed inventory Evidence with integrity observations, unexplored branches and next probes. Default complete returns the full graph; detail summary retains it for inspect_analysis_view kind inventory using parent_evidence_id, exact paths/IDs, path globs, size order, fields and paging. Summary changes delivery, not inventory coverage. Bun/Node SEA/Deno carriers expose stored modules/assets and recorded metadata; opaque bytecode and npm snapshots are not decoded. Local Evidence can include environment-file values and certificate bytes. iNES and NES 2.0 add file-region/reconstruction facts, not mapper execution. Integrity mismatches fail unless record-and-continue explicitly retains untrusted contradictions. Supported macOS DMGs are mounted read-only. Use extract_artifact to materialize regular contents; DMGs instead need a caller-managed read-only mount.", artifactInspectionInputSchema, { evidenceParameters: "preserve-detail" }, - false, + "request-dependent", ), artifact( "extract_artifact", diff --git a/src/contracts/captures/captureToolContracts.ts b/src/contracts/captures/captureToolContracts.ts index c6f5a2a96af..59165b6c00a 100644 --- a/src/contracts/captures/captureToolContracts.ts +++ b/src/contracts/captures/captureToolContracts.ts @@ -23,7 +23,6 @@ export const CAPTURE_TOOL_CONTRACTS = [ }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "Find protocols or field definitions registered in installed TShark 4.x. kind defaults to protocols; use fields with an optional exact protocol abbreviation, then pass selected names to inspect_packet_capture. query is a case-insensitive literal substring. Returns definitions, duplicate registrations, source lines, tool identity and coverage; offset/limit pages matches (default 50; null means all remaining). Requires Linux, prlimit and TShark on PATH or absolute REA_TSHARK_COMMAND. Each call rereads the glossary. No capture/target is needed; registrations describe capabilities, not observed traffic.", inputSchema: inspectPacketFieldsInputSchema, @@ -49,7 +48,6 @@ export const CAPTURE_TOOL_CONTRACTS = [ }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "Extract caller-selected TShark fields from a saved packet capture, with display filters, decode-as rules and pass mode preserved. Returns frame numbers, repeated values, coverage and diagnostics; use inspect_pcap_capture for a prepared endpoint/DNS/TLS/HTTP summary. Defaults to 50 matching frames; match_offset/match_limit page output and null requests all remaining. packet_limit counts input packets before filtering; output paging does not shorten dissection or reassembly. Requires Linux, prlimit and TShark 4.x on PATH or absolute REA_TSHARK_COMMAND. No live capture/device communication; no matches does not prove absence of traffic.", inputSchema: inspectPacketCaptureInputSchema, diff --git a/src/contracts/catalog/catalogIdentity.ts b/src/contracts/catalog/catalogIdentity.ts index 6d7eef04015..52b13c0e459 100644 --- a/src/contracts/catalog/catalogIdentity.ts +++ b/src/contracts/catalog/catalogIdentity.ts @@ -5,6 +5,7 @@ import { promptsForToolFamilies } from "../promptToolFamilyScope.js"; import { PROMPT_CONTRACTS } from "../promptContracts.js"; import type { PromptContract } from "../promptContracts.js"; import { TOOL_CONTRACTS } from "../toolContracts.js"; +import { describeToolPrerequisite } from "../toolAvailability.js"; import type { ToolContract } from "../toolContractTypes.js"; import { CLI_COMMANDS, cliCommandFor } from "../cliCommandNames.js"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; @@ -59,7 +60,10 @@ const createToolCatalog = (contracts: readonly ToolContract[]) => name: contract.name, title: contract.title, surface: contract.kind, - description: contract.description, + description: describeToolPrerequisite( + contract.description, + contract.availability, + ), effects: { ...contract.effects }, returns_target_content: contract.returnsTargetContent, annotations: contract.annotations, diff --git a/src/contracts/cutterToolContracts.ts b/src/contracts/cutterToolContracts.ts index 6959ce78268..3cd170f93f4 100644 --- a/src/contracts/cutterToolContracts.ts +++ b/src/contracts/cutterToolContracts.ts @@ -72,7 +72,7 @@ export const CUTTER_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Run one arbitrary Rizin command in a selected Cutter session; it may persist edits or execute plugin effects. Reports completion uncertainty as Evidence; do not retry automatically. An admitted command retires shared binary analysis: close active Ghidra explicitly first, then reopen with open_binary after command effects settle. Supply session_id and expected_generation from discovery. REA_BRIDGE_MAX_REQUEST_BYTES bounds authenticated request/response payloads excluding LF (default 16777216, range 7464..536870887); mismatched client/Cutter budgets refuse dispatch. An out-of-band Cutter without this setting uses the default.", + "Run one arbitrary Rizin command in a selected Cutter session; it may persist edits or execute plugin effects. Reports completion uncertainty as Evidence; do not retry automatically. An admitted command retires shared binary analysis: call close_binary first if Ghidra is active, then reopen with open_binary after command effects settle. Supply session_id and expected_generation from discovery. REA_BRIDGE_MAX_REQUEST_BYTES bounds authenticated request/response payloads excluding LF (default 16777216, range 7464..536870887); mismatched client/Cutter budgets refuse dispatch. An out-of-band Cutter without this setting uses the default.", inputSchema: cutterCommandInputSchema, outputSchema: evidenceResultOf(cutterCommandResultSchema), examples: [ diff --git a/src/contracts/deb/debPackageToolContracts.ts b/src/contracts/deb/debPackageToolContracts.ts index 660466ef3b2..7add83bb2f4 100644 --- a/src/contracts/deb/debPackageToolContracts.ts +++ b/src/contracts/deb/debPackageToolContracts.ts @@ -14,7 +14,6 @@ export const DEB_PACKAGE_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_deb_package", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect a local Debian .deb without installing it, running maintainer scripts, or contacting a mirror. Returns the ar container (magic, members, debian-binary version), control fields (Package, Version with epoch/revision, Architecture, Maintainer, relationships parsed into alternatives with operators and arch qualifiers), conffiles/md5sums presence and counts, maintainer-script interpreter lines and byte lengths, and a bounded data.tar file inventory with an md5sums path cross-check. gzip, zstd, xz, and uncompressed control/data members are decoded in-process; bzip2 and lzma members are unsupported. Missing optional fields stay null, not empty. Malformed or truncated ar/tar input is a typed refusal that retains members already parsed. Package signatures are not verified. Complete Evidence is the result.", inputSchema: inspectDebPackageInputSchema, diff --git a/src/contracts/desktopApplicationToolContracts.ts b/src/contracts/desktopApplicationToolContracts.ts index 6e51867cd9e..0253589e07d 100644 --- a/src/contracts/desktopApplicationToolContracts.ts +++ b/src/contracts/desktopApplicationToolContracts.ts @@ -16,7 +16,6 @@ export const DESKTOP_APPLICATION_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_desktop_application", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Identify runtime candidates and next probes in a local desktop app directory from bounded listings, headers and metadata. Recognizes .NET, Unity Mono/IL2CPP, Unreal, Godot, GameMaker and Electron, else native executables with Qt/SDL/MSVC markers; returns supporting paths and range hashes. Probes are ranked application-first and runtime facades are counted in deferred_probes. Default summary retains complete Evidence for inspect_analysis_view kind desktop-application; detail complete returns retained facts inline. Identity covers examined ranges, not every file byte. Coverage and unavailable probes remain explicit. No target execution, extraction, network or target changes.", inputSchema: inspectDesktopApplicationInputSchema.extend({ diff --git a/src/contracts/enhancedToolContracts.ts b/src/contracts/enhancedToolContracts.ts index b7e1932a69f..940b0444462 100644 --- a/src/contracts/enhancedToolContracts.ts +++ b/src/contracts/enhancedToolContracts.ts @@ -41,7 +41,7 @@ const enhanced = < description, kind: "enhanced", ...(ENHANCED_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), - requiresActiveTarget: true, + availability: "active-target", inputSchema, outputSchema: requireOutputSchema(enhancedOutputSchemas, name), examples: examplesFor(name, inputSchema), diff --git a/src/contracts/erlang/beamToolContracts.ts b/src/contracts/erlang/beamToolContracts.ts index b98b33f3a28..611b7b1f30d 100644 --- a/src/contracts/erlang/beamToolContracts.ts +++ b/src/contracts/erlang/beamToolContracts.ts @@ -33,7 +33,6 @@ export const ERLANG_BEAM_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_erlang_beam", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect an Erlang BEAM IFF file without executing bytecode or requiring Erlang. Returns chunk byte ranges/digests, atoms, exports/imports/lambdas and Code header. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it, and an optional beam view selects collection rows in the first call. Reuse inspect_analysis_view kind beam for atoms/exports/imports/lambdas/chunks, exact names/indices/fields and paging. source_index scopes rows to parent/collection, preserving every arity; original atom/lambda indices remain distinct. Missing tables/counts stay null, not empty; runtime absence is unknown. Malformed/truncated input or exhausted budgets fail without partial success.", inputSchema: inspectErlangBeamRequestSchema, diff --git a/src/contracts/evm/evmToolContracts.ts b/src/contracts/evm/evmToolContracts.ts index 2cf1b6a299b..345b337128f 100644 --- a/src/contracts/evm/evmToolContracts.ts +++ b/src/contracts/evm/evmToolContracts.ts @@ -31,7 +31,6 @@ export const INSPECT_EVM_INTERFACE_CONTRACT = { }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "Infer interface candidates from explicit local flat EVM bytecode using the bundled EVMole WASM engine. Select raw or hex encoding. Linux x64 profile; EOF-style EF00 containers are unsupported. Returns selectors, offsets, arguments and mutability candidates, not verified deployment or runtime behavior. Bytecode kind, hardfork and discovery completeness stay unknown. Default complete includes bytecode/full Evidence; detail summary retains it for inspect_analysis_view kind evm, facets functions/bytecode_hex/stdout/stderr, via parent_evidence_id. timeout_ms and producer_limits are independent of each other and worker heap; tighter inherited limits still apply. No target execution, chain/RPC access, signature lookup, wallet action or broadcast.", inputSchema: evmInterfaceInspectionInputSchema, diff --git a/src/contracts/functionWorkflowToolContracts.ts b/src/contracts/functionWorkflowToolContracts.ts index 7ec1146dfbe..5f0c4a94f46 100644 --- a/src/contracts/functionWorkflowToolContracts.ts +++ b/src/contracts/functionWorkflowToolContracts.ts @@ -48,7 +48,7 @@ const functionWorkflow = ( ...(FUNCTION_WORKFLOW_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), - requiresActiveTarget: true, + availability: "active-target", inputSchema, outputSchema, examples: [ diff --git a/src/contracts/gdbToolContracts.ts b/src/contracts/gdbToolContracts.ts index b5cabbf9a2f..2db98719f0d 100644 --- a/src/contracts/gdbToolContracts.ts +++ b/src/contracts/gdbToolContracts.ts @@ -66,7 +66,7 @@ export const GDB_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Run one unrestricted command in a persistent GDB session; commands can run shell, change target state, access files and network. Returns ordered MI/console/target/log Evidence. A timeout retains collected records with completion_status unknown and stops the owned debugger; closing does not imply target termination. Omitted detail preserves full Evidence within the agent result budget, else the retained summary; summary retains it and omits duplicate stream/raw mirrors for inspect_analysis_view summary queries. In a shared server this command retires active binary analysis: close Ghidra explicitly first, then reopen the binary after command effects settle.", + "Run one unrestricted command in a persistent GDB session; commands can run shell, change target state, access files and network. Returns ordered MI/console/target/log Evidence. A timeout retains collected records with completion_status unknown and stops the owned debugger; closing does not imply target termination. Omitted detail preserves full Evidence within the agent result budget, else the retained summary; summary retains it and omits duplicate stream/raw mirrors for inspect_analysis_view summary queries. In a shared server this command retires active binary analysis: call close_binary first if Ghidra is active, then reopen the binary after command effects settle.", inputSchema: z.strictObject({ session_id: sessionId, command: z.string().min(1), @@ -142,7 +142,7 @@ export const GDB_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Close the owned GDB process after verifying the inferior state. When one live thread group has a verified durable output TTY, REA automatically detaches it, which may resume target execution; otherwise close reports that a disposition is required. REA never kills attached or remote targets as part of debugger cleanup. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", + "Close the owned GDB process after verifying the inferior state. When one live thread group has a verified durable output TTY, REA automatically detaches it, which may resume target execution; otherwise close reports that a disposition is required. REA never kills attached or remote targets as part of debugger cleanup. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. If Ghidra is active, call close_binary first.", inputSchema: z.strictObject({ session_id: sessionId }), outputSchema: z.strictObject({ target_state: z.enum(INFERIOR_DISPOSITIONS), diff --git a/src/contracts/go/goToolContracts.ts b/src/contracts/go/goToolContracts.ts index 78b65a0e6b7..0aef20d665e 100644 --- a/src/contracts/go/goToolContracts.ts +++ b/src/contracts/go/goToolContracts.ts @@ -15,7 +15,6 @@ export const GO_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_go_binary", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Read embedded Go compiler, module, dependency/replacement and build-setting metadata from a local ELF, PE or selected Mach-O slice without running it or requiring Go. include_string_literals: true adds inferred static UTF-8 literals; runtime use and dependency completeness remain unknown. Missing build info does not prove the image is not Go. Omitted detail returns artifact SHA-256, source ranges and original metadata within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind go, collections dependencies/settings/string_literals, or kind cyclonedx for one CycloneDX 1.6 document, with parent_evidence_id. Slice ranges remain offsets in the original universal file. No function/type/source recovery. Increase only the reported per-call budget and retry the same artifact; it does not raise parser or MCP delivery limits. Malformed/unsupported inputs fail explicitly.", inputSchema: inspectGoBinaryInputSchema, diff --git a/src/contracts/gpu/gpuToolContracts.ts b/src/contracts/gpu/gpuToolContracts.ts index 3677f574e45..20a58c7b732 100644 --- a/src/contracts/gpu/gpuToolContracts.ts +++ b/src/contracts/gpu/gpuToolContracts.ts @@ -17,7 +17,6 @@ export const GPU_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_gpu_code_objects", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect CUDA/HIP code objects in local ELF/PE, fatbins, CUBIN, PTX or Clang HIP bundles without GPU tools or target execution. Default inventory hashes the full file; analysis kernels decodes selected object_ids/targets, with object_ids requiring the inventory expected_sha256. IDs are positional within that digest. Returns distinct PTX/CUBIN/AMDGPU kernel declarations, encoded/decoded provenance and explicit partial/unknown coverage; unsupported compression retains encoded locations. Default summary retains complete Evidence. Optional view selects targets/objects/kernels or PTX text; inspect_analysis_view kind gpu-code-objects pages retained facts without reopening (PTX offsets are UTF-16 units). No SASS disassembly, host-launch correlation or network; decoded-work/retention limits remain independent of selection.", inputSchema: inspectGpuCodeObjectsInputSchema, diff --git a/src/contracts/il2cpp/il2cppToolContracts.ts b/src/contracts/il2cpp/il2cppToolContracts.ts index b5f9345785d..181fdcf8de7 100644 --- a/src/contracts/il2cpp/il2cppToolContracts.ts +++ b/src/contracts/il2cpp/il2cppToolContracts.ts @@ -16,7 +16,6 @@ export const IL2CPP_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_il2cpp_metadata", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect Unity IL2CPP metadata versions 24/27/29/31/39, optionally linking a selected 64-bit little-endian Mach-O/PE/ELF binary without execution. Returns metadata tables and derived native method links; shared addresses retain every method, zero slots mean no-body, and unknown ownership/relocations stay unknown. Default summary retains complete Evidence for inspect_analysis_view kind il2cpp-metadata using parent_evidence_id, named collections, original indices, fields and pages. Unrequested native counts are null; version27 names may be unknown. generic_instances adds supported static registration-table matches for versions 27/29/31. Executable-byte fallback is inferred and does not verify instruction boundaries. Full detail remains available; static agreement proves neither same-build pairing nor runtime behavior. Resource/unsupported-layout failures name their reasons.", inputSchema: inspectIl2cppMetadataInputSchema, diff --git a/src/contracts/javascript/electronToolContracts.ts b/src/contracts/javascript/electronToolContracts.ts index f385096c23b..4c521d2b19f 100644 --- a/src/contracts/javascript/electronToolContracts.ts +++ b/src/contracts/javascript/electronToolContracts.ts @@ -207,7 +207,6 @@ export const ELECTRON_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_electron_fuses", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect packaged Electron fuse bytes in one local macOS app bundle, Electron Framework binary, Windows PE executable, or Linux ELF executable. Returns the artifact digest, per-slice wire version, fuse index, version-1 name, state, and raw byte, plus derived implications for Inspector flags, ELECTRON_RUN_AS_NODE, embedded ASAR integrity, and app.asar-only loading. A missing sentinel is unknown fuse state. Reads artifact bytes only and does not modify the selected file or open a runtime target.", inputSchema: inspectElectronFusesInputSchema, diff --git a/src/contracts/labview/labviewToolContracts.ts b/src/contracts/labview/labviewToolContracts.ts index b7cfbbed771..3f6e26b3a9c 100644 --- a/src/contracts/labview/labviewToolContracts.ts +++ b/src/contracts/labview/labviewToolContracts.ts @@ -18,7 +18,6 @@ export const LABVIEW_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_labview_artifact", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect the RSRC container of a local LabVIEW artifact: a .vi/.ctl/.llb file, or a LabVIEW-built PE whose VI tree is stored in a resource. Returns artifact identity, container header facts, the LabVIEW version recorded by its vers block, and the block inventory with each section's coding and decoded byte count. zlib-coded sections are decoded for their byte count only; no section payload is returned. A missing block-diagram heap (BDH*) or front-panel heap (FPH*) is reported as an explicit limitation rather than reconstructed. Complete detail returns the block inventory inline; summary (or omitted detail over the agent result budget) retains complete Evidence for inspect_analysis_view kind labview-artifact (collections blocks and sections, filterable by block) or evidence-json. Reads existing files only and starts no process; malformed or oversized containers fail rather than return a partial inventory.", inputSchema: inspectLabviewArtifactInputSchema.extend({ diff --git a/src/contracts/model/modelToolContracts.ts b/src/contracts/model/modelToolContracts.ts index 0f67514e4c6..36928dea3a7 100644 --- a/src/contracts/model/modelToolContracts.ts +++ b/src/contracts/model/modelToolContracts.ts @@ -15,7 +15,6 @@ export const INSPECT_MODEL_ARTIFACT_CONTRACT = { cli: true, ...toolContractMetadata("inspect_model_artifact", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: 'Inspect GGUF v2/v3 or safetensors metadata and tensor declarations without loading weights or running inference. Default hash header commits only a prefix: full-file SHA-256 and Evidence subject remain unknown; hash full streams every byte for file identity. Tensor shapes/IDs/offsets are observed; textual types and totals are derived, with ambiguous layouts retaining unknown byte lengths. Metadata arrays are eight-element previews; scalar metadata is complete. Default summary retains complete Evidence; detail complete returns all declarations inline. Optional view selects metadata/tensors/types. To page retained tensors, use inspect_analysis_view with source:{kind:"retained-evidence",evidence_id:""} and view:{kind:"model-artifact",collection:"tensors",offset:0,limit:32}. No payload inspection, quality claim, network, model runtime or pickle deserialization; one inspection at a time with explicit resource refusals.', inputSchema: inspectModelArtifactInputSchema, diff --git a/src/contracts/native/nativeToolContracts.ts b/src/contracts/native/nativeToolContracts.ts index b078eea42b1..1d27eb79b5f 100644 --- a/src/contracts/native/nativeToolContracts.ts +++ b/src/contracts/native/nativeToolContracts.ts @@ -64,7 +64,7 @@ const native = < description, kind: "native-provider", cli: true, - requiresActiveTarget: true, + availability: "active-target", ...(retainedSummary === undefined ? {} : { retainedSummary }), inputSchema: strictInputSchema, outputSchema, diff --git a/src/contracts/nuget/nupkgToolContracts.ts b/src/contracts/nuget/nupkgToolContracts.ts index a45b6c3feb7..dad52139433 100644 --- a/src/contracts/nuget/nupkgToolContracts.ts +++ b/src/contracts/nuget/nupkgToolContracts.ts @@ -18,7 +18,6 @@ export const NUGET_NUPKG_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_nuget_nupkg", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect a local NuGet .nupkg ZIP without restoring, executing, or contacting a feed. Returns package identity (id, version, authors, description), license and repository fields as present in the .nuspec, dependency groups with target frameworks and version ranges, and a ZIP contents inventory (entry names, sizes, encrypted flag, path-derived folder roles). Missing, ambiguous, or malformed .nuspec members succeed with inventory and explicit limitations. Encrypted members are listed and not extracted. Invalid ZIP input fails without partial success. Member roles are folder conventions, not restore-time asset selection. Omitted detail returns complete Evidence within the agent result budget and otherwise the retained summary of identity, license, repository and dependency/content counts; inspect_analysis_view kind evidence-json pages the complete record.", inputSchema: inspectNugetNupkgInputSchema.extend({ diff --git a/src/contracts/oci/ociImageLayoutToolContracts.ts b/src/contracts/oci/ociImageLayoutToolContracts.ts index 3155a76f2f1..60f91a328d2 100644 --- a/src/contracts/oci/ociImageLayoutToolContracts.ts +++ b/src/contracts/oci/ociImageLayoutToolContracts.ts @@ -18,7 +18,6 @@ export const OCI_IMAGE_LAYOUT_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_oci_image_layout", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect a local OCI image-layout directory (oci-layout, index.json, blobs/) without unpacking a tar, decompressing layers, executing the image, or contacting a registry. Returns layout version, index entries (media type, digest, size, platform, annotations), nested indexes within a depth bound, image config facts (architecture/os/variant, created, author, User, Env names and values (null when include_env_values is false), Entrypoint, Cmd, WorkingDir, ExposedPorts, Volumes, Labels, StopSignal, rootfs.diff_ids, history), layers, and streamed SHA-256 (and SHA-512 when declared) verification of present referenced blobs. Missing blobs, digest/size mismatches, unreferenced blobs, unknown media types, unsupported digest algorithms, and symlink blobs are findings. Directory form only. Omitted detail returns complete Evidence within the agent result budget and otherwise the retained summary of layout identity, coverage, and index/image/blob/finding counts; inspect_analysis_view kind evidence-json pages the complete record.", inputSchema: inspectOciImageLayoutInputSchema.extend({ diff --git a/src/contracts/officialToolContracts.ts b/src/contracts/officialToolContracts.ts index abaeb44cb09..31e33ed9785 100644 --- a/src/contracts/officialToolContracts.ts +++ b/src/contracts/officialToolContracts.ts @@ -70,7 +70,7 @@ const official = < description, kind: "official-proxy", ...(OFFICIAL_CLI_CONTRACTS.has(name) ? { cli: true as const } : {}), - requiresActiveTarget: true, + availability: "active-target", ...(retainedSummary === undefined ? {} : { retainedSummary }), inputSchema: strictInputSchema, outputSchema: requireOutputSchema(officialOutputSchemas, name), diff --git a/src/contracts/python/pythonPycToolContracts.ts b/src/contracts/python/pythonPycToolContracts.ts index 0acb04e5761..7f36fa7367f 100644 --- a/src/contracts/python/pythonPycToolContracts.ts +++ b/src/contracts/python/pythonPycToolContracts.ts @@ -33,7 +33,6 @@ export const PYTHON_PYC_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_python_pyc", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect local CPython 3.7–3.15 .pyc headers and nested code objects without executing bytecode, invoking Python or recovering source. Returns pinned version/header fields, names, constant summaries and bytecode lengths/digests; nested_code links code constants, not runtime calls. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind python-pyc, collection code_objects, with exact names/indices/fields and paging. source_index preserves same-name alternatives. Unsupported magics/layouts, truncation and exhausted budgets fail without partial success. A header does not prove matching .py source exists.", inputSchema: inspectPythonPycRequestSchema, diff --git a/src/contracts/reverseEngineeringToolContracts.ts b/src/contracts/reverseEngineeringToolContracts.ts index 78b029f121d..626e7fdb0b1 100644 --- a/src/contracts/reverseEngineeringToolContracts.ts +++ b/src/contracts/reverseEngineeringToolContracts.ts @@ -59,7 +59,7 @@ export const REVERSE_ENGINEERING_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Run one caller-selected Rizin command on a local artifact. Commands/plugins can execute code, mutate files, access network and read outside the artifact; those external inputs are not Evidence-bound. Suppresses user settings/scripts but retains plugins. Raw stdout/stderr is authoritative, JSON is command-specific, and UTF-8 loss/truncation is explicit; output-limit termination leaves completion unknown. Rizin exits 0 even when its shell refuses a statement; completion_status rejected marks that refusal, and later statements did not run. Other command failures can still exit 0, so inspect stderr before treating empty output as absence. Before each command REA also runs the selected executable with -v; provider.name/version come from its banner and can name another tool REA_RIZIN_COMMAND selected, such as radare2, or are assumed without an identifying banner (provider_identity). For raw images, asm_arch/asm_bits/asm_cpu select decoding and base_address maps offset 0; base_address also passes -n to skip loaders even on ELF, without REA confirming either. An admitted command retires shared binary analysis: close Ghidra explicitly first, then open_binary after effects settle. command_timeout_ms is per-phase and max_output_bytes bounds combined output (16 MiB default); both apply next call without restart and do not raise client receive limits or persistent debugger deadlines.", + "Run one caller-selected Rizin command on a local artifact. Commands/plugins can execute code, mutate files, access network and read outside the artifact; those external inputs are not Evidence-bound. Suppresses user settings/scripts but retains plugins. Raw stdout/stderr is authoritative, JSON is command-specific, and UTF-8 loss/truncation is explicit; output-limit termination leaves completion unknown. Rizin exits 0 even when its shell refuses a statement; completion_status rejected marks that refusal, and later statements did not run. Other command failures can still exit 0, so inspect stderr before treating empty output as absence. Before each command REA also runs the selected executable with -v; provider.name/version come from its banner and can name another tool REA_RIZIN_COMMAND selected, such as radare2, or are assumed without an identifying banner (provider_identity). For raw images, asm_arch/asm_bits/asm_cpu select decoding and base_address maps offset 0; base_address also passes -n to skip loaders even on ELF, without REA confirming either. An admitted command retires shared binary analysis: call close_binary first if Ghidra or a resource-only session is active, then open_binary after effects settle. command_timeout_ms is per-phase and max_output_bytes bounds combined output (16 MiB default); both apply next call without restart and do not raise client receive limits or persistent debugger deadlines.", inputSchema: rizinInputSchema, outputSchema: evidenceResultOf(commandObservationSchema), examples: [ diff --git a/src/contracts/rizinDebugToolContracts.ts b/src/contracts/rizinDebugToolContracts.ts index ef9caad2c47..26219e3c193 100644 --- a/src/contracts/rizinDebugToolContracts.ts +++ b/src/contracts/rizinDebugToolContracts.ts @@ -39,7 +39,7 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Start a persistent Rizin debugger for one selected target/backend. Linux and a caller-selected TTY for inferior stdin/stdout/stderr are required; the target may use that terminal after detach. Startup suppresses user settings/scripts while retaining plugins. Detach requires verified output sinks, no target access to the debugger command stream, and dbg.exitkills=false. Capabilities depend on the installed backend. This shared-server operation retires binary analysis: close Ghidra explicitly first, then reopen the binary after effects settle.", + "Start a persistent Rizin debugger for one selected target/backend. Linux and a caller-selected TTY for inferior stdin/stdout/stderr are required; the target may use that terminal after detach. Startup suppresses user settings/scripts while retaining plugins. Detach requires verified output sinks, no target access to the debugger command stream, and dbg.exitkills=false. Capabilities depend on the installed backend. This shared-server operation retires binary analysis: call close_binary first if Ghidra is active, then reopen the binary after effects settle.", inputSchema: z.strictObject({ path: absoluteLocalPathStringSchema, inferior_tty: absoluteLocalPathStringSchema, @@ -74,7 +74,7 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Run one unrestricted command in a persistent Rizin debugger; it can access target state, plugins, shell, files and network. Returns raw/interleaved session output as Evidence. Output/frame limits stop the owned debugger and retain partial output with output_truncated and unknown completion. Prequeued unsolicited frames refuse the call because correlation is ambiguous. This shared-server operation retires binary analysis: close Ghidra explicitly first, then reopen the binary after effects settle.", + "Run one unrestricted command in a persistent Rizin debugger; it can access target state, plugins, shell, files and network. Returns raw/interleaved session output as Evidence. Output/frame limits stop the owned debugger and retain partial output with output_truncated and unknown completion. Prequeued unsolicited frames refuse the call because correlation is ambiguous. This shared-server operation retires binary analysis: call close_binary first if Ghidra is active, then reopen the binary after effects settle.", inputSchema: z.strictObject({ session_id: sessionId, command: z @@ -148,7 +148,7 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Close the REA-owned Rizin debugger after verifying no inferior remains, detaching one with a verified caller-selected TTY output sink, or terminating the debugger when a desynchronized command transport cannot resynchronize. A detached target may continue running, read from and write to that TTY; a target whose detach was not verified may keep running with unknown state and output route. REA never signals an inferior based on PID or path. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. Close an active Ghidra session explicitly first.", + "Close the REA-owned Rizin debugger after verifying no inferior remains, detaching one with a verified caller-selected TTY output sink, or terminating the debugger when a desynchronized command transport cannot resynchronize. A detached target may continue running, read from and write to that TTY; a target whose detach was not verified may keep running with unknown state and output route. REA never signals an inferior based on PID or path. target_state reports what cleanup established: none_observed, detached, exited, or unknown when the debugger was terminated without a verified detach. In a shared MCP server, this admitted close retires any active binary-analysis session; after target effects have settled, call open_binary before further analysis. If Ghidra is active, call close_binary first.", inputSchema: z.strictObject({ session_id: sessionId }), outputSchema: z.strictObject({ target_state: z.enum(INFERIOR_DISPOSITIONS), diff --git a/src/contracts/rust/rustToolContracts.ts b/src/contracts/rust/rustToolContracts.ts index 09dc59a4c64..ad2fb2044a1 100644 --- a/src/contracts/rust/rustToolContracts.ts +++ b/src/contracts/rust/rustToolContracts.ts @@ -17,7 +17,6 @@ export const RUST_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_rust_binary", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Read the embedded cargo-auditable crate dependencies of a local ELF, PE, selected Mach-O slice or WebAssembly core module without running it or requiring Rust. Returns artifact identity, source ranges, ordered packages and dependency edges. Missing metadata does not prove no dependencies; a rustc commit from an observed source path is inferred. Omitted detail returns the report within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind rust, collections packages/edges, or kind cyclonedx for one CycloneDX 1.6 document, via parent_evidence_id. Optional view selects a page in this call and cannot accompany explicit complete detail. Original row indices and every matching version survive selection; select dependencies explicitly for package dependency vectors. Runtime dependencies remain unknown; malformed or oversized inputs fail rather than return partial success.", inputSchema: inspectRustBinaryRequestSchema, diff --git a/src/contracts/sessionToolContracts.ts b/src/contracts/sessionToolContracts.ts index 4aa66775655..0124adaf2cf 100644 --- a/src/contracts/sessionToolContracts.ts +++ b/src/contracts/sessionToolContracts.ts @@ -246,7 +246,7 @@ export const SESSION_TOOL_CONTRACTS = [ "Return the selected document, current address, and containing/current procedure in one provider-neutral result. The result reflects sequential provider observations, not an atomic cursor snapshot; a cursor outside any procedure returns procedure: null.", navigationContextInputSchema, ), - requiresActiveTarget: true, + availability: "active-target", }, { ...session( @@ -258,6 +258,6 @@ export const SESSION_TOOL_CONTRACTS = [ "Inspect one explicit reproducible address for its analyzed name, containing procedure, regular and inline comments, and matching bookmarks. Each unsupported facet returns a typed unavailable outcome. A facet rejected for invalid input, source Evidence integrity, or a resource constraint retains its canonical error and recovery alongside successful facets. Use xrefs, assembly, or pseudocode for those deeper views.", addressContextInputSchema, ), - requiresActiveTarget: true, + availability: "active-target", }, ] as const satisfies readonly ToolContract[]; diff --git a/src/contracts/signals/signalToolContracts.ts b/src/contracts/signals/signalToolContracts.ts index a5d23f10e09..1c4333d2403 100644 --- a/src/contracts/signals/signalToolContracts.ts +++ b/src/contracts/signals/signalToolContracts.ts @@ -23,7 +23,6 @@ export const SIGNAL_TOOL_CONTRACTS = [ }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "List installed sigrok decoder IDs/names, or supply an exact decoder ID to inspect its channel/option help. Use returned IDs/options with decode_signal_recording. query matches a case-insensitive literal substring; offset/limit pages matches (default 50; null means all remaining). Returns original help lines, coverage and current tool identity. Requires Linux, REA_SIGROK_COMMAND and prlimit. Each call probes again; decoder modules are trusted but not fully fingerprinted. No recording, target, hardware scan or acquisition.", inputSchema: inspectSignalDecodersInputSchema, @@ -49,7 +48,6 @@ export const SIGNAL_TOOL_CONTRACTS = [ }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "Decode a saved logic/signal recording with an explicitly selected sigrok decoder stack, channels and options. Returns literal text, sample ranges, diagnostics, source/tool identity and coverage. line_offset/line_limit page display lines (default 50; null means all remaining), not annotations or samples; paging does not shorten decoding. Requires Linux, sigrok-cli 0.7.2 through absolute REA_SIGROK_COMMAND, and prlimit. No acquisition or device communication. Empty output does not prove absent traffic.", inputSchema: decodeSignalRecordingInputSchema, diff --git a/src/contracts/sqlite/sqliteToolContracts.ts b/src/contracts/sqlite/sqliteToolContracts.ts index ff6a21800fe..b9439978546 100644 --- a/src/contracts/sqlite/sqliteToolContracts.ts +++ b/src/contracts/sqlite/sqliteToolContracts.ts @@ -20,7 +20,6 @@ export const SQLITE_TOOL_CONTRACTS = [ }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect a local SQLite snapshot and sibling WAL without modifying them. Returns their SHA-256 and schema inventory; select an exact ordinary table and columns for rows (default 20), or schema_scope database for expanded schema. row_offset pages a stated rowid/primary-key order while database/WAL digests match. A declared rowid alias can supply the order if all built-in aliases are shadowed. Values preserve 64-bit integers, text bytes and blobs with explicit truncation. Needs DatabaseSync.limits, so unavailable on Node.js 22.x. worker_timeout_ms bounds worker startup/query/reply work, not snapshot acquisition, cleanup or host delivery; independent safety budgets remain. Supply a quiescent snapshot; no atomic live-snapshot claim. No arbitrary SQL, WHERE/ORDER BY, views/virtual tables, extensions, repair or encryption. Two inspections may run per provider; occupied capacity is retryable. Temporary-copy/worker bounds do not cap overall native heap.", inputSchema: inspectSqliteDatabaseInputSchema, diff --git a/src/contracts/toolAvailability.ts b/src/contracts/toolAvailability.ts index 93f480bc9a9..a8ad26c560b 100644 --- a/src/contracts/toolAvailability.ts +++ b/src/contracts/toolAvailability.ts @@ -20,13 +20,34 @@ export type HostRestrictedFeature = (typeof HOST_RESTRICTED_FEATURES)[number]; * - `"standalone"`: a built-in workflow over caller-selected input. It needs * no optional provider, deep-analysis provider or host integration, so it * is always available. + * - `"active-target"`: the tool acts on the target opened by open_binary and + * dispatches through the binary-analysis session, so it needs one open + * before it can run. Its provider family still decides the rest. * - `{ host }`: an optional integration that the host must support and the * operator must configure; the inventory owns each feature's configuration * flag and remediation. * * A contract without a declaration takes its availability from its provider - * family, its active target, or a named rule in the inventory. + * family or a named rule in the inventory, and needs no open target. */ export type ToolAvailabilityDeclaration = | "standalone" + | "active-target" | { readonly host: HostRestrictedFeature }; + +/** + * The advertised statement of an `"active-target"` prerequisite. It is on + * each such tool's description, not only in server instructions, so it + * reaches clients that drop instructions or load one tool at a time. + */ +export const ACTIVE_TARGET_PREREQUISITE = + "Needs an open target: call open_binary first."; + +/** A tool's advertised description, ending with its declared prerequisite. */ +export const describeToolPrerequisite = ( + description: string, + availability: ToolAvailabilityDeclaration | undefined, +): string => + availability === "active-target" + ? `${description} ${ACTIVE_TARGET_PREREQUISITE}` + : description; diff --git a/src/contracts/toolContractTypes.ts b/src/contracts/toolContractTypes.ts index 7b358fd7ed5..2abda382f04 100644 --- a/src/contracts/toolContractTypes.ts +++ b/src/contracts/toolContractTypes.ts @@ -70,8 +70,6 @@ export interface ToolContract< * CLI command inventory is derived from this declaration. */ readonly cli?: true; - /** This handler dispatches through the active binary-analysis session. */ - readonly requiresActiveTarget?: boolean; /** Adapter delivery of a retained summary; detail never reaches analysis. */ readonly retainedSummary?: { readonly evidenceParameters: "omit-detail" | "preserve-detail"; diff --git a/src/contracts/vsix/vsixPackageToolContracts.ts b/src/contracts/vsix/vsixPackageToolContracts.ts index 6dcbcb12873..2c080b2848d 100644 --- a/src/contracts/vsix/vsixPackageToolContracts.ts +++ b/src/contracts/vsix/vsixPackageToolContracts.ts @@ -18,7 +18,6 @@ export const VSIX_PACKAGE_TOOL_CONTRACTS = [ cli: true, ...toolContractMetadata("inspect_vsix_package", evidenceEffects), kind: "artifact-provider", - requiresActiveTarget: true, description: "Inspect a local VS Code .vsix ZIP without installing, executing, or contacting a marketplace. Returns package identity from extension.vsixmanifest and extension/package.json with any disagreement, engine range, target platform, entry points and whether each resolves to a member, activation events (with * and onStartupFinished flagged as eager), a contributes summary, declared dependencies and pack members, untrusted/virtual workspace capabilities, API proposals, assets, a ZIP inventory with counts by kind, hashed native addons/wasm/executables/shell scripts/nested archives, and signature-file presence. Missing or malformed manifests succeed with inventory and explicit limitations. Encrypted members are listed and not extracted. Invalid ZIP input fails without partial success. Signature files are reported present or absent and are not verified. Omitted detail returns complete Evidence within the agent result budget and otherwise the retained summary of identity, entry points and inventory counts; inspect_analysis_view kind evidence-json pages the complete record.", inputSchema: inspectVsixPackageInputSchema.extend({ diff --git a/src/contracts/wasm/wasmToolContracts.ts b/src/contracts/wasm/wasmToolContracts.ts index 38f9f951dd8..1dc1d2189ff 100644 --- a/src/contracts/wasm/wasmToolContracts.ts +++ b/src/contracts/wasm/wasmToolContracts.ts @@ -30,7 +30,6 @@ export const INSPECT_WASM_ARTIFACT_CONTRACT = { }), ), kind: "artifact-provider", - requiresActiveTarget: true, description: `Validate and inspect local WASM with caller-supplied ${WABT_RELEASE_LINE}, without executing it or fetching dependencies. Returns artifact SHA-256, sections, import/export WAT forms and decoded WAT; custom-section interpretation warnings do not invalidate the core module. Omitted detail returns full Evidence within the agent result budget, else the retained summary; detail summary retains it for inspect_analysis_view kind wasm using normalized_result.parent_evidence_id, with import/export rows or UTF-16 WAT pages. Delivery does not change analysis. Optional JavaScript glue associations preserve ambiguous candidates. Configure absolute REA_WABT_BIN_DIRECTORY. Per-call command_timeout_ms, input/tool/output, interface-precision and auxiliary-path budgets are independent; reported limit errors identify the control to adjust. No installation or original-source claim.`, inputSchema: wasmArtifactInspectionInputSchema, outputSchema: analysisDetailOutputSchemaOf( diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index dc6d5167684..5b002ab144a 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -329,6 +329,11 @@ export const analysisErrorRemediationAction = ( } if (error instanceof UnknownRegistryError && error.reason === "not-found") return "Check that the unknown_id belongs to this session, then retry."; + if ( + error instanceof NoBinaryOpenError && + error.remediationAction !== undefined + ) + return error.remediationAction; return analysisErrorUserMessage(error); }; diff --git a/src/domain/configurationErrors.ts b/src/domain/configurationErrors.ts index 6f974e82f51..fd715899d70 100644 --- a/src/domain/configurationErrors.ts +++ b/src/domain/configurationErrors.ts @@ -46,13 +46,19 @@ export class ConfigurationError extends AnalysisError { } } +/** Recovery when nothing is open and no earlier cleanup must settle first. */ +export const NO_TARGET_RECOVERY = + "No app is open. Ask the user which app to investigate, then call open_binary with its local path."; + /** No app or binary session exists for an analysis request. */ export class NoBinaryOpenError extends AnalysisError { readonly _tag = "NoBinaryOpenError"; - constructor() { - super( - "No app is open. Ask the user which app to investigate, then call open_binary with its local path.", - ); + /** Session admission's recovery, when it differs from the message. */ + readonly remediationAction: string | undefined; + constructor(remediationAction?: string) { + super(NO_TARGET_RECOVERY); + this.remediationAction = + remediationAction === NO_TARGET_RECOVERY ? undefined : remediationAction; } } diff --git a/src/firmware/FirmwareCommand.test.ts b/src/firmware/FirmwareCommand.test.ts index bd79a0a7b19..48da2f6ffec 100644 --- a/src/firmware/FirmwareCommand.test.ts +++ b/src/firmware/FirmwareCommand.test.ts @@ -676,6 +676,29 @@ const signalTestGroupKill = (groupId: number): void => { // The injected launcher runs real owned Node processes on every POSIX host; // Linux firmware binaries and prlimit are deliberately outside this lifecycle seam. +test("refuses an unsupported host before reading the engine configuration", async () => { + const refusal: unknown = await resolveFirmwareCommand( + { REA_BINWALK_COMMAND: "/opt/binwalk" }, + "binwalk", + "inspect_firmware_regions", + new FirmwareFileAccess(), + "darwin", + ).catch((cause: unknown) => cause); + + if (!(refusal instanceof AnalysisCapabilityUnavailableError)) + throw new Error("Expected a capability refusal"); + // The remediation names the host, not the variable that is already set. + expect(projectAnalysisError(refusal)).toMatchObject({ + code: "capability_unavailable", + message: + "This firmware integration runs only on Linux; this host is darwin.", + remediation: { + action: + "Run inspect_firmware_regions on a Linux host with REA_BINWALK_COMMAND set; no setting enables it on this host.", + }, + }); +}); + test.skipIf(process.platform === "win32").each([ { overflow: false, diff --git a/src/firmware/FirmwareCommand.ts b/src/firmware/FirmwareCommand.ts index d438229fc1f..dba93583be7 100644 --- a/src/firmware/FirmwareCommand.ts +++ b/src/firmware/FirmwareCommand.ts @@ -133,16 +133,21 @@ export const resolveFirmwareCommand = async ( signal?: AbortSignal, ) => { const variable = FIRMWARE_TOOL_REQUIREMENTS[engine].commandEnvironment; + // No setting makes another host supported, so the host is refused before + // the configuration is read. + if (!firmwareHostSupported(platform)) { + const reason = `This firmware integration runs only on Linux; this host is ${platform}`; + throw new AnalysisCapabilityUnavailableError(engine, operation, reason, { + userMessage: `${reason}.`, + remediationAction: `Run ${operation} on a Linux host with ${variable} set; no setting enables it on this host.`, + }); + } const configured = environment[variable]; - if ( - !firmwareHostSupported(platform) || - configured === undefined || - !isAbsolute(configured) - ) + if (configured === undefined || !isAbsolute(configured)) throw firmwareToolUnavailable( engine, operation, - `This integration requires Linux and an absolute ${variable} path to the caller-supplied tool`, + `This integration requires an absolute ${variable} path to the caller-supplied tool`, ); const selection = await selectArtifactCommandPath(configured, signal).catch( (cause: unknown) => { diff --git a/src/javascript/recovery/WakaruCommand.test.ts b/src/javascript/recovery/WakaruCommand.test.ts index 72a5bf34dda..3ef8a433bf1 100644 --- a/src/javascript/recovery/WakaruCommand.test.ts +++ b/src/javascript/recovery/WakaruCommand.test.ts @@ -47,6 +47,26 @@ it("names the Wakaru configuration requirement when it is not configured", async }); }); +it("refuses an unsupported host before reading the Wakaru configuration", async () => { + const refusal: unknown = await resolveWakaruCommand( + { REA_WAKARU_COMMAND: "/opt/wakaru" }, + { platform: "darwin", architecture: "arm64" }, + ).catch((cause: unknown) => cause); + + if (!(refusal instanceof AnalysisCapabilityUnavailableError)) + throw new Error("Expected a capability refusal"); + // Setting REA_WAKARU_COMMAND cannot help on this host. + expect(projectAnalysisError(refusal)).toMatchObject({ + code: "capability_unavailable", + message: + "Wakaru recovery runs only on Linux x64; this host is darwin arm64.", + remediation: { + action: + "Run recover_javascript_sources on a Linux x64 host with REA_WAKARU_COMMAND set; no setting enables it on this host.", + }, + }); +}); + it("projects the fixed Wakaru deadline without an editable setting", async () => { const refusal: unknown = await runWakaruCommand({ resources: createTestArtifactResourceScope(), diff --git a/src/javascript/recovery/WakaruCommand.ts b/src/javascript/recovery/WakaruCommand.ts index a0cf501d55f..e66c74049d2 100644 --- a/src/javascript/recovery/WakaruCommand.ts +++ b/src/javascript/recovery/WakaruCommand.ts @@ -95,12 +95,17 @@ export const resolveWakaruCommand = async ( resources?: ArtifactResourceScope, signal?: AbortSignal, ) => { + // No setting makes another host supported, so the host is refused before + // the configuration is read. + if (!wakaruHostSupported(host.platform, host.architecture)) { + const reason = `Wakaru recovery runs only on Linux x64; this host is ${host.platform} ${host.architecture}`; + throw new AnalysisCapabilityUnavailableError("wakaru", OPERATION, reason, { + userMessage: `${reason}.`, + remediationAction: `Run ${OPERATION} on a Linux x64 host with REA_WAKARU_COMMAND set; no setting enables it on this host.`, + }); + } const configured = environment.REA_WAKARU_COMMAND; - if ( - !wakaruHostSupported(host.platform, host.architecture) || - configured === undefined || - !isAbsolute(configured) - ) + if (configured === undefined || !isAbsolute(configured)) throw new AnalysisCapabilityUnavailableError( "wakaru", OPERATION, diff --git a/src/pcap/PcapNativeBound.ts b/src/pcap/PcapNativeBound.ts index 1c56d69486b..31cf6c6c309 100644 --- a/src/pcap/PcapNativeBound.ts +++ b/src/pcap/PcapNativeBound.ts @@ -2,6 +2,7 @@ import { BOUNDED_PRODUCER_LIMITS } from "../domain/producerResourceLimits.js"; import { selectArtifactCommandPath } from "../process/ArtifactCommandPath.js"; import { pcapCaptureHostSupported, + PCAP_CAPTURE_HOST_REMEDIATION, PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, } from "../domain/pcap/pcapAnalysis.js"; import { access, stat } from "node:fs/promises"; @@ -25,6 +26,27 @@ import { errorMessage } from "../kernel/errorMessage.js"; const PRLIMIT_COMMAND_ENV = "REA_TSHARK_PRLIMIT_COMMAND"; /** Repair for an unusable selected capture limiter; readiness and admission share it. */ export const PCAP_LIMITER_REMEDIATION = `Check that ${PRLIMIT_COMMAND_ENV} (default /usr/bin/prlimit) names an absolute, executable util-linux prlimit.`; +/** + * Capture summaries need this host before anything else: no tool selection + * or setting can make an unsupported host enforce the native bound, so the + * host is checked before tshark is resolved. + */ +export const pcapCaptureHostRefusal = ( + platform: NodeJS.Platform, + operation: "inspect_pcap_client" | "inspect_pcap_capture", +): AnalysisCapabilityUnavailableError | undefined => + pcapCaptureHostSupported(platform) + ? undefined + : new AnalysisCapabilityUnavailableError( + "pcap", + operation, + PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, + { + userMessage: PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, + remediationAction: PCAP_CAPTURE_HOST_REMEDIATION, + }, + ); + /** Which stage an unsuccessful limited capture command's exit belongs to. */ export type PcapLimitedExitStage = | { readonly stage: "tool" } @@ -99,12 +121,8 @@ export const preparePcapNativeBound = async ( ], }; } - if (!pcapCaptureHostSupported(platform)) { - const reason = PCAP_CAPTURE_UNSUPPORTED_HOST_REASON; - throw new AnalysisCapabilityUnavailableError("pcap", operation, reason, { - userMessage: reason, - }); - } + const hostRefusal = pcapCaptureHostRefusal(platform, operation); + if (hostRefusal !== undefined) throw hostRefusal; const configured = environment[PRLIMIT_COMMAND_ENV] ?? "/usr/bin/prlimit"; let probeFailure: AnalysisError | undefined; let capturedOutput: AnalysisCapturedOutput | undefined; diff --git a/src/pcap/PcapProvider.ts b/src/pcap/PcapProvider.ts index c864d55eb02..99cfe1b371e 100644 --- a/src/pcap/PcapProvider.ts +++ b/src/pcap/PcapProvider.ts @@ -17,7 +17,6 @@ import { import { pcapResultSchemas, PCAP_CAPTURE_HOST_REMEDIATION, - pcapCaptureHostSupported, type PcapRequest, type PcapOperation, } from "../domain/pcap/pcapAnalysis.js"; @@ -72,7 +71,10 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { UnclassifiedProviderFailure } from "../domain/unclassifiedProviderFailure.js"; import { ownedJsonValueSchema } from "../domain/jsonValue.js"; import { createPcapEvidence } from "../domain/pcap/pcapEvidence.js"; -import { preparePcapNativeBound } from "./PcapNativeBound.js"; +import { + pcapCaptureHostRefusal, + preparePcapNativeBound, +} from "./PcapNativeBound.js"; import { PcapSnapshot } from "./PcapSnapshot.js"; import { readStableArtifact, @@ -682,17 +684,21 @@ export class PcapProvider { private async inspectAvailabilityAdmitted( signal?: AbortSignal, ): Promise { + const hostRefusal = pcapCaptureHostRefusal( + this.platform, + "inspect_pcap_client", + ); + if (hostRefusal !== undefined) + return { + status: "unavailable", + code: "unsupported_host", + reason: hostRefusal.reason, + remediation: PCAP_CAPTURE_HOST_REMEDIATION, + // No tool is resolved on a host that no setting can support. + diagnostics: {}, + }; try { const { client } = await this.client("inspect_pcap_client", signal); - if (!pcapCaptureHostSupported(this.platform)) - return { - status: "unavailable", - code: "unsupported_host", - reason: - "No enforceable native memory boundary is available for capture summaries on this host.", - remediation: PCAP_CAPTURE_HOST_REMEDIATION, - diagnostics: client, - }; await this.prepareCaptureBound("inspect_pcap_client", signal); return { status: "available", @@ -916,6 +922,11 @@ export class PcapProvider { let result: Result; try { if (signal?.aborted) throw cancelledBy(request.operation, signal); + const hostRefusal = + request.operation === "inspect_pcap_client" + ? undefined + : pcapCaptureHostRefusal(this.platform, request.operation); + if (hostRefusal !== undefined) throw hostRefusal; const { selection, client } = await this.client( request.operation, signal, diff --git a/src/server/ErrorEvidenceTransport.ts b/src/server/ErrorEvidenceTransport.ts index 99bafaed285..07b8f7d08ce 100644 --- a/src/server/ErrorEvidenceTransport.ts +++ b/src/server/ErrorEvidenceTransport.ts @@ -36,6 +36,10 @@ import { OwnerCancellation, type AnalysisInputIssue, } from "../domain/analysisErrorCore.js"; +import { + MCP_INPUT_SCHEMA_SPELLING, + renderInputSchemaRemediation, +} from "../domain/analysisErrorPresentation.js"; import { projectAnalysisErrorWithoutPartialObservation } from "../domain/analysisErrorProjection.js"; import { projectInputIssueGroupsWithinBudget } from "../domain/inputIssueProjection.js"; import { createEvidence } from "../domain/evidence.js"; @@ -51,7 +55,10 @@ import { measureMcpResultWithinBudget, TARGET_CONTENT_RESULT_META, } from "./toolResultEncoding.js"; -import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; +import type { + ToolAdmission, + WithAdmittedAnalysis, +} from "./analysisAdmission.js"; import type { McpToolsListPageBudget } from "../config/mcpToolsListPageBudget.js"; import { paginateToolsList } from "./toolListPagination.js"; import { @@ -250,6 +257,7 @@ export class ErrorEvidenceTransport extends ForwardingTransport { | undefined, private readonly currentDelivery: () => ToolResultDelivery, private readonly currentAdmission: () => WithAdmittedAnalysis | undefined, + private readonly currentToolAdmission: () => ToolAdmission | undefined, private readonly outputPresentation: AdvertisedToolPresentation["output"], private readonly maximumInputElements: number, private readonly evidenceReferenceAlternatives: ReadonlySet, @@ -858,7 +866,10 @@ export class ErrorEvidenceTransport extends ForwardingTransport { tool, ); const projectionLimited = validation !== undefined && groups === undefined; - const summary = `The arguments for MCP tool ${tool} do not match its advertised input schema.`; + // Correcting the arguments alone cannot succeed while the session would + // still refuse the tool, so its recovery comes first. + const refusal = this.currentToolAdmission()?.(tool); + const summary = `${refusal === undefined ? "" : `${refusal.cause} `}The arguments for MCP tool ${tool} do not match its advertised input schema.`; const partitioned = partitionSdkDiagnostic(validation, groups, diagnostic); const issues = partitioned?.issues ?? groups?.flat(); const error = new AnalysisInputError( @@ -874,6 +885,11 @@ export class ErrorEvidenceTransport extends ForwardingTransport { ? summary : `${summary} ${partitioned.remaining}` : `${summary} ${diagnostic}`, + ...(refusal === undefined + ? {} + : { + remediationAction: `${refusal.remediation} ${renderInputSchemaRemediation(tool, MCP_INPUT_SCHEMA_SPELLING)}`, + }), }, issues ?? [ { diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index 044a5655c45..7d59c3d90e6 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -39,7 +39,10 @@ import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js"; import { AnalysisTargetFailureError } from "../domain/analysisErrorCore.js"; import { DISCOVER_TOOLS } from "../contracts/catalog/catalogDiscovery.js"; import { ProgressiveToolCatalog } from "./ProgressiveToolCatalog.js"; -import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; +import type { + ToolAdmission, + WithAdmittedAnalysis, +} from "./analysisAdmission.js"; import { canReferenceInlineEvidence } from "./evidenceInputRegistration.js"; import { currentMcpToolRequest } from "./McpToolRequest.js"; import type { PromptCompletionSource } from "./promptCompletion.js"; @@ -155,6 +158,8 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { analysisSettings: AnalysisSettings | undefined; /** Transport-owned Evidence uses the same lifetime as application writes. */ withAdmittedAnalysis: WithAdmittedAnalysis | undefined; + /** Session admission, read when the SDK refuses a tool's arguments. */ + toolAdmission: ToolAdmission | undefined; private identity: ReturnType | undefined; /** Register an awaitable cleanup hook settled during {@link close}. */ @@ -598,6 +603,7 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { () => this.recordEvidence, () => this.delivery, () => this.withAdmittedAnalysis, + () => this.toolAdmission, this.presentation.output, this.maximumInputElements, this.evidenceReferenceAlternatives, diff --git a/src/server/analysisAdmission.ts b/src/server/analysisAdmission.ts index a44fd4946d5..26a4f96987c 100644 --- a/src/server/analysisAdmission.ts +++ b/src/server/analysisAdmission.ts @@ -1,5 +1,9 @@ import type { AnalysisOperationPort } from "../ports/AnalysisProvider.js"; import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; +import { + admitDeclaredTool, + type SessionRefusal, +} from "../application/binary/sessionAdmission.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { cancelledBy } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -17,6 +21,28 @@ export type ServerAnalysisSource = | { readonly kind: "session"; readonly session: BinarySessionPort } | { readonly kind: "fixed"; readonly analysis: AnalysisOperationPort }; +/** The session's current refusal of a named tool, if it would refuse it. */ +export type ToolAdmission = (tool: string) => SessionRefusal | undefined; + +/** + * Read session admission for a named tool from the source's owner. A fixed + * analysis has no session state to refuse on. A connection that cannot open + * a target itself supplies its own no-target recovery. + */ +export const toolAdmission = ( + source: ServerAnalysisSource, + noTargetRecovery?: string, +): ToolAdmission | undefined => + source.kind === "session" + ? (tool) => { + const refusal = admitDeclaredTool(tool, source.session.sessionLane()); + return refusal?.blocking === "no_target" && + noTargetRecovery !== undefined + ? { ...refusal, remediation: noTargetRecovery } + : refusal; + } + : undefined; + /** Run against the source's explicit owner, admitting session-scoped work. */ export const withAdmittedAnalysis = ( source: ServerAnalysisSource, diff --git a/src/server/contractToolHandler.ts b/src/server/contractToolHandler.ts index fa5c85218fc..e0b5cdfcb82 100644 --- a/src/server/contractToolHandler.ts +++ b/src/server/contractToolHandler.ts @@ -33,6 +33,7 @@ import type { ToolResultEncoding } from "./toolResultEncoding.js"; import { logToolExecution } from "./toolLogging.js"; import type { WithAdmittedAnalysis } from "./analysisAdmission.js"; import { runAdmittedToolOperation } from "./admittedToolOperation.js"; +import { sessionRefusalError } from "../application/binary/sessionAdmission.js"; import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; import type { InvestigationWorkflowExecution } from "../application/investigation/InvestigationWorkflows.js"; import { withAdmittedAnalysis as sessionAdmission } from "./analysisAdmission.js"; @@ -553,6 +554,14 @@ export const createAnalysisToolHandler = contract.name, signal, async (analysis) => { + // A composed workflow is refused as a whole, as binary_session + // reports it, not through each child operation it would dispatch. + const refusal = server.toolAdmission?.(contract.name); + if (refusal !== undefined) + return server.delivery.toErrorToolResult( + sessionRefusalError(contract.name, refusal), + contract.returnsTargetContent, + ); const progress = createOperationProgress( mcpProgressReporter(context), contract.name, diff --git a/src/server/createServer.ts b/src/server/createServer.ts index eba1df7d6d4..956c0759837 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -63,6 +63,7 @@ import type { AvailabilityPolicy } from "../application/CapabilityInventory.js"; import { sessionAvailabilityPolicy } from "./sessionAvailabilityPolicy.js"; import { withAdmittedAnalysis, + toolAdmission, type ServerAnalysisSource, } from "./analysisAdmission.js"; import { @@ -135,6 +136,17 @@ const createMcpServer = ( ); }; +/** A scoped connection without session tools cannot open a target itself. */ +const scopedNoTargetRecovery = ( + hasSession: boolean, + advertisedToolFamilies: ReadonlySet | undefined, +): string | undefined => + hasSession && + advertisedToolFamilies !== undefined && + !advertisedToolFamilies.has("session") + ? SCOPED_NO_TARGET_RECOVERY + : undefined; + /** * Construct one MCP server without acquiring subprocess resources. * Supplying a session adds target lifecycle tools; omitting it retains the @@ -166,12 +178,14 @@ export const createServer = ( host.platform, ); const baseDelivery = selectToolResultDelivery(environment, options.delivery); + const noTargetRecovery = scopedNoTargetRecovery( + session !== undefined, + advertisedToolFamilies, + ); const delivery = - session !== undefined && - advertisedToolFamilies !== undefined && - !advertisedToolFamilies.has("session") - ? baseDelivery.withNoTargetRecovery(SCOPED_NO_TARGET_RECOVERY) - : baseDelivery; + noTargetRecovery === undefined + ? baseDelivery + : baseDelivery.withNoTargetRecovery(noTargetRecovery); const capabilities = createCapabilityServices({ environment, providerEnvironment, @@ -338,6 +352,7 @@ export const createServer = ( if (evidenceById !== undefined) server.serveRetainedEvidence(evidenceById); const analysisAdmission = withAdmittedAnalysis(source); server.withAdmittedAnalysis = analysisAdmission; + server.toolAdmission = toolAdmission(source, noTargetRecovery); server.registerTransportCloseHook(() => { void closeProviders().catch((cause: unknown) => { logger.error( diff --git a/src/server/toolRegistrationOptions.ts b/src/server/toolRegistrationOptions.ts index 217ba044959..b20ce751e46 100644 --- a/src/server/toolRegistrationOptions.ts +++ b/src/server/toolRegistrationOptions.ts @@ -4,6 +4,7 @@ import { type ToolFamilyMeta, } from "../contracts/toolContractTypes.js"; import { toolFamilyId } from "../contracts/toolFamilies.js"; +import { describeToolPrerequisite } from "../contracts/toolAvailability.js"; import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server"; import type { z } from "zod"; import { @@ -24,7 +25,7 @@ export const toolRegistrationOptions = ( contract: Contract, ): { readonly title: Contract["title"]; - readonly description: Contract["description"]; + readonly description: string; readonly inputSchema: StandardSchemaWithJSON< z.input, EvidenceRequestFrameInput> @@ -52,7 +53,10 @@ export const toolRegistrationOptions = ( }; return { title: contract.title, - description: contract.description, + description: describeToolPrerequisite( + contract.description, + contract.availability, + ), inputSchema: evidenceInputs.hasEvidenceReferenceAlternative ? markEvidenceInput(inputSchema) : inputSchema, diff --git a/tests/boundary/browser/historicalCaptureDecoder.test.ts b/tests/boundary/browser/historicalCaptureDecoder.test.ts index 33edec762cc..1697563335e 100644 --- a/tests/boundary/browser/historicalCaptureDecoder.test.ts +++ b/tests/boundary/browser/historicalCaptureDecoder.test.ts @@ -30,6 +30,7 @@ import { historicalHar } from "../../fixtures/historicalHar.js"; import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { primaryAnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js"; import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js"; import { waitFor } from "../../support/testWait.js"; @@ -66,6 +67,24 @@ linux("allows a symlink to a regular mitmdump executable", async () => { ).resolves.toMatchObject({ command }); }); +it("refuses an unsupported host before reading the mitmdump configuration", async () => { + const refusal: unknown = await new MitmproxyCaptureAdapter( + { REA_MITMDUMP_COMMAND: "/opt/mitmdump" }, + "darwin", + ) + .command("/unused/request.json", "/unused/runtime") + .catch((cause: unknown) => cause); + if (!(refusal instanceof AnalysisCapabilityUnavailableError)) + throw new Error("Expected a capability refusal"); + // The variable is already set; the remediation names the host instead. + expect(projectAnalysisError(refusal)).toMatchObject({ + code: "capability_unavailable", + remediation: { + action: expect.stringContaining("on a Linux host"), + }, + }); +}); + it("keeps the admitted decoder environment across adapter preparation and refreshes it for the next call", async () => { const root = await createTestTempDirectory("rea-capture-environment-"); const path = join(root, "capture.har"); diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts index 32feff9c9a4..3a121d93264 100644 --- a/tests/boundary/mcp/serverIdentity.test.ts +++ b/tests/boundary/mcp/serverIdentity.test.ts @@ -28,6 +28,12 @@ import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaP import { sessionOutputSchemas } from "../../../src/contracts/toolOutputSchemaGroups.js"; import type { PromptContract } from "../../../src/contracts/promptContracts.js"; import { createServer } from "../../../src/server/createServer.js"; +import { ACTIVE_TARGET_PREREQUISITE } from "../../../src/contracts/toolAvailability.js"; +import { NO_TARGET_RECOVERY } from "../../../src/domain/configurationErrors.js"; +import { + MCP_INPUT_SCHEMA_SPELLING, + renderInputSchemaRemediation, +} from "../../../src/domain/analysisErrorPresentation.js"; import { createServerIdentity } from "../../../src/process/ServerIdentity.js"; import { observed } from "../../fixtures/analysisExecution.js"; import type { @@ -84,6 +90,18 @@ describe("server and catalog identity", () => { expect(changed.prompts_sha256).toBe(original.prompts_sha256); }); + it("covers the advertised open-target prerequisite in the tool and combined digests", () => { + const contract = toolContract("search_strings"); + expect(contract.availability).toBe("active-target"); + const original = createCatalogDigests([contract], []); + // A server that predates the advertised prerequisite sentence. + const { availability: _omitted, ...undeclared } = contract; + const changed = createCatalogDigests([undeclared], []); + expect(changed.combined_sha256).not.toBe(original.combined_sha256); + expect(changed.tools_sha256).not.toBe(original.tools_sha256); + expect(changed.prompts_sha256).toBe(original.prompts_sha256); + }); + it("binds output schema profile and canonical output contracts into identity", () => { const contract = toolContract("binary_session"); const profiles = createCatalogDigestProfiles([contract], []); @@ -379,6 +397,92 @@ describe("active-target availability over MCP", () => { }); }); +describe("active-target first contact over MCP", () => { + it("advertises the open-target prerequisite and names open_binary when arguments fail with no target", async () => { + const session = createTestBinarySession(availabilityProvider()); + const server = createServer( + { kind: "session", session }, + { environment: { REA_MCP_OUTPUT_SCHEMA_PROFILE: "off" } }, + ); + const client = new Client( + { name: "first-contact-test", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const directory = await createTestTempDirectory("rea-first-contact-"); + const executable = join(directory, "tool"); + await writeFile(executable, machoImage({})); + try { + await server.connect(serverTransport); + await client.connect(clientTransport); + const { tools } = await client.listTools(); + const described = (name: string) => + tools.find((tool) => tool.name === name)?.description ?? ""; + expect(described("search_strings")).toContain(ACTIVE_TARGET_PREREQUISITE); + // A tool that reads its own path never claims to need a target. + expect(described("inspect_go_binary")).not.toContain( + ACTIVE_TARGET_PREREQUISITE, + ); + // The file path belongs to open_binary, so fixing the arguments alone + // cannot succeed: the recovery names the open first. + const misdirected = { + name: "search_strings", + arguments: { path: executable }, + }; + const schemaRemediation = renderInputSchemaRemediation( + "search_strings", + MCP_INPUT_SCHEMA_SPELLING, + ); + expect( + parseMcpToolError(await client.callTool(misdirected)), + ).toMatchObject({ + error: { + code: "invalid_request", + remediation: { + action: `${NO_TARGET_RECOVERY} ${schemaRemediation}`, + }, + details: { + issues: expect.arrayContaining([ + expect.objectContaining({ + path: ["path"], + reason: "unknown_argument", + }), + ]), + }, + }, + }); + // A composed workflow with valid arguments is refused as a whole with + // the advertised recovery, not reported as a batch of child failures. + expect( + parseMcpToolError( + await client.callTool({ + name: "batch_decompile", + arguments: { addresses: ["0x1000"] }, + }), + ), + ).toMatchObject({ + error: { + code: "target_unavailable", + remediation: { action: NO_TARGET_RECOVERY }, + }, + }); + await openTarget(client, executable); + expect( + parseMcpToolError(await client.callTool(misdirected)), + ).toMatchObject({ + error: { remediation: { action: schemaRemediation } }, + }); + } finally { + await Promise.allSettled([ + client.close(), + server.close(), + session.close(), + ]); + } + }); +}); + const PLIST_XML = 'CFBundleNameFixture'; diff --git a/tests/boundary/mcp/serverWorkflowMcp.test.ts b/tests/boundary/mcp/serverWorkflowMcp.test.ts index 9d4c75f93dc..29120b0fd1e 100644 --- a/tests/boundary/mcp/serverWorkflowMcp.test.ts +++ b/tests/boundary/mcp/serverWorkflowMcp.test.ts @@ -1,4 +1,5 @@ import { structured } from "../../support/mcp/toolResult.js"; +import { describeToolPrerequisite } from "../../../src/contracts/toolAvailability.js"; import { connectFixtureClient } from "../../support/mcp/mcpFixture.js"; import { canonicalOutputSchema, @@ -162,7 +163,10 @@ it("advertises the complete currently available inventory with a session", async expect(tool.description, tool.name).toBe( advertiseTool( { - description: contract.description, + description: describeToolPrerequisite( + contract.description, + "availability" in contract ? contract.availability : undefined, + ), inputSchema: advertisedInputJsonSchema(contract), }, advertisedToolPresentation("off"), diff --git a/tests/boundary/mcp/targetContentFramingMcp.test.ts b/tests/boundary/mcp/targetContentFramingMcp.test.ts index 9135b448baa..d83c73a0c36 100644 --- a/tests/boundary/mcp/targetContentFramingMcp.test.ts +++ b/tests/boundary/mcp/targetContentFramingMcp.test.ts @@ -304,6 +304,19 @@ it.each([ }), ); expect(error.code).toBe("target_unavailable"); + // Malformed arguments with no target lead with the same scoped recovery. + const misdirected = parseMcpToolError( + await client.callTool({ + name: "read_bytes", + arguments: { path: "/tmp/x" }, + }), + ).error; + expect(misdirected.code).toBe("invalid_request"); + expect(misdirected.remediation.action).toMatch( + sessionAvailable + ? /^No app is open\..*call open_binary.*local path/iu + : /^No target is open, and this MCP connection does not advertise open_binary\..*add session to REA_MCP_TOOL_FAMILIES.*restart/iu, + ); if (sessionAvailable) { expect(error.remediation.action).toMatch( /call open_binary.*local path/iu, diff --git a/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts b/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts index 49754f96b3f..3f8d50cda5c 100644 --- a/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts +++ b/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts @@ -39,7 +39,11 @@ import * as regularFile from "../../../src/filesystem/RegularFile.js"; import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js"; import type { PcapCommandLauncher } from "../../../src/pcap/PcapCommand.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; -import type { PcapRequest } from "../../../src/domain/pcap/pcapAnalysis.js"; +import { + PCAP_CAPTURE_HOST_REMEDIATION, + PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, + type PcapRequest, +} from "../../../src/domain/pcap/pcapAnalysis.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; @@ -467,6 +471,8 @@ it.runIf(hasNativeBound)( it("reports a missing binary as a capability gap", async () => { const provider = new PcapProvider({ + // A supported host, so the selected tool is the reported gap. + platform: "linux", environment: { REA_TSHARK_COMMAND: "/nonexistent/tshark" }, }); expect(await provider.inspectAvailability()).toMatchObject({ @@ -525,10 +531,36 @@ it.runIf(!hasNativeBound)( expect(reason).toContain("Windows"); expect(reason).toContain("owned"); expect(reason).toContain("Job Objects"); - expect(projected.remediation.action).toBe(projected.message); + expect(projected.remediation.action).toBe(PCAP_CAPTURE_HOST_REMEDIATION); }, ); +it("refuses an unsupported host before resolving TShark, in availability and execution alike", async () => { + // Installing TShark cannot help on this host, so its absence is not reported. + const provider = new PcapProvider({ + platform: "darwin", + environment: { REA_TSHARK_COMMAND: "/nonexistent/tshark" }, + }); + onTestFinished(() => provider.close()); + expect(await provider.inspectAvailability()).toEqual({ + status: "unavailable", + code: "unsupported_host", + reason: PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, + remediation: PCAP_CAPTURE_HOST_REMEDIATION, + diagnostics: {}, + }); + const result = await provider.execute({ + operation: "inspect_pcap_capture", + input: { path: "/not-opened/capture.pcap" }, + }); + if (result.ok) throw new Error("an unsupported host admitted a capture"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "capability_unavailable", + message: PCAP_CAPTURE_UNSUPPORTED_HOST_REASON, + remediation: { action: PCAP_CAPTURE_HOST_REMEDIATION }, + }); +}); + it("retains a verification admission owner before translating cancellation", async () => { const root = await createTestTempDirectory("rea-pcap-verify-admission-"); const path = join(root, "held.bin"); @@ -620,6 +652,8 @@ it.each(["availability", "execution"] as const)( if (!allowClose) throw new Error("controlled capinfos close denial"); }); const provider = new PcapProvider({ + // A supported host, so availability resolves the selected tools. + platform: "linux", environment: { REA_TSHARK_COMMAND: missing, REA_CAPINFOS_COMMAND: capinfosStub, diff --git a/tests/composition/analysis-sessions/binarySession.test.ts b/tests/composition/analysis-sessions/binarySession.test.ts index e21872692bd..aedcb3b7989 100644 --- a/tests/composition/analysis-sessions/binarySession.test.ts +++ b/tests/composition/analysis-sessions/binarySession.test.ts @@ -1944,13 +1944,11 @@ it("requires explicit close before an external mutation of an active Ghidra sess mutate, (_value, error) => error, ); - expect(result).toMatchObject({ - ok: false, - error: { - message: expect.stringContaining( - "Close the active Ghidra session explicitly", - ), - }, + if (result.ok) throw new Error("external mutation was admitted"); + // A session precondition, not unreadable provider output. + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "capability_unavailable", + remediation: { action: expect.stringContaining("call close_binary") }, }); expect(mutate).not.toHaveBeenCalled(); expect(session.activeTarget()?.path).toBe(target);